示例#1
0
        public IActionResult Reply(int entryId, string contents)
        {
            try
            {
                var userName = User?.Identity?.Name ?? "Anonymous";
                var response = new BlogResponse()
                {
                    //Author = Username,
                    Contents     = contents,
                    BlogEntryId  = entryId,
                    ResponseDate = DateTime.Now
                };


                _blogResponseRepository.CreateBlogResponse(response);
            }

            catch (InvalidOperationException)
            {
                ViewBag.ErrorMessage = "Reply not created.";
            }


            return(RedirectToAction("Index"));
        }
示例#2
0
        public async Task <BlogResponse <string> > GenerateTokenAsync(string type, string code, string state)
        {
            var response = new BlogResponse <string>();

            if (!StateManager.IsExist(state))
            {
                response.IsFailed("Request failed.");
                return(response);
            }

            StateManager.Remove(state);

            var token = type switch
            {
                "github" => GenerateToken(await _githubService.GetUserByOAuthAsync(type, code, state)),
                "gitee" => GenerateToken(await _giteeService.GetUserByOAuthAsync(type, code, state)),
                "alipay" => GenerateToken(await _alipayService.GetUserByOAuthAsync(type, code, state)),
                "dingtalk" => GenerateToken(await _dingtalkService.GetUserByOAuthAsync(type, code, state)),
                "microsoft" => GenerateToken(await _microsoftService.GetUserByOAuthAsync(type, code, state)),
                "weibo" => GenerateToken(await _weiboService.GetUserByOAuthAsync(type, code, state)),
                "qq" => GenerateToken(await _qqService.GetUserByOAuthAsync(type, code, state)),
                _ => throw new NotImplementedException($"Not implemented:{type}")
            };

            response.IsSuccess(token);
            return(response);
        }
示例#3
0
 protected void ListViewResponses_ItemCommand(object sender, ListViewCommandEventArgs e)
 {
     if (e.CommandName == "DeleteResponse")
     {
         BlogResponse newResponse          = new BlogResponse();
         Label        blogResponseID       = (Label)e.Item.FindControl("labelResponseID");
         var          blogResponseToDelete = BlogService.GetBlogResponse(Int32.Parse(blogResponseID.Text));
         var          blogId = blogResponseToDelete.BlogID;
         var          result = BlogService.DeleteBlogResponse(blogResponseToDelete);
         if (result == true)
         {
             List <BlogResponse> blogResponses    = BlogService.GetBlogResponses(blogId);
             ListView            listViewRespones = (ListView)sender;
             listViewRespones.DataSource = blogResponses;
             listViewRespones.DataBind();
             string index = listViewRespones.ClientID.Split('_').Last();
             Label  labelNoOfResponses = (Label)ListViewBlogs.Items[Int32.Parse(index)].FindControl("labelNoOfResponses");
             labelNoOfResponses.Text = blogResponses.Count.ToString();
             LinkButton linkButtonToggleListViewResponse = (LinkButton)ListViewBlogs.Items[Int32.Parse(index)].FindControl("LinkButtonToggleListViewResponse");
             if (blogResponses.Count > 0)
             {
                 linkButtonToggleListViewResponse.Visible = true;
             }
             else
             {
                 linkButtonToggleListViewResponse.Visible = false;
             }
         }
         else
         {
         };
     }
 }
