Пример #1
0
 /// <summary>
 /// 杂项页
 /// </summary>
 /// <param name="miscService"></param>
 /// <param name="donateService"></param>
 /// <param name="hostingEnvironment"></param>
 /// <param name="httpClientFactory"></param>
 public MiscController(IMiscService miscService, IDonateService donateService, IHostingEnvironment hostingEnvironment, IHttpClientFactory httpClientFactory)
 {
     MiscService         = miscService;
     DonateService       = donateService;
     _hostingEnvironment = hostingEnvironment;
     _imagebedClient     = new ImagebedClient(httpClientFactory.CreateClient());
 }
Пример #2
0
        public Crawler Fetch()
        {
            if (!SourceUrl.IsExternalAddress() || SourceUrl.Contains(AppConfig.ImgbedDomains))
            {
                State = "INVALID_URL";
                return(this);
            }
            var request = WebRequest.Create(SourceUrl) as HttpWebRequest;

            using (var response = request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    State = "Url returns " + response.StatusCode + ", " + response.StatusDescription;
                    return(this);
                }
                if (response.ContentType.IndexOf("image") == -1)
                {
                    State = "Url is not an image";
                    return(this);
                }
                ServerUrl = PathFormatter.Format(Path.GetFileName(SourceUrl), UeditorConfig.GetString("catcherPathFormat"));

                try
                {
                    using (var stream = response.GetResponseStream())
                    {
                        var savePath = AppContext.BaseDirectory + "wwwroot" + ServerUrl;
                        using (var httpClient = new HttpClient())
                        {
                            var(url, success) = new ImagebedClient(httpClient).UploadImage(stream, savePath).Result;
                            if (success)
                            {
                                BackgroundJob.Enqueue(() => File.Delete(savePath));
                                ServerUrl = url;
                            }
                            else
                            {
                                if (!Directory.Exists(Path.GetDirectoryName(savePath)))
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(savePath));
                                }
                                using (var ms = new MemoryStream())
                                {
                                    stream.CopyTo(ms);
                                    File.WriteAllBytes(savePath, ms.GetBuffer());
                                }
                            }
                        }
                        State = "SUCCESS";
                    }
                }
                catch (Exception e)
                {
                    State = "抓取错误:" + e.Message;
                }
                return(this);
            }
        }
Пример #3
0
        public async Task <ActionResult> Edit(PostCommand post, bool reserve = true, CancellationToken cancellationToken = default)
        {
            post.Content = await ImagebedClient.ReplaceImgSrc(await post.Content.Trim().ClearImgAttributes(), cancellationToken);

            if (!ValidatePost(post, out var resultData))
            {
                return(resultData);
            }

            Post p = await PostService.GetByIdAsync(post.Id);

            if (reserve && p.Status == Status.Published)
            {
                var context = BrowsingContext.New(Configuration.Default);
                var doc1    = await context.OpenAsync(req => req.Content(p.Content), cancellationToken);

                var doc2 = await context.OpenAsync(req => req.Content(post.Content), cancellationToken);

                if (doc1.Body.TextContent != doc2.Body.TextContent)
                {
                    var history = p.Mapper <PostHistoryVersion>();
                    p.PostHistoryVersion.Add(history);
                }

                p.ModifyDate = DateTime.Now;
                var user = HttpContext.Session.Get <UserInfoDto>(SessionKey.UserInfo);
                post.Modifier      = string.IsNullOrEmpty(post.Modifier) ? user.NickName : post.Modifier;
                post.ModifierEmail = string.IsNullOrEmpty(post.ModifierEmail) ? user.Email : post.ModifierEmail;
            }

            Mapper.Map(post, p);
            p.IP = ClientIP;
            p.Seminar.Clear();
            if (!string.IsNullOrEmpty(post.Seminars))
            {
                var tmp = post.Seminars.Split(',').Distinct();
                foreach (var s in tmp)
                {
                    var seminar = await SeminarService.GetAsync(e => e.Title.Equals(s));

                    if (seminar != null)
                    {
                        p.Seminar.Add(seminar);
                    }
                }
            }

            var js = new JiebaSegmenter();

            (p.Keyword + "," + p.Label).Split(',', StringSplitOptions.RemoveEmptyEntries).ForEach(s => js.AddWord(s));
            bool b = await SearchEngine.SaveChangesAsync() > 0;

            if (!b)
            {
                return(ResultData(null, false, "文章修改失败!"));
            }

            return(ResultData(p.Mapper <PostDto>(), message: "文章修改成功!"));
        }
