Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Карпов ФТ-302 #36

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57,072 changes: 49,530 additions & 7,542 deletions BadNews/.db/news.txt

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions BadNews/BadNews.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="5.0.3" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="5.0.4" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />
</ItemGroup>
Expand Down
71 changes: 71 additions & 0 deletions BadNews/BlazorComponents/Comments.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
@using BadNews.Repositories.Comments
@using Microsoft.AspNetCore.SignalR.Client
@inject CommentsRepository commentsRepository;
@inject NavigationManager navigationManager
@implements IAsyncDisposable
<div>
<label>
Пользователь: <input @bind="userInput"/>
</label>
<label>
Сообщение: <input @bind="messageInput"/>
</label>
<div>
<button @onclick="Send">Отправить</button>
</div>
@foreach (var comment in comments)
{
<li>@RenderComment(comment)</li>
}
</div>

@code {
private HubConnection hubConnection;
private List<Comment> comments = new();

private string userInput;
private string messageInput;

[Parameter]
public Guid ArticleId { get; set; }

public override Task SetParametersAsync(ParameterView parameters)
{
comments = commentsRepository.GetComments(ArticleId).ToList();
return base.SetParametersAsync(parameters);
}

protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(navigationManager.ToAbsoluteUri("/commentsHub"))
.Build();

hubConnection.On<string, string>("ReceiveComment", (user, message) =>
{
var comment = new Comment(user, message);
comments.Add(comment);
StateHasChanged();
});

await hubConnection.StartAsync().ConfigureAwait(false);
}

private async Task Send()
{
if (hubConnection is not null)
{
await hubConnection.SendAsync("SendComment", userInput, messageInput);
}
}

public async ValueTask DisposeAsync()
{
if (hubConnection is not null)
{
await hubConnection.DisposeAsync();
}
}

private string RenderComment(Comment comment) => $"{comment.User} говорит: {comment.Value}";
}
38 changes: 38 additions & 0 deletions BadNews/Controllers/CommentsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System;
using System.Linq;
using BadNews.Models.Comments;
using BadNews.Repositories.Comments;
using Microsoft.AspNetCore.Mvc;

namespace BadNews.Controllers
{
[ApiController]
public class CommentsController : ControllerBase
{
private readonly CommentsRepository commentsRepository;

public CommentsController(CommentsRepository commentsRepository)
{
this.commentsRepository = commentsRepository;
}

// GET
[HttpGet("api/news/{id}/comments")]
public ActionResult<CommentsDto> GetCommentsForNews(Guid newsId)
{
return new CommentsDto
{
Comments = commentsRepository
.GetComments(newsId)
.Select(x =>
new CommentDto
{
User = x.User,
Value = x.Value,
})
.ToArray(),
NewsId = newsId
};
}
}
}
13 changes: 13 additions & 0 deletions BadNews/Hubs/CommentsHub.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

namespace BadNews.Hubs
{
public class CommentsHub: Hub
{
public async Task SendComment(string user, string message)
{
await Clients.All.SendAsync("ReceiveComment", user, message).ConfigureAwait(false);
}
}
}
9 changes: 9 additions & 0 deletions BadNews/Models/Comments/CommentDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace BadNews.Models.Comments
{
public class CommentDto
{
public string User { get; set; }

public string Value { get; set; }
}
}
13 changes: 13 additions & 0 deletions BadNews/Models/Comments/CommentsDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using BadNews.Repositories.Comments;

namespace BadNews.Models.Comments
{
public class CommentsDto
{
public Guid NewsId { get; set; }

public IReadOnlyCollection<CommentDto> Comments { get; set; }
}
}
20 changes: 8 additions & 12 deletions BadNews/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
using Microsoft.Extensions.Hosting;
using Serilog;
using System;
using BadNews.Hubs;
using BadNews.Repositories.Comments;