示例#4
0
        public async Task <BlogResponse <PostDetailDto> > GetPostByUrlAsync(string url)
        {
            return(await _cache.GetPostByUrlAsync(url, async() =>
            {
                var response = new BlogResponse <PostDetailDto>();

                var post = await _posts.FindAsync(x => x.Url == url);
                if (post is null)
                {
                    response.IsFailed($"The post url not exists.");
                    return response;
                }

                var previous = _posts.Where(x => x.CreatedAt > post.CreatedAt).Take(1).Select(x => new PostPagedDto
                {
                    Title = x.Title,
                    Url = x.Url
                }).FirstOrDefault();
                var next = _posts.Where(x => x.CreatedAt < post.CreatedAt).OrderByDescending(x => x.CreatedAt).Take(1).Select(x => new PostPagedDto
                {
                    Title = x.Title,
                    Url = x.Url
                }).FirstOrDefault();

                var result = ObjectMapper.Map <Post, PostDetailDto>(post);
                result.Previous = previous;
                result.Next = next;

                response.Result = result;
                return response;
            }));
示例#5
0
        public async Task <BlogResponse> ReplyAsync(string id, ReplyMessageInput input)
        {
            var response = new BlogResponse();

            var message = await _messages.FindAsync(id.ToObjectId());

            if (message is null)
            {
                response.IsFailed($"The message id not exists.");
                return(response);
            }

            var reply = message.Reply ?? new List <MessageReply>();

            reply.Add(new MessageReply
            {
                Name    = input.Name,
                Content = input.Content,
                Avatar  = input.Avatar,
                UserId  = input.UserId
            });
            message.Reply = reply;

            await _messages.UpdateAsync(message);

            return(response);
        }
示例#6
0
        public async Task <BlogResponse> DeleteAsync(string id)
        {
            var response = new BlogResponse();

            var message = await _messages.FindAsync(id.ToObjectId());

            if (message is null)
            {
                response.IsFailed($"The message id not exists.");
                return(response);
            }

            if (message.Reply is not null)
            {
                if (message.Reply.Any())
                {
                    response.IsFailed($"The reply message is not empty.");
                    return(response);
                }
            }

            await _messages.DeleteAsync(id.ToObjectId());

            return(response);
        }
示例#7
0
        public async Task <BlogResponse <List <string> > > Ip2RegionAsync(string ip)
        {
            var response = new BlogResponse <List <string> >();

            if (ip.IsNullOrEmpty())
            {
                ip = _httpContextAccessor.HttpContext.Request.Headers["X-Real-IP"].FirstOrDefault() ??
                     _httpContextAccessor.HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault() ??
                     _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            }
            else
            {
                if (!ip.IsIp())
                {
                    response.IsFailed("The ip address error.");
                    return(response);
                }
            }

            var path = Path.Combine(Directory.GetCurrentDirectory(), "Resources/ip2region.db");

            using var _search = new DbSearcher(path);
            var block = await _search.BinarySearchAsync(ip);

            var region = block.Region.Split("|").Distinct().Where(x => x != "0").ToList();

            region.AddFirst(ip);

            response.Result = region;
            return(response);
        }
示例#8
0
        public async Task <BlogResponse> CreatePostAsync(CreatePostInput input)
        {
            var response = new BlogResponse();

            var tags = await _tags.GetListAsync();

            var newTags = input.Tags.Where(item => !tags.Any(x => x.Name == item)).Select(x => new Tag
            {
                Name  = x,
                Alias = x.ToLower()
            });

            if (newTags.Any())
            {
                await _tags.InsertManyAsync(newTags);
            }

            var post = new Post
            {
                Title     = input.Title,
                Author    = input.Author,
                Url       = input.Url.GeneratePostUrl(input.CreatedAt.ToDateTime()),
                Markdown  = input.Markdown,
                Category  = await _categories.GetAsync(input.CategoryId.ToObjectId()),
                Tags      = await _tags.GetListAsync(input.Tags),
                CreatedAt = input.CreatedAt.ToDateTime()
            };
            await _posts.InsertAsync(post);

            return(response);
        }
示例#9
0
        public async Task <BlogResponse> CreateUserAsync(CreateUserInput input)
        {
            var response = new BlogResponse();

            var user = await _users.FindAsync(x => x.Username == input.Username);

            if (user is not null)
            {
                response.IsFailed("The username already exists.");
                return(response);
            }

            input.Password = input.Password.ToMd5();
            await _users.InsertAsync(new User
            {
                Username = input.Username,
                Password = input.Password,
                Type     = input.Type,
                Identity = input.Identity,
                Name     = input.Name,
                Avatar   = input.Avatar,
                Email    = input.Email
            });

            return(response);
        }
示例#10
0
        public async Task <IActionResult> CreateBlog(BlogResponse blogResponse)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View());
                }

                BlogtypeModel blogtypeModel = (BlogtypeModel)Enum.Parse(typeof(BlogtypeModel), blogResponse.BlogType);

                var blog = new Blog()
                {
                    Title       = blogResponse.Title,
                    Description = blogResponse.Description,
                    BlogType    = blogtypeModel.ToString(),
                    Content     = blogResponse.Content,
                    DateCreated = DateTime.Now
                };

                var result = await _blogInterface.CreateBlog(blog, (Request.Cookies[_configuration["ZumbaCookies:ZumbaJwt"]]).ToString());

                if (result.Code != 200)
                {
                    return(RedirectToAction("Index", "Error"));
                }

                return(RedirectToAction("Index", "Blogs"));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Error encountered in BlogsController||CreateBlog ErrorMessage: {ex.Message}");
                throw;
            }
        }