Пример #4
0
        public override string Process()
        {
            var file           = Request.Form.Files[UploadConfig.UploadFieldName];
            var uploadFileName = file.FileName;

            if (!CheckFileType(uploadFileName))
            {
                Result.State = UploadState.TypeNotAllow;
                return(WriteResult());
            }
            if (!CheckFileSize(file.Length))
            {
                Result.State = UploadState.SizeLimitExceed;
                return(WriteResult());
            }

            Result.OriginFileName = uploadFileName;
            var savePath  = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat);
            var localPath = AppContext.BaseDirectory + "wwwroot" + savePath;

            try
            {
                if (UploadConfig.AllowExtensions.Contains(Path.GetExtension(uploadFileName)))
                {
                    using (Stream stream = file.OpenReadStream())
                    {
                        using (var httpClient = new HttpClient())
                        {
                            var(url, success) = new ImagebedClient(httpClient).UploadImage(stream, localPath).Result;
                            if (success)
                            {
                                Result.Url = url;
                            }
                            else
                            {
                                if (!Directory.Exists(Path.GetDirectoryName(localPath)))
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(localPath));
                                }
                                File.WriteAllBytes(localPath, stream.ToByteArray());
                                Result.Url = savePath;
                            }
                        }
                    }
                }
                else
                {
                    Result.Url = savePath;
                }
                Result.State = UploadState.Success;
            }
            catch (Exception e)
            {
                Result.State        = UploadState.FileAccessError;
                Result.ErrorMessage = e.Message;
            }
            return(WriteResult());
        }
Пример #5
0
        public async Task <ActionResult> Write(PostCommand post, DateTime?timespan, bool schedule = false, CancellationToken cancellationToken = default)
        {
            post.Content = await ImagebedClient.ReplaceImgSrc(await post.Content.Trim().ClearImgAttributes(), cancellationToken);

            if (!ValidatePost(post, out var resultData))
            {
                return(resultData);
            }

            post.Status = Status.Published;
            Post p = post.Mapper <Post>();

            p.Modifier      = p.Author;
            p.ModifierEmail = p.Email;
            p.IP            = ClientIP;
            p.Rss           = p.LimitMode is null or RegionLimitMode.All;
            if (!string.IsNullOrEmpty(post.Seminars))
            {
                var tmp = post.Seminars.Split(',').Distinct();
                foreach (var s in tmp)
                {
                    var     id      = s.ToInt32();
                    Seminar seminar = await SeminarService.GetByIdAsync(id);

                    p.Seminar.Add(seminar);
                }
            }

            if (schedule)
            {
                if (!timespan.HasValue || timespan.Value <= DateTime.Now)
                {
                    return(ResultData(null, false, "如果要定时发布,请选择正确的一个将来时间点!"));
                }

                p.Status     = Status.Schedule;
                p.PostDate   = timespan.Value.ToUniversalTime();
                p.ModifyDate = timespan.Value.ToUniversalTime();
                BackgroundJob.Enqueue <IHangfireBackJob>(job => job.PublishPost(p));
                return(ResultData(p.Mapper <PostDto>(), message: $"文章于{timespan.Value:yyyy-MM-dd HH:mm:ss}将会自动发表!"));
            }

            PostService.AddEntity(p);
            var js = new JiebaSegmenter();

            (p.Keyword + "," + p.Label).Split(',', StringSplitOptions.RemoveEmptyEntries).ForEach(s => js.AddWord(s));
            bool b = await SearchEngine.SaveChangesAsync() > 0;

            if (!b)
            {
                return(ResultData(null, false, "文章发表失败!"));
            }

            return(ResultData(null, true, "文章发表成功!"));
        }
