Esempio n. 1
0
 public Cache(IDatabase cache) : base(cache)
 {
     KeyFn = query =>
     {
         return(CacheKeyBuilder.Build <GetJobs, Query>(query, m => m.UserId, m => m.PaginationParams.Page, m => m.PaginationParams.PerPage));
     };
 }
Esempio n. 2
0
        private async Task UpdateMemoryPostsAsync()
        {
            var memPosts  = GetPosts();
            var filePosts = await GetPostsFromFileAsync();

            var posts = new List <BlogPost>();

            foreach (var filePost in filePosts)
            {
                if (StringEqualsHelper.IgnoreCase(filePost.GitHubPath, BlogConstant.TemplatePostGitHubPath))
                {
                    continue;
                }

                var memPost = memPosts.FirstOrDefault(p =>
                                                      StringEqualsHelper.IgnoreCase(p.Link, filePost.Link));
                if (memPost != null)
                {
                    filePost.Visits = Math.Max(filePost.Visits, memPost.Visits);
                }

                posts.Add(filePost);
            }

            _memoryCacheClient.Set(CacheKeyBuilder.Build(SiteComponent.Blog, "post", "all"), posts);
        }
Esempio n. 3
0
    public IActionResult Sitemap()
    {
        var sitemap = _cacheClient.GetOrCreate(CacheKeyBuilder.Build(nameof(HomeController), nameof(Sitemap)),
                                               () =>
        {
            var sb = new StringBuilder();
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.AppendLine("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");
            sb.AppendLine(
                $"<url><loc>{_blogOptions.BlogRemoteEndpoint}</loc><lastmod>{DateTime.Now.ToDate()}</lastmod><changefreq>daily</changefreq><priority>1.0</priority></url>");
            sb.AppendLine(
                $"<url><loc>{_blogOptions.BlogRemoteEndpoint}/read</loc><lastmod>{DateTime.Now.ToDate()}</lastmod><changefreq>daily</changefreq><priority>0.9</priority></url>");
            sb.AppendLine(
                $"<url><loc>{_blogOptions.BlogRemoteEndpoint}/about</loc><lastmod>{DateTime.Now.ToDate()}</lastmod><changefreq>daily</changefreq><priority>0.9</priority></url>");
            sb.AppendLine(
                $"<url><loc>{_blogOptions.BlogRemoteEndpoint}/archive</loc><lastmod>{DateTime.Now.ToDate()}</lastmod><changefreq>daily</changefreq><priority>0.8</priority></url>");
            sb.AppendLine(
                $"<url><loc>{_blogOptions.BlogRemoteEndpoint}/tag</loc><lastmod>{DateTime.Now.ToDate()}</lastmod><changefreq>daily</changefreq><priority>0.8</priority></url>");

            foreach (var post in _blogService.GetAllPosts().Where(x => x.Raw.IsPostPublished()))
            {
                sb.AppendLine(
                    $"<url><loc>{post.Raw.GetFullPath(_blogOptions.BlogRemoteEndpoint)}</loc><lastmod>{post.Raw.LastUpdateTime.ToDate()}</lastmod><changefreq>daily</changefreq><priority>0.6</priority></url>");
            }

            sb.AppendLine("</urlset>");
            return(sb.ToString());
        });

        return(Content(sitemap, "text/xml", Encoding.UTF8));
    }
Esempio n. 4
0
    public IActionResult Index()
    {
        var authenticated = User.Identity?.IsAuthenticated ?? false;
        var viewModel     = _cacheClient.GetOrCreate(
            CacheKeyBuilder.Build(nameof(ArchiveController), nameof(Index), authenticated),
            () =>
        {
            var posts = _blogService.GetAllPosts().Where(x => x.Raw.IsPostPublished() || authenticated)
                        .ToList();
            var model = new List <PostArchiveViewModel>();
            foreach (var item in posts.GroupBy(x => x.Raw.PublishTime.Year).OrderByDescending(y => y.Key))
            {
                var archiveViewModel = new PostArchiveViewModel
                {
                    Count = item.Count(),
                    Posts = item.ToList(),
                    Link  = $"{item.Key}",
                    Name  = $"{item.Key}年"
                };

                model.Add(archiveViewModel);
            }

            return(model);
        });

        ViewData["Title"]       = "存档";
        ViewData["Image"]       = $"{_blogOptions.BlogRemoteEndpoint}/archive.png";
        ViewData["Description"] = "所有文章的存档。";
        return(View("Index", viewModel));
    }