示例#11
0
        public async Task OnGetAsync(string id)
        {
            HotSources = await GetResultAsync <BlogResponse <List <HotSourceDto> > >("api/hots/source");

            Id = string.IsNullOrEmpty(id) ? HotSources.Result.FirstOrDefault().Id : id;

            Hot = await GetResultAsync <BlogResponse <HotDto> >($"api/hots/{Id}");
        }
示例#12
0
        public async Task <BlogResponse <string> > GetRandomAsync()
        {
            var response = new BlogResponse <string>();

            var saying = await _sayings.GetRandomAsync();

            response.Result = saying.Content;
            return(response);
        }
示例#13
0
        public async Task <BlogResponse <string> > GenerateAsync(GenerateSignatureInput input)
        {
            return(await _cache.GenerateAsync(input, async() =>
            {
                var response = new BlogResponse <string>();

                var ip = _httpContextAccessor.HttpContext.Request.Headers["X-Real-IP"].FirstOrDefault() ??
                         _httpContextAccessor.HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault() ??
                         _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();

                var type = Signature.KnownTypes.Dictionary.FirstOrDefault(x => x.Value == input.TypeId).Key;
                if (type.IsNullOrEmpty())
                {
                    response.IsFailed($"The signature type not exists.");
                    return response;
                }

                var signature = await _signatures.FindAsync(x => x.Name == input.Name && x.Type == type);
                if (signature is not null)
                {
                    response.Result = signature.Url;
                    return response;
                }

                var api = _signatureOptions.Urls
                          .OrderBy(x => GuidGenerator.Create())
                          .Select(x => new { Url = x.Key, Param = string.Format(x.Value, input.Name, input.TypeId) })
                          .FirstOrDefault();

                var content = new StringContent(api.Param);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                using var client = _httpClient.CreateClient();
                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0");
                var httpResponse = await client.PostAsync(api.Url, content);
                var httpResult = await httpResponse.Content.ReadAsStringAsync();

                var regex = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
                var imgUrl = regex.Match(httpResult).Groups["imgUrl"].Value;

                var url = $"{$"{input.Name}_{type}".ToMd5()}.png";
                var signaturePath = Path.Combine(_signatureOptions.Path, url);

                var imgBuffer = await client.GetByteArrayAsync(imgUrl);
                await imgBuffer.DownloadAsync(signaturePath);

                await _signatures.InsertAsync(new Signature
                {
                    Name = input.Name,
                    Type = type,
                    Url = url,
                    Ip = ip
                });

                response.Result = url;
                return response;
            }));
示例#14
0
        public async Task <BlogResponse <List <UserDto> > > GetUsersAsync()
        {
            var response = new BlogResponse <List <UserDto> >();

            var users = await _users.GetListAsync();

            var result = ObjectMapper.Map <List <User>, List <UserDto> >(users);

            response.IsSuccess(result);
            return(response);
        }
示例#15
0
        public async Task <BlogResponse <List <GetAdminFriendLinkDto> > > GetAdminFriendLinksAsync()
        {
            var response = new BlogResponse <List <GetAdminFriendLinkDto> >();

            var friendLinks = await _friendLinks.GetListAsync();

            var result = ObjectMapper.Map <List <FriendLink>, List <GetAdminFriendLinkDto> >(friendLinks);

            response.Result = result;
            return(response);
        }
示例#16
0
        public async Task <BlogResponse <string> > GenerateTokenAsync([FromServices] IUserService userService, AccountInput input)
        {
            var response = new BlogResponse <string>();

            var user = await userService.VerifyByAccountAsync(input.Username, input.Password);

            var token = GenerateToken(user);

            response.IsSuccess(token);
            return(await Task.FromResult(response));
        }
示例#17
0
        public async Task <BlogResponse <PagedList <GetAdminPostDto> > > GetAdminPostsAsync([Range(1, 100)] int page = 1, [Range(10, 100)] int limit = 10)
        {
            var response = new BlogResponse <PagedList <GetAdminPostDto> >();

            var result = await _posts.GetPagedListAsync(page, limit);

            var total = result.Item1;
            var posts = ObjectMapper.Map <List <Post>, List <GetAdminPostDto> >(result.Item2);

            response.Result = new PagedList <GetAdminPostDto>(total, posts);
            return(response);
        }
        public void CreateBlogResponse(BlogResponse response)
        {
            try
            {
                _context.BlogResponses.Add(response);
                _context.SaveChanges();
            }

            catch (Exception)
            {
            }
        }
示例#19
0
        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();
            var env = context.GetEnvironment();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
                ForwardLimit     = null
            });
            app.UseHealthChecks("/api/meowv/health", new HealthCheckOptions
            {
                ResponseWriter = (context, healthReport) =>
                {
                    context.Response.ContentType = "application/json;charset=utf-8";
                    context.Response.StatusCode  = StatusCodes.Status200OK;

                    var result = healthReport.Entries.Select(x => new NameValue
                    {
                        Name  = x.Key,
                        Value = x.Value.Status.ToString()
                    });

                    var response = new BlogResponse <IEnumerable <NameValue> >();
                    response.IsSuccess(result);

                    return(context.Response.WriteAsJsonAsync(response));
                }
            });
            app.UseHsts();
            app.UseRouting();
            app.UseCors(AppOptions.Cors.PolicyName);
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.HeadContent = @"<style>.opblock-summary-description{font-weight: bold;text-align: right;}</style>";
                options.SwaggerEndpoint($"/swagger/{AppOptions.Swagger.Name}/swagger.json", AppOptions.Swagger.Title);
                options.DefaultModelsExpandDepth(-1);
                options.DocExpansion(DocExpansion.None);
                options.RoutePrefix   = AppOptions.Swagger.RoutePrefix;
                options.DocumentTitle = AppOptions.Swagger.DocumentTitle;
            });
            app.UseAuditing();
            app.UseAbpSerilogEnrichers();
            app.UseConfiguredEndpoints();
        }
