public async Task WriteEntry()
        {
            var link      = new SyndicationLink(new Uri("https://contoso.com/alternate"));
            var related   = new SyndicationLink(new Uri("https://contoso.com/related"), AtomLinkTypes.Related);
            var self      = new SyndicationLink(new Uri("https://contoso.com/28af09b3"), AtomLinkTypes.Self);
            var enclosure = new SyndicationLink(new Uri("https://contoso.com/podcast"), AtomLinkTypes.Enclosure)
            {
                Title     = "Podcast",
                MediaType = "audio/mpeg",
                Length    = 4123
            };
            var source = new SyndicationLink(new Uri("https://contoso.com/source"), AtomLinkTypes.Source)
            {
                Title       = "Blog",
                LastUpdated = DateTimeOffset.UtcNow.AddDays(-10)
            };
            var author   = new SyndicationPerson("John Doe", "*****@*****.**");
            var category = new SyndicationCategory("Lorem Category");

            //
            // Construct entry
            var entry = new AtomEntry()
            {
                Id          = "https://contoso.com/28af09b3",
                Title       = "Lorem Ipsum",
                Description = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit...",
                LastUpdated = DateTimeOffset.UtcNow,
                ContentType = "text/html",
                Summary     = "Proin egestas sem in est feugiat, id laoreet massa dignissim",
                Rights      = $"copyright (c) {DateTimeOffset.UtcNow.Year}"
            };

            entry.AddLink(link);
            entry.AddLink(enclosure);
            entry.AddLink(related);
            entry.AddLink(source);
            entry.AddLink(self);

            entry.AddContributor(author);

            entry.AddCategory(category);

            //
            // Write
            var sw = new StringWriterWithEncoding(Encoding.UTF8);

            using (var xmlWriter = XmlWriter.Create(sw))
            {
                var writer = new AtomFeedWriter(xmlWriter);

                await writer.Write(entry);

                await writer.Flush();
            }

            string res = sw.ToString();

            Assert.True(CheckResult(res, $"<entry><id>{entry.Id}</id><title>{entry.Title}</title><updated>{entry.LastUpdated.ToString("r")}</updated><link href=\"{link.Uri}\" /><link title=\"{enclosure.Title}\" href=\"{enclosure.Uri}\" rel=\"{enclosure.RelationshipType}\" type=\"{enclosure.MediaType}\" length=\"{enclosure.Length}\" /><link href=\"{related.Uri}\" rel=\"{related.RelationshipType}\" /><source><title>{source.Title}</title><link href=\"{source.Uri}\" /><updated>{source.LastUpdated.ToString("r")}</updated></source><link href=\"{self.Uri}\" rel=\"{self.RelationshipType}\" /><author><name>{author.Name}</name><email>{author.Email}</email></author><category term=\"{category.Name}\" /><content type=\"{entry.ContentType}\">{entry.Description}</content><summary>{entry.Summary}</summary><rights>{entry.Rights}</rights></entry>"));
        }
Esempio n. 2
0
        public async Task <IEnumerable <AtomEntry> > GetEntries(string type, string host)
        {
            var items = new List <AtomEntry>();
            var posts = await _postProvider.GetList(new Pager(1), 0, "", "P");

            foreach (var post in posts)
            {
                var item = new AtomEntry
                {
                    Title       = post.Title,
                    Description = post.Content,
                    Id          = $"{host}/posts/{post.Slug}",
                    Published   = post.Published,
                    LastUpdated = post.Published,
                    ContentType = "html",
                };

                if (post.Categories != null && post.Categories.Count > 0)
                {
                    foreach (Category category in post.Categories)
                    {
                        item.AddCategory(new SyndicationCategory(category.Content));
                    }
                }

                item.AddContributor(new SyndicationPerson(post.Author.Email, post.Author.DisplayName));
                item.AddLink(new SyndicationLink(new Uri(item.Id)));
                items.Add(item);
            }

            return(await Task.FromResult(items));
        }