Esempio n. 5
0
 public Cache(IDatabase cache) : base(cache)
 {
     KeyFn = query =>
     {
         return(CacheKeyBuilder.Build <GetChats, Query>(query, m => m.UserId));
     };
 }
Esempio n. 6
0
        public List <BlogTag> GetTags()
        {
            if (!_memoryCacheClient.TryGet <List <BlogTag> >(CacheKeyBuilder.Build(SiteComponent.Blog, "tag", "all"), out var tags))
            {
                tags = new List <BlogTag>();
            }

            return(tags);
        }
Esempio n. 7
0
        public List <BlogCategory> GetCategories()
        {
            if (!_memoryCacheClient.TryGet <List <BlogCategory> >(CacheKeyBuilder.Build(SiteComponent.Blog, "category", "all"), out var categories))
            {
                categories = new List <BlogCategory>();
            }

            return(categories);
        }
Esempio n. 8
0
        public List <BlogPost> GetPosts()
        {
            if (!_memoryCacheClient.TryGet <List <BlogPost> >(CacheKeyBuilder.Build(SiteComponent.Blog, "post", "all"), out var posts))
            {
                posts = new List <BlogPost>();
            }

            return(posts);
        }
Esempio n. 9
0
        private async Task UpdateMemoryAboutAsync()
        {
            var zhAbout = await GetAboutFromFileAsync(RequestLang.Chinese);

            _memoryCacheClient.Set(CacheKeyBuilder.Build(SiteComponent.Blog, "about", RequestLang.Chinese), zhAbout);

            var enAbout = await GetAboutFromFileAsync(RequestLang.English);

            _memoryCacheClient.Set(CacheKeyBuilder.Build(SiteComponent.Blog, "about", RequestLang.English), enAbout);
        }
Esempio n. 10
0
        public string GetAboutHtml(RequestLang lang = RequestLang.Chinese)
        {
            var cacheKey = CacheKeyBuilder.Build(SiteComponent.Blog, "about", lang);

            if (!_memoryCacheClient.TryGet <string>(cacheKey, out var html))
            {
                html = string.Empty;
            }

            return(html);
        }
Esempio n. 11
0
    public IActionResult Rss()
    {
        var rss = _cacheClient.GetOrCreate(CacheKeyBuilder.Build(nameof(HomeController), nameof(Rss)), () =>
        {
            var feed = new SyndicationFeed(Constants.BlogTitle, Constants.BlogDescription,
                                           new Uri($"{_blogOptions.BlogRemoteEndpoint}/rss"),
                                           Constants.ApplicationName, DateTimeOffset.UtcNow)
            {
                Copyright = new TextSyndicationContent(
                    $"&#x26;amp;#169; {DateTime.Now.Year} {_blogOptions.AdminChineseName}")
            };
            feed.Authors.Add(new SyndicationPerson(_blogOptions.AdminEmail,
                                                   _blogOptions.AdminChineseName,
                                                   _blogOptions.BlogRemoteEndpoint));
            feed.BaseUri  = new Uri(_blogOptions.BlogRemoteEndpoint);
            feed.Language = "zh-cn";
            var items     = new List <SyndicationItem>();
            foreach (var post in _blogService.GetAllPosts().Where(x => x.Raw.IsPostPublished()))
            {
                items.Add(new SyndicationItem(post.Raw.Title, post.HtmlContent,
                                              new Uri(post.Raw.GetFullPath(_blogOptions.BlogRemoteEndpoint)),
                                              post.Raw.GetFullPath(_blogOptions.BlogRemoteEndpoint),
                                              new DateTimeOffset(post.Raw.LastUpdateTime, TimeSpan.FromHours(8))));
            }

            feed.Items   = items;
            var settings = new XmlWriterSettings
            {
                Encoding            = Encoding.UTF8,
                NewLineHandling     = NewLineHandling.Entitize,
                NewLineOnAttributes = false,
                Async  = true,
                Indent = true
            };

            using var ms = new MemoryStream();
            using (var xmlWriter = XmlWriter.Create(ms, settings))
            {
                var rssFormatter = new Rss20FeedFormatter(feed, false);
                rssFormatter.WriteTo(xmlWriter);
                xmlWriter.Flush();
            }

            return(Encoding.UTF8.GetString(ms.ToArray()));
        });

        return(Content(rss, "application/rss+xml", Encoding.UTF8));
    }