namespace BadNews
{
Expand All @@ -34,6 +36,7 @@ public void ConfigureServices(IServiceCollection services)
services.AddSingleton<INewsModelBuilder, NewsModelBuilder>();
services.AddSingleton<IValidationAttributeAdapterProvider, StopWordsAttributeAdapterProvider>();
services.AddSingleton<IWeatherForecastRepository, WeatherForecastRepository>();
services.AddSingleton<CommentsRepository>();
services.Configure<OpenWeatherOptions>(configuration.GetSection("OpenWeather"));
services.AddResponseCompression(options =>
{
Expand All @@ -43,6 +46,8 @@ public void ConfigureServices(IServiceCollection services)
var mvcBuilder = services.AddControllersWithViews();
if (env.IsDevelopment())
mvcBuilder.AddRazorRuntimeCompilation();
services.AddSignalR();
services.AddServerSideBlazor();
}

// В этом методе конфигурируется последовательность обработки HTTP-запроса
Expand All @@ -55,18 +60,7 @@ public void Configure(IApplicationBuilder app)

app.UseHttpsRedirection();
app.UseResponseCompression();
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = options =>
{
options.Context.Response.GetTypedHeaders().CacheControl =
new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
{
Public = false,
MaxAge = TimeSpan.FromDays(1)
};
}
});
app.UseStaticFiles();
app.UseSerilogRequestLogging();
app.UseStatusCodePagesWithReExecute("/StatusCode/{0}");

Expand All @@ -80,6 +74,8 @@ public void Configure(IApplicationBuilder app)
action = "StatusCode"
});
endpoints.MapControllerRoute("default", "{controller=News}/{action=Index}/{id?}");
endpoints.MapHub<CommentsHub>("/commentsHub");
endpoints.MapBlazorHub();
});
app.MapWhen(context => context.Request.IsElevated(), branchApp =>
{
Expand Down
17 changes: 14 additions & 3 deletions BadNews/Views/News/FullArticle.cshtml
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
@using BadNews.Elevation
@using BadNews.BlazorComponents
@using BadNews.Components
@using Microsoft.AspNetCore.Mvc.TagHelpers
@model BadNews.Models.News.FullArticleModel

<script src="/lib/jquery/dist/jquery.min.js"></script>
<script src="/js/signalr/dist/browser/signalr.js"></script>

<main role="main" class="container">
<div class="row">
<div class="col-md-8 news-main">
Expand All @@ -11,12 +17,17 @@
</p>
@if (ViewContext.IsElevated())
{
<form class="mb-4" onsubmit="return confirm('Удалить новость?')"
asp-controller="Editor" asp-action="DeleteArticle" asp-route-id="@(Model.Article.Id)">
<form
class="mb-4"
onsubmit="return confirm('Удалить новость?')"
asp-controller="Editor"
asp-action="DeleteArticle"
asp-route-id="@(Model.Article.Id)">
<button type="submit" class="btn-danger">Удалить</button>
</form>
}
@Html.Raw(Model.Article.ContentHtml)
@(await Html.RenderComponentAsync<Comments>(RenderMode.ServerPrerendered))
</div>
</div>

Expand All @@ -31,4 +42,4 @@
<p>
<a href="#">Наверх</a>
</p>
</footer>
</footer>
6 changes: 5 additions & 1 deletion BadNews/Views/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
@using BadNews.Elevation

<base href="~/" />
<!DOCTYPE html>
<html lang="ru">
<head>
Expand Down Expand Up @@ -28,10 +30,12 @@
</div>

@RenderBody()

<script src="/lib/jquery/dist/jquery.min.js" asp-append-version="true"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.bundle.js" asp-append-version="true"></script>
<script src="/js/site.js" asp-append-version="true"></script>
<partial name="_ValidationScriptsPartial" />
</body>
</html>

<script src="_framework/blazor.server.js"></script>
5 changes: 5 additions & 0 deletions BadNews/_Imports.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
@using Microsoft.AspNetCore.Authorization;
@using Microsoft.AspNetCore.Components.Authorization;
@using Microsoft.AspNetCore.Components.Forms;
@using Microsoft.AspNetCore.Components.Routing;
@using Microsoft.AspNetCore.Components.Web;
14 changes: 14 additions & 0 deletions BadNews/libman.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"version": "1.0",
"defaultProvider": "unpkg",
"libraries": [
{
"library": "@microsoft/signalr@latest",
"destination": "wwwroot/js/signalr",
"files": [
"dist/browser/signalr.js",
"dist/browser/signalr.min.js"
]
}
]
}
Loading