Esempio n. 3
0
        public async Task Rss(string type)
        {
            Response.ContentType = "application/xml";

            using (var xmlWriter = XmlWriter.Create(Response.Body, new XmlWriterSettings()
            {
                Async = true, Indent = true, Encoding = new UTF8Encoding(false)
            }))
            {
                var posts = await _blog.GetPosts(10);

                var writer = await GetWriter(type, xmlWriter, posts.Max(p => p.PubDate));

                foreach (var post in posts)
                {
                    var item = new AtomEntry
                    {
                        Title       = post.Title,
                        Description = post.Content,
                        Id          = $"{Request.Scheme}://{Request.Host}/read/{post.Slug}",
                        Published   = post.PubDate,
                        LastUpdated = post.LastModified,
                        ContentType = "html",
                    };

                    item.AddCategory(new SyndicationCategory(post.Category));

                    item.AddContributor(new SyndicationPerson("*****@*****.**", SiteSettings.Owner));
                    item.AddLink(new SyndicationLink(new Uri(item.Id)));

                    await writer.Write(item);
                }
            }
        }
Esempio n. 4
0
        public async Task <IEnumerable <AtomEntry> > GetEntries(string type, string host)
        {
            var items = new List <AtomEntry>();
            var posts = await _db.BlogPosts.GetList(p => p.Published > DateTime.MinValue, new Pager(1));

            foreach (var post in posts)
            {
                var item = new AtomEntry
                {
                    Title       = post.Title,
                    Description = post.Content,
                    Id          = $"{host}/posts/{post.Slug}",
                    Published   = post.Published,
                    LastUpdated = post.Published,
                    ContentType = "html",
                };

                if (!string.IsNullOrEmpty(post.Categories))
                {
                    foreach (string category in post.Categories.Split(','))
                    {
                        item.AddCategory(new SyndicationCategory(category));
                    }
                }

                item.AddContributor(new SyndicationPerson(post.Author.DisplayName, post.Author.Email));
                item.AddLink(new SyndicationLink(new Uri(item.Id)));
                items.Add(item);
            }

            return(await Task.FromResult(items));
        }
Esempio n. 5
0
        public async Task <AtomEntry> GetEntry(PostItem post, string host)
        {
            var item = new AtomEntry
            {
                Title       = post.Title,
                Description = post.Content,
                Id          = $"{host}posts/{post.Slug}",
                Published   = post.Published,
                LastUpdated = post.Published,
                ContentType = "html",
                Summary     = post.Description
            };

            if (!string.IsNullOrEmpty(post.Categories))
            {
                foreach (string category in post.Categories.Split(','))
                {
                    item.AddCategory(new SyndicationCategory(category));
                }
            }

            item.AddContributor(new SyndicationPerson(post.Author.DisplayName, post.Author.Email));
            item.AddLink(new SyndicationLink(new Uri(item.Id)));

            return(await Task.FromResult(item));
        }
Esempio n. 6
0
        public void AddLinkReturnsCorrectResult(
            AtomEntry sut,
            AtomLink newLink)
        {
            AtomEntry actual = sut.AddLink(newLink);

            var expected = sut.AsSource().OfLikeness<AtomEntry>()
                .With(x => x.Links).EqualsWhen(
                    (s, d) => sut.Links.Concat(new[] { newLink }).SequenceEqual(d.Links));
            expected.ShouldEqual(actual);
        }
Esempio n. 7
0
        public void AddLinkReturnsCorrectResult(
            AtomEntry sut,
            AtomLink newLink)
        {
            AtomEntry actual = sut.AddLink(newLink);

            var expected = sut.AsSource().OfLikeness <AtomEntry>()
                           .With(x => x.Links).EqualsWhen(
                (s, d) => sut.Links.Concat(new[] { newLink }).SequenceEqual(d.Links));

            expected.ShouldEqual(actual);
        }