Пример #6
0
 /// <summary>
 /// 文章管理
 /// </summary>
 /// <param name="postService"></param>
 /// <param name="categoryService"></param>
 /// <param name="broadcastService"></param>
 /// <param name="seminarService"></param>
 /// <param name="postHistoryVersionService"></param>
 /// <param name="hostingEnvironment"></param>
 /// <param name="searchEngine"></param>
 public PostController(IPostService postService, ICategoryService categoryService, IBroadcastService broadcastService, ISeminarService seminarService, IPostHistoryVersionService postHistoryVersionService, IHostingEnvironment hostingEnvironment, ISearchEngine <DataContext> searchEngine, IHttpClientFactory httpClientFactory)
 {
     PostService               = postService;
     CategoryService           = categoryService;
     BroadcastService          = broadcastService;
     SeminarService            = seminarService;
     PostHistoryVersionService = postHistoryVersionService;
     _hostingEnvironment       = hostingEnvironment;
     _searchEngine             = searchEngine;
     _imagebedClient           = new ImagebedClient(httpClientFactory.CreateClient());
 }
Пример #7
0
        public Crawler Fetch()
        {
            if (!SourceUrl.IsExternalAddress())
            {
                State = "INVALID_URL";
                return(this);
            }

            using (var httpClient = new HttpClient())
            {
                var response = httpClient.GetAsync(SourceUrl).Result;
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    State = "Url returns " + response.StatusCode;
                    return(this);
                }

                ServerUrl = PathFormatter.Format(Path.GetFileName(SourceUrl), UeditorConfig.GetString("catcherPathFormat"));

                try
                {
                    using (var stream = response.Content.ReadAsStreamAsync().Result)
                    {
                        var savePath = AppContext.BaseDirectory + "wwwroot" + ServerUrl;
                        var(url, success) = new ImagebedClient(httpClient).UploadImage(stream, savePath).Result;
                        if (success)
                        {
                            ServerUrl = url;
                        }
                        else
                        {
                            if (!Directory.Exists(Path.GetDirectoryName(savePath)))
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(savePath));
                            }
                            using (var ms = new MemoryStream())
                            {
                                stream.CopyTo(ms);
                                File.WriteAllBytes(savePath, ms.GetBuffer());
                            }
                        }
                    }

                    State = "SUCCESS";
                }
                catch (Exception e)
                {
                    State = "抓取错误:" + e.Message;
                }

                return(this);
            }
        }
Пример #8
0
        public async Task <ActionResult> UploadFile([FromServices] ImagebedClient imagebedClient, IFormFile file, CancellationToken cancellationToken)
        {
            string path;
            string filename = SnowFlake.GetInstance().GetUniqueId() + Path.GetExtension(file.FileName);
            var    pathBase = CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload").Trim('/', '\\');

            switch (file.ContentType)
            {
            case var _ when file.ContentType.StartsWith("image"):
            {
                await using var stream = file.OpenReadStream();
                var(url, success)      = await imagebedClient.UploadImage(stream, file.FileName, cancellationToken);

                if (success)
                {
                    return(ResultData(url));
                }

                path = Path.Combine(HostEnvironment.WebRootPath, pathBase, "images", filename);
                var dir = Path.GetDirectoryName(path);
                Directory.CreateDirectory(dir);
                await using var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                await file.CopyToAsync(fs);

                break;
            }

            case var _ when file.ContentType.StartsWith("audio") || file.ContentType.StartsWith("video"):
                path = Path.Combine(HostEnvironment.WebRootPath, pathBase, "media", filename);

                break;

            case var _ when file.ContentType.StartsWith("text") || (ContentType.Doc + "," + ContentType.Xls + "," + ContentType.Ppt + "," + ContentType.Pdf).Contains(file.ContentType):
                path = Path.Combine(HostEnvironment.WebRootPath, pathBase, "docs", filename);

                break;

            default:
                path = Path.Combine(HostEnvironment.WebRootPath, pathBase, "files", filename);
                break;
            }
            try
            {
                await SaveFile(file, path);

                return(ResultData(path.Substring(HostEnvironment.WebRootPath.Length).Replace("\\", "/")));
            }
            catch (Exception e)
            {
                LogManager.Error(e);
                return(ResultData(null, false, "文件上传失败!"));
            }
        }
