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

Ховрычев Воинов Букирев Александров #31

Open
wants to merge 1 commit 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,080 changes: 49,534 additions & 7,546 deletions BadNews/.db/news.txt

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions BadNews/BadNews.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,14 @@

<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>

<ItemGroup>
<Content Update="_Imports.razor">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
</Project>
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}";
}
31 changes: 31 additions & 0 deletions BadNews/Controllers/CommentsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
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)
{
var comments = commentsRepository.GetComments(newsId);
return new CommentsDto
{
NewsId = newsId,
Comments = comments.Select(x => new CommentDto() { User = x.User, Value = x.Value }).ToList()
};
}
}
}
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; }
}
}
12 changes: 12 additions & 0 deletions BadNews/Models/Comments/CommentsDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;

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

public IReadOnlyCollection<CommentDto> Comments { get; set; }
}
}
21 changes: 9 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,11 +74,14 @@ 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 =>
{
branchApp.UseDirectoryBrowser("/files");
});


// Остальные запросы — 404 Not Found
}
Expand Down
9 changes: 6 additions & 3 deletions BadNews/Views/News/FullArticle.cshtml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
@using BadNews.Elevation
@using BadNews.BlazorComponents
@using BadNews.Elevation
@model BadNews.Models.News.FullArticleModel

<main role="main" class="container">
Expand All @@ -12,11 +13,13 @@
@if (ViewContext.IsElevated())
{
<form class="mb-4" onsubmit="return confirm('Удалить новость?')"
asp-controller="Editor" asp-action="DeleteArticle" asp-route-id="@(Model.Article.Id)">
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)
<div id="comments" />
@(await Html.RenderComponentAsync<Comments>(RenderMode.ServerPrerendered))
</div>
</div>

Expand All @@ -31,4 +34,4 @@
<p>
<a href="#">Наверх</a>
</p>
</footer>
</footer>
6 changes: 4 additions & 2 deletions BadNews/Views/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
@using BadNews.Elevation
<base href="~/" />
@using BadNews.Elevation
<!DOCTYPE html>
<html lang="ru">
<head>
Expand Down Expand Up @@ -28,10 +29,11 @@
</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;