Esempio n. 12
0
    public IActionResult Index([FromQuery] int page)
    {
        var authenticated = User.Identity?.IsAuthenticated ?? false;
        var viewModel     = _cacheClient.GetOrCreate(
            CacheKeyBuilder.Build(nameof(HomeController), nameof(Index), page, authenticated),
            () =>
        {
            var posts =
                _blogService.GetAllPosts().Where(x => x.Raw.IsPostPublished() || authenticated).ToList();
            var toppedPosts = posts.Where(x => x.Raw.IsTopping).ToList();
            foreach (var blogPost in toppedPosts)
            {
                posts.Remove(blogPost);
            }

            posts.InsertRange(0, toppedPosts);

            var postsPerPage = Convert.ToInt32(_blogOptions.PostsPerPage);
            var model        = new PagedViewModel <PostViewModel>(page, posts.Count, postsPerPage)
            {
                Url = Request.Path
            };

            foreach (var blogPost in posts.Chunk(postsPerPage).ElementAtOrDefault(model.CurrentPage - 1) ??
                     Enumerable.Empty <BlogPostRuntime>())
            {
                var postViewModel = new PostViewModel {
                    Current = blogPost
                };
                postViewModel.SetAdditionalInfo();
                model.Items.Add(postViewModel);
            }

            return(model);
        });

        if (viewModel.CurrentPage > 1)
        {
            ViewData["RobotsEnabled"] = false;
            ViewData["Title"]         = $"首页:第{viewModel.CurrentPage}页";
        }

        return(View(viewModel));
    }
Esempio n. 13
0
    public IActionResult Index()
    {
        var authenticated = User.Identity?.IsAuthenticated ?? false;
        var model         = _cacheClient.GetOrCreate(
            CacheKeyBuilder.Build(nameof(ReadController), nameof(Index), authenticated),
            () =>
        {
            var viewModels = new List <ReadItemViewModel>();
            var posts      = _blogService.GetAllPosts().Where(x => authenticated || x.Raw.IsPostPublished())
                             .ToList();
            foreach (var item in _blogService.GetReadItems().Where(x => authenticated || x.Raw.IsPublished)
                     .GroupBy(x => x.Raw.StartTime.Year))
            {
                var viewModel = new ReadItemViewModel
                {
                    Count = item.Count(),
                    Id    = $"year-{item.Key:D4}",
                    Title = $"{item.Key} 年"
                };

                foreach (var readItem in item)
                {
                    if (!string.IsNullOrEmpty(readItem.Raw.BlogPostLink))
                    {
                        var post = posts.FirstOrDefault(x =>
                                                        StringUtil.EqualsIgnoreCase(readItem.Raw.BlogPostLink, x.Raw.Link));
                        readItem.Raw.BlogPostLink = post?.Raw.GetFullPath(_blogOptions.BlogRemoteEndpoint);
                        readItem.BlogPostTitle    = post?.Raw.Title;
                    }
                }

                viewModel.Items.AddRange(item);
                viewModels.Add(viewModel);
            }

            return(viewModels);
        });

        return(View(model));
    }