示例#20
0
        public async Task <BlogResponse <PagedList <MessageDto> > > GetMessagesAsync(int page, int limit)
        {
            var response = new BlogResponse <PagedList <MessageDto> >();

            var result = await _messages.GetPagedListAsync(page, limit);

            var total    = result.Item1;
            var messages = ObjectMapper.Map <List <Message>, List <MessageDto> >(result.Item2);

            response.Result = new PagedList <MessageDto>(total, messages);
            return(response);
        }
示例#21
0
        public async Task <BlogResponse <PagedList <SayingDto> > > GetSayingsAsync(int page, int limit)
        {
            var response = new BlogResponse <PagedList <SayingDto> >();

            var result = await _sayings.GetPagedListAsync(page, limit);

            var total   = result.Item1;
            var sayings = ObjectMapper.Map <List <Saying>, List <SayingDto> >(result.Item2);

            response.Result = new PagedList <SayingDto>(total, sayings);
            return(response);
        }
示例#22
0
        public async Task <BlogResponse> SendMessageAsync(SendMessageInput input)
        {
            var response = new BlogResponse();

            var content = new StringContent($"text={input.Text}&desp={input.Desc}");

            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

            using var client = _httpClient.CreateClient();
            await client.PostAsync($"https://sc.ftqq.com/{_appOptions.ScKey}.send", content);

            return(response);
        }
示例#23
0
        public async Task <BlogResponse <List <HotSourceDto> > > GetSourcesAsync()
        {
            return(await _cache.GetSourcesAsync(async() =>
            {
                var response = new BlogResponse <List <HotSourceDto> >();

                var hots = await _hots.GetSourcesAsync();
                var result = ObjectMapper.Map <List <Hot>, List <HotSourceDto> >(hots);

                response.Result = result;
                return response;
            }));
        }
示例#24
0
        public async Task <BlogResponse <PushUrlsCacheResponse> > PushCdnUrlsAsync(List <string> urls)
        {
            var result = new BlogResponse <PushUrlsCacheResponse>();

            var parameters = new { Urls = urls }.SerializeToJson();

            DoCdnAction(out CdnClient client, out PushUrlsCacheRequest req, parameters);

            var resp = await client.PushUrlsCache(req);

            result.IsSuccess(resp);
            return(result);
        }
示例#25
0
        public async Task <BlogResponse <Tuple <int, int, int> > > GetStatisticsAsync()
        {
            var response = new BlogResponse <Tuple <int, int, int> >();

            var postCount = await _posts.GetCountAsync();

            var categoryCount = await _categories.GetCountAsync();

            var tagCount = await _tags.GetCountAsync();

            response.Result = new Tuple <int, int, int>(postCount.To <int>(), categoryCount.To <int>(), tagCount.To <int>());
            return(response);
        }
