Example #1
0
        public async Task AutoMaticallyPublishMarkdownPostsAsync(GitlabPostsNavInput input)
        {
            // var userId=  AbpSession.UserId;
            var sercertCode = _appConfiguration.GetMarkdownPostSercerCode();

            if (sercertCode.IsNullOrEmpty())
            {
                throw new UserFriendlyException("key丢失,请配置后,再提交。");
            }
            if (input.SercertCode != sercertCode)
            {
                throw new UserFriendlyException("密钥不正确,请重新提交新密钥。");
            }
            var fileContent = await _gitlabClientAppService.GetGitlabFileInfo(input);

            if (fileContent == null)
            {
                throw new UserFriendlyException($"{input.FilePath}路径下的{input.FileName}文件在Gitlab中不存在,请重试。");
            }
            var dto = JsonConvert.DeserializeObject <RepoPostsDto>(fileContent.ContentDecoded);

            if (dto.items != null)
            {
                var items = dto.items.Where(a => a.Enabled).ToList();

                if (items.Count > 0)
                {
                    //判断第一篇文章发布的博客名称
                    var blogshortName = items[0].blogShortName;

                    var blog = await _blogManager.GetByShortNameAsync(blogshortName);

                    foreach (var item in items)
                    {
                        //如果后续的文章名称和博客名称不一致则发布到新博客文章中去
                        if (item.blogShortName != blogshortName)
                        {
                            blog = await _blogManager.GetByShortNameAsync(blogshortName);
                        }

                        if (item.title.IsNullOrWhiteSpace())
                        {
                            continue;
                        }

                        input.FileName = item.path;
                        //获取文章内容
                        var itemContent = await _gitlabClientAppService.GetGitlabFileInfo(input);

                        if (itemContent == null)
                        {
                            continue;
                        }

                        var name = itemContent.Filename;

                        if (item.URL.IsNullOrEmpty())
                        {
                            item.URL = Path.GetFileNameWithoutExtension(name);
                        }

                        //转换为html内容
                        var htmlContent = _markdownConverter.ConvertToHtml(itemContent.ContentDecoded);
                        //上传图片到图床
                        htmlContent = await UploadpicturesToPictureBedAsync(htmlContent, input, item);

                        //todo find a way to make it on client in prismJS configuration (eg: map C# => csharp)
                        htmlContent = HtmlNormalizer.ReplaceCodeBlocksLanguage(
                            htmlContent,
                            "language-C#",
                            "language-csharp"
                            );
                        htmlContent = HtmlNormalizer.ReplaceCodeLinkUrl(htmlContent);
                        var tags = item.tags.Split(',');

                        var post = new CreatePostDto
                        {
                            BlogId     = blog.Id,
                            Title      = item.title,
                            Content    = htmlContent,
                            Url        = item.URL,
                            NewTags    = tags.ToList(),
                            CoverImage = item.ConverImage,
                            PostType   = PostType.Original
                        };

                        await _postAppService.CreatePostByMakrdown(post);
                    }
                }
            }
        }
        /// <summary>
        /// 上传图片到图床中
        /// </summary>
        /// <param name="content"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task <string> UploadpicturesToPictureBedAsync(string content, GitlabPostsNavInput input, PostItems postConfig)
        {
            if (content == null)
            {
                return(null);
            }

            //获取需要被图床的图片列表
            var toDoImgBedList = Regex.Matches(content, @"(<img\s+[^>]*)src=""([^""]*)""([^>]*>)", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);

            var newSourceImagesList = new List <string>();

            foreach (Match itemPic in toDoImgBedList)
            {
                //检查是否为外联,如果是外联按不处理
                if (WebUrlHelper.IsExternalLink(itemPic.Value))
                {
                    //检查图片是否为外部链接
                    return(itemPic.Value);
                }

                input.FileName = itemPic.Groups[2].Value;

                var file = await _gitlabClientAppService.GetGitlabFileInfo(input);

                if (file == null)
                {
                    continue;
                }
                //获取当前图片的base64,然后上传到图床中。

                var tags = postConfig.tags.Split(',');

                var directoryPath = $"{postConfig.blogShortName}/{tags[0]}";

                //存放的图床地址
                var pictureToBed = new UploadPictureToBed
                {
                    PathWithNamespace = "52abp/picturebed",
                    file          = file,
                    DirectoryPath = directoryPath
                };



                //上传图片到指定图床
                var imgRawUrl = await _gitlabClientAppService.UploadPictureToImgBed(pictureToBed);

                newSourceImagesList.Add(imgRawUrl);
                //install-ubuntu-1.png

                //http://code.52abp.com/52abp/picturebed/raw/master/2020/04/28/install-ubuntu-1.png
            }



            content = Regex.Replace(content, @"(<img\s+[^>]*)src=""([^""]*)""([^>]*>)", (Match match) =>
            {
                var oldImageSource = match.Groups[2].Value;

                oldImageSource = Path.GetFileName(oldImageSource);
                if (WebUrlHelper.IsExternalLink(oldImageSource))
                {
                    //检查图片是否为外部链接
                    return(match.Value);
                }

                var newImageSource = newSourceImagesList.Where(a => a.EndsWith(oldImageSource))
                                     .FirstOrDefault();

                var url = match.Groups[1] + " src=\"" + newImageSource + "\" " + match.Groups[3];
                return(url);
            }, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);

            return(content);
        }