Пример #9
0
        public async Task <ActionResult> Publish(PostCommand post, [Required(ErrorMessage = "验证码不能为空")] string code, CancellationToken cancellationToken)
        {
            if (await RedisHelper.GetAsync("code:" + post.Email) != code)
            {
                return(ResultData(null, false, "验证码错误!"));
            }

            if (PostService.Any(p => p.Status == Status.Forbidden && p.Email == post.Email))
            {
                return(ResultData(null, false, "由于您曾经恶意投稿,该邮箱已经被标记为黑名单,无法进行投稿,如有疑问,请联系网站管理员进行处理。"));
            }

            var match = Regex.Match(post.Title + post.Author + post.Content, CommonHelper.BanRegex);

            if (match.Success)
            {
                LogManager.Info($"提交内容:{post.Title}/{post.Author}/{post.Content},敏感词:{match.Value}");
                return(ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请检查您的内容后尝试重新提交!"));
            }

            if (!CategoryService.Any(c => c.Id == post.CategoryId))
            {
                return(ResultData(null, message: "请选择一个分类"));
            }

            post.Label   = string.IsNullOrEmpty(post.Label?.Trim()) ? null : post.Label.Replace(",", ",");
            post.Status  = Status.Pending;
            post.Content = await ImagebedClient.ReplaceImgSrc(await post.Content.HtmlSantinizerStandard().ClearImgAttributes(), cancellationToken);

            Post p = post.Mapper <Post>();

            p.IP            = ClientIP;
            p.Modifier      = p.Author;
            p.ModifierEmail = p.Email;
            p.DisableCopy   = true;
            p.Rss           = true;
            p = PostService.AddEntitySaved(p);
            if (p == null)
            {
                return(ResultData(null, false, "文章发表失败!"));
            }

            await RedisHelper.ExpireAsync("code:" + p.Email, 1);

            var content = new Template(await new FileInfo(HostEnvironment.WebRootPath + "/template/publish.html").ShareReadWrite().ReadAllTextAsync(Encoding.UTF8))
                          .Set("link", Url.Action("Details", "Post", new { id = p.Id }, Request.Scheme))
                          .Set("time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                          .Set("title", p.Title).Render();

            BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "有访客投稿:", content, CommonHelper.SystemSettings["ReceiveEmail"], ClientIP));
            return(ResultData(p.Mapper <PostDto>(), message: "文章发表成功,待站长审核通过以后将显示到列表中!"));
        }
Пример #10
0
 /// <summary>
 /// 网站公告
 /// </summary>
 /// <param name="httpClientFactory"></param>
 public NoticeController(IHttpClientFactory httpClientFactory)
 {
     _imagebedClient = new ImagebedClient(httpClientFactory.CreateClient());
 }
Пример #11
0
 /// <summary>
 /// 文件上传
 /// </summary>
 /// <param name="HostEnvironment"></param>
 public UploadController(ImagebedClient imagebedClient)
 {
     _imagebedClient = imagebedClient;
 }
Пример #12
0
 /// <summary>
 /// 文件上传
 /// </summary>
 /// <param name="hostingEnvironment"></param>
 public UploadController(IHostingEnvironment hostingEnvironment, IHttpClientFactory httpClientFactory)
 {
     _hostingEnvironment = hostingEnvironment;
     _imagebedClient     = new ImagebedClient(httpClientFactory.CreateClient());
 }
Пример #13
0
 /// <summary>
 /// 网站公告
 /// </summary>
 /// <param name="noticeService"></param>
 /// <param name="hostingEnvironment"></param>
 public NoticeController(INoticeService noticeService, IHostingEnvironment hostingEnvironment, IHttpClientFactory httpClientFactory)
 {
     NoticeService       = noticeService;
     _hostingEnvironment = hostingEnvironment;
     _imagebedClient     = new ImagebedClient(httpClientFactory.CreateClient());
 }