示例#26
0
        public async Task <BlogResponse> SendMessageAsync(SendMessageInput input)
        {
            var response = new BlogResponse();

            var content = new StringContent($"text={input.Text}&desp={input.Desc}");

            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

            using var client = _httpClient.CreateClient();
            await client.PostAsync("https://sc.ftqq.com/SCU60393T5a94df1d5a9274125293f34a6acf928f5d78f551cf6d6.send", content);

            return(response);
        }
示例#27
0
        public async Task <BlogResponse <PurgePathCacheResponse> > PurgeCdnPathsAsync(List <string> paths)
        {
            var result = new BlogResponse <PurgePathCacheResponse>();

            var parameters = new { Paths = paths, FlushType = "flush" }.SerializeToJson();

            DoCdnAction(out CdnClient client, out PurgePathCacheRequest req, parameters);

            var resp = await client.PurgePathCache(req);

            result.IsSuccess(resp);
            return(result);
        }
示例#28
0
        public async Task <BlogResponse> SendMessageAsync(SendMessageInput input)
        {
            var response = new BlogResponse();

            var content = new StringContent($"text={input.Text}&desp={input.Desc}");

            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

            using var client = _httpClient.CreateClient();
            _logger.LogInformation($"FtqqUrl: {_notificationOptions.FtqqUrl}");
            await client.PostAsync(_notificationOptions.FtqqUrl, content);

            return(response);
        }
示例#29
0
        public async Task <BlogResponse <List <FriendLinkDto> > > GetFriendLinksAsync()
        {
            return(await _cache.GetFriendLinksAsync(async() =>
            {
                var response = new BlogResponse <List <FriendLinkDto> >();

                var friendLinks = await _friendLinks.GetListAsync();

                var result = ObjectMapper.Map <List <FriendLink>, List <FriendLinkDto> >(friendLinks);

                response.Result = result;
                return response;
            }));
        }
示例#30
0
        public async Task <BlogResponse <UserDto> > GetCurrentUserAsync()
        {
            var response = new BlogResponse <UserDto>();

            var claim = _principalAccessor.Principal.Claims?.FirstOrDefault((Claim c) => c.Type == ClaimTypes.NameIdentifier);

            if (claim == null || claim.Value.IsNullOrWhiteSpace())
            {
                response.IsFailed("Unauthorized.");
                return(response);
            }

            return(await GetUserAsync(claim.Value));
        }
        public override bool DeleteBlogResponse(BlogResponse blogResponse)
        {
            var blogResponseToDelete = (from b in db.BlogResponses
                                        where (b.BlogResponseID == blogResponse.BlogResponseID)
                                        select b).FirstOrDefault();

            if (blogResponseToDelete == null)
                return false;
            else
            {
                db.BlogResponses.DeleteOnSubmit(blogResponseToDelete);
                db.SubmitChanges();
                return true;
            }
        }
示例#32
0
        public List<BlogResponse> GetBlogs()
        {
            List<BlogResponse> responses = new List<BlogResponse>();

            using (BlogEntities data = new BlogEntities())
            {
                List<Blog> blogs = data.BlogPosts.ToList();

                foreach (Blog b in blogs)
                {
                    BlogResponse br = new BlogResponse();
                    br.Blogs.Add(new BlogObject(b.Id, b.Name));
                    br.Success = true;

                    responses.Add(br);
                }
            }

            return responses;
        }
示例#33
0
 public abstract bool DeleteBlogResponse(BlogResponse blogResponse);
示例#34
0
 public static void PostBlogResponse(BlogResponse blogResponse)
 {
     LoadProviders();
     _provider.PostBlogResponse(blogResponse);
 }
示例#35
0
 public static bool DeleteBlogResponse(BlogResponse blogResponse)
 {
     LoadProviders();
     return _provider.DeleteBlogResponse(blogResponse);
 }
示例#36
0
 public abstract void PostBlogResponse(BlogResponse blogResponse);
 public override void PostBlogResponse(BlogResponse blogResponse)
 {
     MembershipUser currentUser = Membership.GetUser(blogResponse.UserName);
     IITBlog.Classes.BlogResponse newBlogResponse = new IITBlog.Classes.BlogResponse
     {
         BlogID = blogResponse.BlogID,
         UserName = blogResponse.UserName,
         RecCreation = blogResponse.RecCreation,
         IP = blogResponse.IPAddress,
         Response = blogResponse.ResponseText
     };
     db.BlogResponses.InsertOnSubmit(newBlogResponse);
     db.SubmitChanges();
 }