Esempio n. 8
0
        public async Task Rss(string type)
        {
            try
            {
                this.Response.ContentType = "application/xml";
                var host = $"{this.Request.Scheme}://{this.Request.Host}";

                using var xmlWriter = XmlWriter.Create(
                          this.Response.Body,
                          new XmlWriterSettings()
                {
                    Async = true, Indent = true, Encoding = new UTF8Encoding(false)
                });
                var posts  = this.blog.GetPosts(10);
                var writer = await this.GetWriter(
                    type,
                    xmlWriter,
                    await posts.MaxAsync(p => p.PubDate)).ConfigureAwait(false);

                await foreach (var post in posts)
                {
                    var item = new AtomEntry
                    {
                        Title       = post.Title,
                        Description = post.Content,
                        Id          = host + post.GetLink(),
                        Published   = post.PubDate,
                        LastUpdated = post.LastModified,
                        ContentType = "html",
                    };

                    foreach (var category in post.Categories)
                    {
                        item.AddCategory(new SyndicationCategory(category));
                    }

                    // item.AddContributor(new SyndicationPerson("*****@*****.**", this.settings.Value.Owner));
                    item.AddLink(new SyndicationLink(new Uri(item.Id)));

                    await writer.Write(item).ConfigureAwait(false);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 9
0
        public async Task ExecuteResultAsync(ActionContext context)
        {
            var response = context.HttpContext.Response;
            var request  = context.HttpContext.Request;

            response.ContentType = "application/xml";

            var host = request.Scheme + "://" + request.Host;

            using (var xmlWriter = XmlWriter.Create(response.Body, new XmlWriterSettings()
            {
                Async = true, Indent = true, Encoding = new UTF8Encoding(true)
            }))
            {
                var rss = new RssFeedWriter(xmlWriter);
                await rss.WriteTitle(_options.Value.Title);

                await rss.WriteDescription(_options.Value.Description);

                await rss.WriteGenerator(_options.Value.GeneratorDescription);

                await rss.WriteValue("link", host);

                foreach (var post in _page.Items)
                {
                    var item = new AtomEntry
                    {
                        Title       = post.Title,
                        Description = post.GetContentWithoutDataSrc(),
                        Id          = post.Id.ToString(),
                        Published   = post.PublishedDate.Value,
                        LastUpdated = post.ModifiedDate,
                        ContentType = "html",
                    };

                    foreach (var tag in post.BlogStoryTags)
                    {
                        item.AddCategory(new SyndicationCategory(tag.Tag.Name));
                    }

                    item.AddContributor(new SyndicationPerson(_options.Value.AuthorName, _options.Value.FullEmail, "author"));
                    item.AddLink(new SyndicationLink(new Uri($"{host}/{post.Alias}")));

                    await rss.Write(item);
                }
            }
        }
Esempio n. 10
0
        private static Task <AtomEntry> SerializeComment(string host, Comment comment)
        {
            var item = new AtomEntry
            {
                Title       = "comment",
                Description = comment.Content,
                Id          = host + comment.ID,
                Published   = comment.PubDate,
                LastUpdated = comment.PubDate,
                ContentType = "html",
            };

            item.AddContributor(new SyndicationPerson(comment.Author, comment.Email, "Contributor"));
            item.AddLink(new SyndicationLink(new Uri(item.Id)));

            return(Task.FromResult(item));
        }
        public async Task Rss(string type)
        {
            Response.ContentType = "application/xml";
            string host = Request.Scheme + "://" + Request.Host;

            using (XmlWriter xmlWriter = XmlWriter.Create(Response.Body,
                                                          new XmlWriterSettings
            {
                Async = true,
                Indent = true,
                Encoding = new UTF8Encoding(false)
            }))
            {
                IEnumerable <Post> posts = await _blog.GetPosts(10);

                Post[] latestPosts            = posts as Post[] ?? posts.ToArray();
                ISyndicationFeedWriter writer = await GetWriter(type, xmlWriter, latestPosts.Max(p => p.PubDate));

                foreach (Post post in latestPosts)
                {
                    var item = new AtomEntry
                    {
                        Title       = post.Title,
                        Description = post.Content,
                        Id          = host + post.GetLink(),
                        Published   = post.PubDate,
                        LastUpdated = post.DateModified,
                        ContentType = "html"
                    };

                    foreach (string category in post.Categories)
                    {
                        item.AddCategory(new SyndicationCategory(category));
                    }

                    item.AddContributor(new SyndicationPerson("*****@*****.**", _settings.Value.Owner));
                    item.AddLink(new SyndicationLink(new Uri(item.Id)));

                    await writer.Write(item);
                }
            }
        }
Esempio n. 12
0
        public async Task Feed(string type)
        {
            var host = Request.Scheme + "://" + Request.Host;

            Response.ContentType = "application/xml";

            using (var xmlWriter = XmlWriter.Create(Response.Body, new XmlWriterSettings {
                Async = true, Indent = true
            }))
            {
                var blogPosts = (await _qp.ProcessAsync(new GetBlogPostsQuery())).ToList();
                var writer    = await GetWriter(type, xmlWriter, blogPosts.Max(bp => bp.ModifiedAt));

                foreach (var bp in blogPosts)
                {
                    var item = new AtomEntry
                    {
                        Title       = bp.Title,
                        Description = type.Equals("rss", StringComparison.OrdinalIgnoreCase) ? bp.Description
              : CommonMarkConverter.Convert(bp.Content),
                        Id          = host + bp.GetUrl(),
                        Published   = bp.PublishOn,
                        LastUpdated = bp.ModifiedAt,
                        ContentType = "html"
                    };

                    foreach (var c in bp.BlogPostCategory.Select(bpc => bpc.Category).ToList())
                    {
                        item.AddCategory(new SyndicationCategory(c.Name));
                    }

                    var user = await _userManager.Users.Where(u => u.Id == bp.Author.ApplicationUserId).FirstOrDefaultAsync();

                    var email = user?.Email ?? _settings.ContactEmail;

                    item.AddContributor(new SyndicationPerson(bp.Author.FirstName + " " + bp.Author.LastName, email));
                    item.AddLink(new SyndicationLink(new Uri(item.Id)));

                    await writer.Write(item);
                }
            }
        }
Esempio n. 13
0
        private async Task <AtomEntry> SerializePost(string host, Post post)
        {
            var item = new AtomEntry
            {
                Title       = post.Title,
                Description = await post.RenderContent(lazyLoad : false),
                Id          = host + post.GetLink(),
                Published   = post.PubDate,
                LastUpdated = post.LastModified,
                ContentType = "html",
            };

            foreach (string category in post.Categories)
            {
                item.AddCategory(new SyndicationCategory(category));
            }

            item.AddContributor(new SyndicationPerson(_settings.Owner, email: _settings.Email));
            item.AddLink(new SyndicationLink(new Uri(item.Id)));
            return(item);
        }
Esempio n. 14
0
        public async Task Rss(string type)
        {
            Response.ContentType = "application/xml";
            string host = Request.Scheme + "://" + Request.Host;

            using (XmlWriter xmlWriter = XmlWriter.Create(Response.Body, new XmlWriterSettings()
            {
                Async = true, Indent = true
            }))
            {
                var posts = await _blog.GetPosts(10);

                var writer = await GetWriter(type, xmlWriter, posts.Max(p => p.PubDate));

                foreach (Models.Post post in posts)
                {
                    var item = new AtomEntry
                    {
                        Title       = post.Title,
                        Description = post.Content,
                        Id          = host + post.GetLink(),
                        Published   = post.PubDate,
                        LastUpdated = post.LastModified,
                        ContentType = "html",
                    };

                    foreach (string category in post.Categories)
                    {
                        item.AddCategory(new SyndicationCategory(category));
                    }

                    item.AddContributor(new SyndicationPerson(_settings.Value.Owner, "*****@*****.**"));
                    item.AddLink(new SyndicationLink(new Uri(item.Id)));

                    await writer.Write(item);
                }
            }
        }
Esempio n. 15
0
        public async Task Rss(string type)
        {
            Response.ContentType = "application/xml";
            string host = Request.Scheme + "://" + Request.Host;

            using (XmlWriter xmlWriter = XmlWriter.Create(Response.Body, new XmlWriterSettings()
            {
                Async = true, Indent = true
            }))
            {
                var pageViewModels = await _pageService.GetAllVisibleByRangeAsync(take : 10);

                var writer = await GetWriter(type, xmlWriter, pageViewModels.Max(p => p.CreatedDateTimeInDateTime));

                foreach (var pageViewModel in pageViewModels)
                {
                    var item = new AtomEntry
                    {
                        Title       = pageViewModel.Title,
                        Description = pageViewModel.BriefDescription,
                        Id          = host + $@"/page/{pageViewModel.Id}/{pageViewModel.SlugUrl}",
                        Published   = pageViewModel.CreatedDateTimeInDateTime,
                        LastUpdated = pageViewModel.ModifiedDateTimeInDateTime ?? pageViewModel.CreatedDateTimeInDateTime,
                        ContentType = "html",
                    };

                    //foreach (string category in pageViewModel.Categories)
                    //{
                    //    item.AddCategory(new SyndicationCategory(category));
                    //}

                    item.AddContributor(new SyndicationPerson(_settings.Value.Owner, _settings.Value.Email));
                    item.AddLink(new SyndicationLink(new Uri(item.Id)));

                    await writer.Write(item);
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Invokes the middleware.
        /// </summary>
        /// <param name="context">The current HTTP context</param>
        /// <param name="blog">The blog service</param>
        public virtual async Task Invoke(HttpContext context, IBlogService blog, Db db)
        {
            var url = context.Request.Path.HasValue ?
                      context.Request.Path.Value.ToLower() : "";

            if (url.StartsWith("/feed"))
            {
                using (var xml = XmlWriter.Create(context.Response.Body, new XmlWriterSettings {
                    Async = true, Indent = true
                }))
                {
                    var host   = context.Request.Scheme + "://" + context.Request.Host;
                    var latest = await db.Posts
                                 .Where(p => p.Published <= DateTime.Now.ToUniversalTime())
                                 .MaxAsync(p => p.Published);

                    var feed = await GetWriter(xml, blog, url, host, latest);

                    if (feed != null)
                    {
                        context.Response.ContentType = "application/xml";

                        var posts = db.Posts
                                    .Include(p => p.Category)
                                    .Include(p => p.Tags)
                                    .Where(p => p.Published <= DateTime.Now.ToUniversalTime())
                                    .OrderByDescending(p => p.LastModified).ThenBy(p => p.Published);

                        foreach (Models.Post post in posts)
                        {
                            var item = new AtomEntry
                            {
                                Title       = post.Title,
                                Description = post.Body.ToHtml().Value,
                                Id          = $"{host}/{post.Slug}",
                                Published   = post.Published.Value,
                                LastUpdated = post.LastModified,
                                ContentType = "html",
                            };

                            // Add category
                            item.AddCategory(new SyndicationCategory(post.Category.Title));

                            // Add tags
                            foreach (var tag in post.Tags)
                            {
                                item.AddCategory(new SyndicationCategory(tag.Title));
                            }

                            //
                            // TODO: Post needs an author
                            //
                            item.AddContributor(new SyndicationPerson(post.Author.Name, post.Author.Email));
                            item.AddLink(new SyndicationLink(new Uri(item.Id)));

                            await feed.Write(item);
                        }
                    }
                }
            }
            await _next.Invoke(context);
        }
Esempio n. 17
0
        private async Task addEntry(FeedSource source, HtmlNode nextNode)
        {
            HtmlNode urlNode = nextNode.QuerySelector(source.Entries.Url.Selector);

            if (urlNode == null)
            {
                throw new ApplicationException("Error: Failed to match entry url selector against an element.");
            }

            string url = source.Entries.Url.Attribute == string.Empty ?
                         urlNode.InnerText : urlNode.Attributes[source.Entries.Url.Attribute].DeEntitizeValue;

            Uri       entryUri = new Uri(new Uri(source.Feed.Url), new Uri(url));
            AtomEntry nextItem = new AtomEntry()
            {
                Id          = entryUri.ToString(),
                Title       = ReferenceSubstitutor.Replace(source.Entries.Title, nextNode),
                Description = ReferenceSubstitutor.Replace(source.Entries.Content, nextNode),
                ContentType = "html"
            };

            nextItem.AddLink(new SyndicationLink(entryUri, AtomLinkTypes.Alternate));

            if (source.Entries.Published != null)
            {
                nextItem.Published = DateTime.Parse(
                    nextNode.QuerySelectorAttributeOrText(
                        source.Entries.Published
                        )
                    );
            }

            if (source.Entries.LastUpdated != null)
            {
                nextItem.LastUpdated = DateTime.Parse(
                    nextNode.QuerySelectorAttributeOrText(
                        source.Entries.LastUpdated
                        )
                    );
            }
            else if (source.Entries.Published != null)             // Use the publish date if available
            {
                nextItem.LastUpdated = nextItem.Published;
            }
            else             // It requires one, apparently
            {
                nextItem.LastUpdated = DateTimeOffset.Now;
            }


            if (source.Entries.AuthorName != null)
            {
                SyndicationPerson author = new SyndicationPerson(
                    nextNode.QuerySelectorAttributeOrText(source.Entries.AuthorName).Trim(),
                    ""
                    );
                if (source.Entries.AuthorUrl != null)
                {
                    author.Uri = nextNode.QuerySelectorAttributeOrText(source.Entries.AuthorUrl);
                }

                nextItem.AddContributor(author);
            }
            else
            {
                nextItem.AddContributor(new SyndicationPerson("Unknown", ""));
            }


            await feed.Write(nextItem);
        }
Esempio n. 18
0
        public async Task Feed(string type)
        {
            var syncIOFeature = HttpContext.Features.Get <IHttpBodyControlFeature>();

            if (syncIOFeature != null)
            {
                syncIOFeature.AllowSynchronousIO = true;
            }

            Response.ContentType = "application/xml";
            var host = $"{Request.Scheme}://{Request.Host}";

            using var xmlWriter = XmlWriter
                                  .Create(Response.Body,
                                          new XmlWriterSettings()
            {
                Async = true, Indent = true, Encoding = new UTF8Encoding(false)
            });

            var posts = await _postService.GetAll();

            ISyndicationFeedWriter writer;

            if (type?.Equals("rss", StringComparison.OrdinalIgnoreCase) ?? false)
            {
                writer = new RssFeedWriter(xmlWriter);
                await((RssFeedWriter)writer).WriteValue("link", host).ConfigureAwait(false);
                await((RssFeedWriter)writer).WriteTitle("title").ConfigureAwait(false);
                await((RssFeedWriter)writer).WriteDescription("description").ConfigureAwait(false);
                await((RssFeedWriter)writer).WriteGenerator("SharpBlog").ConfigureAwait(false);
            }
            else
            {
                writer = new AtomFeedWriter(xmlWriter);
                await((AtomFeedWriter)writer).WriteId(host).ConfigureAwait(false);
                await((AtomFeedWriter)writer).WriteTitle("titles").ConfigureAwait(false);
                await((AtomFeedWriter)writer).WriteSubtitle("description").ConfigureAwait(false);
                await((AtomFeedWriter)writer).WriteGenerator("SharpBlog", "https://github.com/sharpapp-mareklanduch/sharpblog", "1.0").ConfigureAwait(false);
                await((AtomFeedWriter)writer).WriteValue("updated",
                                                         posts
                                                         .Max(p => p.PublicationDate)
                                                         .Value
                                                         .ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture))
                .ConfigureAwait(false);
            }

            foreach (var post in posts.Where(p => p.IsPublished))
            {
                var item = new AtomEntry
                {
                    Id          = host + post.RelativeUrl,
                    Title       = post.Title,
                    Description = post.Content,
                    Published   = post.PublicationDate.Value,
                    LastUpdated = post.LastModified,
                    ContentType = "html"
                };

                foreach (var category in post.Categories)
                {
                    item.AddCategory(new SyndicationCategory(category.Name));
                }

                item.AddContributor(new SyndicationPerson("*****@*****.**", "Marek Łańduch"));
                item.AddLink(new SyndicationLink(new Uri(item.Id)));

                await writer.Write(item).ConfigureAwait(false);
            }
        }