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

Виленский Кочева Бабинцев #27

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,076 changes: 49,532 additions & 7,544 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}";
}
37 changes: 37 additions & 0 deletions BadNews/Controllers/CommentsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
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);

var commentDtos =comments.Select(comment =>
{
var commentDto = new CommentDto();
commentDto.User = comment.User;
commentDto.Value = comment.Value;
return commentDto;
}).ToArray();
var commentsDtos = new CommentsDto { NewsId=newsId, Comments= commentDtos };
return commentsDtos;
}
}
}
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; }
}
}
21 changes: 9 additions & 12 deletions BadNews/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using BadNews.Elevation;
using BadNews.Hubs;
using BadNews.ModelBuilders.News;
using BadNews.Repositories.Comments;
using BadNews.Repositories.News;
using BadNews.Repositories.Weather;
using BadNews.Validation;
Expand Down Expand Up @@ -31,6 +33,9 @@ public Startup(IWebHostEnvironment env, IConfiguration configuration)
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<INewsRepository, NewsIndexedRepository>();
services.AddSingleton<CommentsRepository>();
services.AddSignalR();
services.AddServerSideBlazor();
services.AddSingleton<INewsModelBuilder, NewsModelBuilder>();
services.AddSingleton<IValidationAttributeAdapterProvider, StopWordsAttributeAdapterProvider>();
services.AddSingleton<IWeatherForecastRepository, WeatherForecastRepository>();
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
47 changes: 46 additions & 1 deletion 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 @@ -17,6 +18,7 @@
</form>
}
@Html.Raw(Model.Article.ContentHtml)
@(await Html.RenderComponentAsync<Comments>(RenderMode.ServerPrerendered))
</div>
</div>

Expand All @@ -32,3 +34,46 @@
<a href="#">Наверх</a>
</p>
</footer>
<script src="/lib/jquery/dist/jquery.min.js"></script>
<script src="/js/signalr/dist/browser/signalr.js"></script>
<script type="text/javascript">
$.get(`/api/news/@Model.Article.Id.ToString()/comments`, function (data) {
const commentsDiv = document.getElementById('comments');

for (const comment of data.comments) {
const li = document.createElement("li");
li.textContent = `${comment.user} говорит: ${comment.value}`;
commentsDiv.appendChild(li);
}
});

const connection = new signalR.HubConnectionBuilder().withUrl("/commentsHub").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveComment", function (user, message) {
const li = document.createElement("li");
document.getElementById("comments").appendChild(li);
// We can assign user-supplied strings to an element's textContent because it
// is not interpreted as markup. If you're assigning in any other way, you
// should be aware of possible script injection concerns.
li.textContent = `${user} говорит: ${message}`;
});

connection.start().then(function () {
document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
const user = document.getElementById("userInput").value;
const message = document.getElementById("commentInput").value;
connection.invoke("SendComment", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});

</script>
7 changes: 5 additions & 2 deletions BadNews/Views/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.min.css" asp-append-version="true" />
<link rel="stylesheet" href="/css/site.css" asp-append-version="true" />
</head>
<body>
<body>
<div class="container">
<header class="news-header">
<a class="news-header-logo text-dark" href="/">Bad News</a>
Expand All @@ -27,8 +27,11 @@
@RenderSection("Header", false)
</div>

@RenderBody()
<base href="~/" />

@RenderBody()

<script src="_framework/blazor.server.js"></script>
<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>
Expand Down
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