Esempio n. 14
0
    public IActionResult About()
    {
        var authenticated = User.Identity?.IsAuthenticated ?? false;
        var viewModel     = _cacheClient.GetOrCreate(
            CacheKeyBuilder.Build(nameof(HomeController), nameof(About), authenticated),
            () =>
        {
            var posts = _blogService.GetAllPosts().Where(x => x.Raw.IsPostPublished() || authenticated)
                        .ToList();
            var topTags = new Dictionary <BlogTag, int>();
            foreach (var tag in _blogService.GetAllTags())
            {
                var count = posts.Count(x =>
                                        x.Raw.Tag.Contains(tag.Id, StringComparer.InvariantCultureIgnoreCase));
                topTags.Add(tag, count);
            }

            var postsPerPage = Convert.ToInt32(_blogOptions.PostsPerPage);
            var model        = new AboutViewModel
            {
                LatestPostRuntime     = posts.FirstOrDefault(),
                PostTotalAccessCount  = posts.Sum(p => p.GetAccessCount()).ToThousandHuman(),
                PostTotalCount        = posts.Count.ToString(),
                TopPosts              = posts.OrderByDescending(p => p.GetAccessCount()).Take(postsPerPage),
                SystemAppVersion      = _blogOptions.AppVersion,
                SystemDotNetVersion   = _blogOptions.RuntimeVersion,
                SystemLastBoot        = _blogService.BootTime.ToChinaDateAndTime(),
                SystemRunningInterval = (DateTime.Now - _blogService.BootTime).ToHuman(),
                TagTotalCount         = _blogService.GetAllTags().Count.ToString(),
                TopTags = topTags.OrderByDescending(x => x.Value).Take(postsPerPage)
                          .ToDictionary(x => x.Key, x => x.Value)
            };

            return(model);
        });


        return(View("~/Views/About/Index.cshtml", viewModel));
    }
Esempio n. 15
0
    public IActionResult Post([FromRoute] string link)
    {
        var authenticated = User.Identity?.IsAuthenticated ?? false;
        var viewModel     = _cacheClient.GetOrCreate(
            CacheKeyBuilder.Build(nameof(HomeController), nameof(Post), authenticated, link),
            () =>
        {
            var post = _blogService.GetAllPosts().FirstOrDefault(x =>
                                                                 StringUtil.EqualsIgnoreCase(x.Raw.Link, link) &&
                                                                 (x.Raw.IsPostPublished() || authenticated));
            if (post == null)
            {
                return(null);
            }

            var previousPost = _blogService.GetAllPosts()
                               .FirstOrDefault(x => x.Raw.PublishTime < post.Raw.PublishTime);
            var nextPost = _blogService.GetAllPosts()
                           .LastOrDefault(x => x.Raw.PublishTime > post.Raw.PublishTime);
            var model = new PostViewModel
            {
                Current  = post,
                Previous = previousPost,
                Next     = nextPost
            };
            model.SetAdditionalInfo();
            return(model);
        });

        if (viewModel == null)
        {
            return(NotFound());
        }

        _blogService.EnqueuePostAccess(viewModel.Current.Raw.Link);
        return(View("Index", viewModel));
    }
Esempio n. 16
0
    public IActionResult Index()
    {
        var authenticated = User.Identity?.IsAuthenticated ?? false;
        var viewModel     = _cacheClient.GetOrCreate(
            CacheKeyBuilder.Build(nameof(HomeController), nameof(Index), authenticated),
            () =>
        {
            var posts = _blogService.GetAllPosts().Where(x => x.Raw.IsPostPublished() || authenticated)
                        .ToList();
            var model = new List <PostArchiveViewModel>();

            foreach (var blogTag in _blogService.GetAllTags())
            {
                var tagPosts = posts.Where(x => x.Raw.Tag.Contains(blogTag.Id)).ToList();
                if (tagPosts.Any())
                {
                    var archiveViewModel = new PostArchiveViewModel
                    {
                        Count = tagPosts.Count,
                        Posts = tagPosts.ToList(),
                        Link  = $"{blogTag.Link}",
                        Name  = $"{blogTag.DisplayName}"
                    };

                    model.Add(archiveViewModel);
                }
            }

            return(model);
        });

        ViewData["Title"]       = "标签";
        ViewData["Image"]       = $"{_blogOptions.BlogRemoteEndpoint}/archive.png";
        ViewData["Description"] = "所有标签的存档。";
        return(View(viewModel));
    }
Esempio n. 17
0
        private async Task UpdateMemoryTagsAsync()
        {
            var tags = await GetTagsFromFileAsync();

            _memoryCacheClient.Set(CacheKeyBuilder.Build(SiteComponent.Blog, "tag", "all"), tags);
        }
Esempio n. 18
0
        private async Task UpdateMemoryCategoriesAsync()
        {
            var categories = await GetCategoriesFromFileAsync();

            _memoryCacheClient.Set(CacheKeyBuilder.Build(SiteComponent.Blog, "category", "all"), categories);
        }