From 2bebd600b8520f8b48af4f33b1d8f743ecedcc83 Mon Sep 17 00:00:00 2001 From: "Artemov Ivan (ZOXEXIVO)" Date: Tue, 21 Feb 2023 21:24:19 +0300 Subject: [PATCH] Updates --- .drone.yml | 2 +- build/Jobs.Dockerfile | 2 +- build/Web.Dockerfile | 4 +- .../Geen.Core/Domains/Clubs/ClubModel.cs | 23 +- .../Domains/Clubs/Commands/ClubSaveCommand.cs | 31 +- .../Clubs/Queries/ClubForCacheQuery.cs | 54 +- .../Clubs/Queries/ClubGetAverageAgeQuery.cs | 51 +- .../Domains/Clubs/Queries/ClubGetByIdQuery.cs | 31 +- .../Clubs/Queries/ClubGetByUrlNameQuery.cs | 31 +- .../Clubs/Queries/ClubGetCoachQuery.cs | 31 +- .../Domains/Clubs/Queries/ClubGetListQuery.cs | 29 +- .../Domains/Clubs/Queries/ClubGetUrlsQuery.cs | 29 +- .../Domains/Clubs/Queries/ClubNextIdQuery.cs | 29 +- .../Clubs/Repositories/IClubRepository.cs | 25 +- .../Countries/Commands/CountrySaveCommand.cs | 31 +- .../Domains/Countries/CountryModel.cs | 15 +- .../Countries/Queries/CountryGetByIdQuery.cs | 31 +- .../Countries/Queries/CountryGetByUrlName.cs | 31 +- .../Countries/Queries/CountryGetListQuery.cs | 29 +- .../Countries/Queries/CountryNextIdQuery.cs | 29 +- .../Repositories/ICountryRepository.cs | 19 +- .../Leagues/Commands/LeagueSaveCommand.cs | 31 +- .../Geen.Core/Domains/Leagues/LeagueModel.cs | 17 +- .../Leagues/Queries/LeagueGetByIdQuery.cs | 31 +- .../Leagues/Queries/LeagueGetByUrlName.cs | 31 +- .../Leagues/Queries/LeagueGetListQuery.cs | 31 +- .../Leagues/Queries/LeagueNextIdQuery.cs | 29 +- .../Leagues/Repositories/ILeagueRepository.cs | 19 +- .../Commands/MentionApproveCommand.cs | 31 +- .../Commands/MentionChangeTextCommand.cs | 33 +- .../Commands/MentionChangeTitleCommand.cs | 33 +- .../Mentions/Commands/MentionCreateCommand.cs | 99 ++- .../Commands/MentionDisapproveCommand.cs | 31 +- .../Commands/MentionDislikeCommand.cs | 97 ++- .../Mentions/Commands/MentionLikeCommand.cs | 97 ++- .../Commands/MentionRandomLikerCommand.cs | 39 +- .../Mentions/Commands/MentionRemoveCommand.cs | 31 +- .../MentionSetDefaultAvatarCommand.cs | 31 +- .../Domains/Mentions/MentionModel.cs | 69 +- .../Mentions/Models/IncrementStatus.cs | 13 +- .../Mentions/Queries/GetFreshMentionsQuery.cs | 160 ++--- .../Mentions/Queries/GetMentionByIdQuery.cs | 31 +- .../Queries/GetMentionIdentitiesQuery.cs | 29 +- .../Mentions/Queries/GetMentionLikeStatus.cs | 31 +- .../Mentions/Queries/GetMentionListQuery.cs | 55 +- .../Queries/GetMentionTitleListQuery.cs | 33 +- .../Repositories/IMentionLikeRepository.cs | 19 +- .../Repositories/IMentionRepository.cs | 65 +- .../Players/Commands/PlayerSaveCommand.cs | 31 +- .../Geen.Core/Domains/Players/PlayerModel.cs | 27 +- .../Players/Queries/GetByClubUrlNameQuery.cs | 2 +- .../GetPlayerIdsByClubAndPositionQuery.cs | 5 +- .../Players/Queries/GetPlayersByIdsQuery.cs | 2 +- .../Players/Queries/GetRandomPlayerQuery.cs | 2 +- .../Players/Queries/GetRelatedPlayersQuery.cs | 2 +- .../Players/Queries/GetTopPlayersQuery.cs | 2 +- .../Players/Queries/PlayerGetByIdQuery.cs | 2 +- .../Players/Queries/PlayerGetByUrlName.cs | 2 +- .../Players/Queries/PlayerGetListQuery.cs | 2 +- .../Players/Queries/PlayerGetUrlsQuery.cs | 2 +- .../Players/Queries/PlayerNextIdQuery.cs | 2 +- .../Players/Queries/PlayersForCacheQuery.cs | 2 +- .../Players/Queries/SearchPlayerQuery.cs | 2 +- .../Players/Repositories/IPlayerRepository.cs | 69 +- .../Domains/Players/Utils/Randomizer.cs | 16 +- .../Replies/Commands/ReplyApproveCommand.cs | 31 +- .../Commands/ReplyChangeTextCommand.cs | 33 +- .../Replies/Commands/ReplyCreateCommand.cs | 82 ++- .../Commands/ReplyDisapproveCommand.cs | 31 +- .../Replies/Commands/ReplyRemoveCommand.cs | 47 +- .../Replies/Queries/GetReplyLatestQuery.cs | 38 +- .../Replies/Queries/GetReplyListQuery.cs | 36 +- .../Queries/GetReplyUnapprovedListQuery.cs | 38 +- .../Geen.Core/Domains/Replies/ReplyModel.cs | 21 +- .../Repositories/IReplyLikeRepository.cs | 19 +- .../Replies/Repositories/IReplyRepository.cs | 33 +- .../Domains/Search/Queries/SearchQuery.cs | 34 +- .../Geen.Core/Domains/Users/UserModel.cs | 19 +- .../Votes/Commands/CreateVoteCommand.cs | 49 +- .../Domains/Votes/Queries/GetVoteDataQuery.cs | 39 +- .../Votes/Repositories/IVoteRepository.cs | 11 +- .../Geen.Core/Domains/Votes/VoteModel.cs | 31 +- src/Backend/Geen.Core/Geen.Core.csproj | 12 +- .../Geen.Core/Interfaces/Common/ICommand.cs | 27 +- .../Geen.Core/Interfaces/Common/IQuery.cs | 27 +- .../Models/Content/ContentContext.cs | 13 +- .../Content/Extensions/ContentExtensions.cs | 19 +- .../Geen.Core/Models/Likes/LikeModel.cs | 23 +- .../Geen.Core/Models/Mentions/EntityInfo.cs | 15 +- .../Models/Mentions/MentionCreateModel.cs | 15 +- .../Models/Replies/ReplyCreateModel.cs | 15 +- src/Backend/Geen.Core/Registration.cs | 55 +- .../Interfaces/IClubCacheRepository.cs | 11 +- .../Interfaces/IPlayerCacheRepository.cs | 11 +- .../Geen.Core/Services/Text/ContentService.cs | 218 +++--- .../Text/Extensions/TextExtensions.cs | 29 +- .../Geen.Core/Services/Text/TextService.cs | 61 +- .../Services/Voting/VotingService.cs | 1 + .../Geen.Core/Utils/PagingExtensions.cs | 17 +- .../Geen.Data/Caches/ClubCacheRepository.cs | 47 +- .../Geen.Data/Caches/PlayerCacheRepository.cs | 85 ++- .../Attributes/MongoEntityAttribute.cs | 23 +- src/Backend/Geen.Data/Entities/ClubEntity.cs | 25 +- .../Geen.Data/Entities/CountryEntity.cs | 17 +- .../Geen.Data/Entities/IdentityEntity.cs | 15 +- .../Geen.Data/Entities/LeagueEntity.cs | 19 +- .../Geen.Data/Entities/MentionEntity.cs | 102 ++- .../Entities/Namespaces/MongoNamespaces.cs | 11 +- .../Geen.Data/Entities/PlayerEntity.cs | 29 +- src/Backend/Geen.Data/Entities/ReplyEntity.cs | 25 +- src/Backend/Geen.Data/Entities/UserEntity.cs | 18 +- src/Backend/Geen.Data/Entities/VoteEntity.cs | 25 +- .../Geen.Data/Extensions/MapperExtensions.cs | 13 +- src/Backend/Geen.Data/Geen.Data.csproj | 28 +- src/Backend/Geen.Data/Registration.cs | 65 +- .../Geen.Data/Repositories/ClubRepository.cs | 209 +++--- .../Repositories/CountryRepository.cs | 97 ++- .../Repositories/LeagueRepository.cs | 98 ++- .../Likes/MentionLikeRepository.cs | 89 ++- .../Repositories/Likes/ReplyLikeRepository.cs | 89 ++- .../Repositories/MentionRepository.cs | 659 +++++++++--------- .../Repositories/PlayerRepository.cs | 515 +++++++------- .../Geen.Data/Repositories/ReplyRepository.cs | 299 ++++---- .../Geen.Data/Repositories/VoteRepository.cs | 27 +- .../Services/Voting/VotingService.cs | 6 +- .../Geen.Data/Settings/GeenSettings.cs | 61 +- .../Mongo/Extensions/MongoExtensions.cs | 8 +- .../Geen.Data/Storages/Mongo/MongoContext.cs | 140 ++-- .../Geen.Data/Storages/Redis/RedisStore.cs | 23 +- .../Geen.Data/Utils/PagingExtensions.cs | 23 +- .../Application/Jobs/SportsSyncService.cs | 2 +- src/Backend/Geen.Jobs/Geen.Jobs.csproj | 6 +- src/Backend/Geen.Jobs/Program.cs | 5 +- .../Attributes/FromJsonUriAttribute.cs | 25 +- .../Extensions/LoginModelExtensions.cs | 16 +- .../Filters/AuthenticationFilter.cs | 53 +- .../Authentication/Model/LoginModel.cs | 13 +- .../Services/AuthenticationService.cs | 15 +- .../Authentication/Services/UserService.cs | 89 ++- .../Application/Constants/CookieConstants.cs | 15 +- .../Dispatchers/CommandDispatcher.cs | 60 +- .../Dispatchers/QueryDispatcher.cs | 50 +- .../Filters/Exceptions/ExceptionFilter.cs | 29 +- .../Filters/Throttling/ThrottlingFilter.cs | 70 +- .../Bindings/FromJsonUriAttribute.cs | 25 +- .../Formatter/Bindings/JsonModelBinder.cs | 23 +- .../Geen.Web/Application/Models/BodyText.cs | 11 +- .../Application/Models/MentionCreateDto.cs | 29 +- .../Application/Models/ReplyCreateDto.cs | 25 +- .../Geen.Web/Application/Registration.cs | 157 ++--- .../Application/Services/Json/JsonService.cs | 45 +- .../Application/Sitemap/SitemapProvider.cs | 135 ++-- .../Controllers/Admin/AdminClubController.cs | 51 -- .../Admin/AdminCountryController.cs | 45 -- .../Admin/AdminLeagueController.cs | 45 -- .../Admin/AdminMentionController.cs | 94 --- .../Admin/AdminPlayerController.cs | 56 -- .../Controllers/Admin/AdminReplyController.cs | 69 -- .../Areas/Admin/AdminClubController.cs | 50 ++ .../Areas/Admin/AdminCountryController.cs | 44 ++ .../Areas/Admin/AdminLeagueController.cs | 44 ++ .../Areas/Admin/AdminMentionController.cs | 93 +++ .../Areas/Admin/AdminPlayerController.cs | 55 ++ .../Areas/Admin/AdminReplyController.cs | 68 ++ .../Controllers/AuthenticationController.cs | 61 +- .../Geen.Web/Controllers/ClubController.cs | 69 +- .../Geen.Web/Controllers/ErrorController.cs | 33 +- .../Geen.Web/Controllers/LeagueController.cs | 27 +- .../Geen.Web/Controllers/MentionController.cs | 197 +++--- .../Geen.Web/Controllers/PlayerController.cs | 103 ++- .../Geen.Web/Controllers/ReplyController.cs | 71 +- .../Geen.Web/Controllers/SearchController.cs | 33 +- .../Geen.Web/Controllers/VoteController.cs | 41 +- src/Backend/Geen.Web/Geen.Web.csproj | 31 +- src/Backend/Geen.Web/Program.cs | 45 +- .../Geen.Web/Properties/launchSettings.json | 2 +- src/Backend/Geen.Web/Startup.cs | 159 +++-- .../Geen.Web/appsettings.Development.json | 2 +- src/Backend/Geen.Web/appsettings.json | 2 +- src/Backend/Geen.sln.DotSettings | 2 + .../Geen.ClientGenerator.csproj | 6 +- .../Shared/Geen.ClientGenerator/Program.cs | 7 +- 182 files changed, 4144 insertions(+), 4355 deletions(-) delete mode 100644 src/Backend/Geen.Web/Controllers/Admin/AdminClubController.cs delete mode 100644 src/Backend/Geen.Web/Controllers/Admin/AdminCountryController.cs delete mode 100644 src/Backend/Geen.Web/Controllers/Admin/AdminLeagueController.cs delete mode 100644 src/Backend/Geen.Web/Controllers/Admin/AdminMentionController.cs delete mode 100644 src/Backend/Geen.Web/Controllers/Admin/AdminPlayerController.cs delete mode 100644 src/Backend/Geen.Web/Controllers/Admin/AdminReplyController.cs create mode 100644 src/Backend/Geen.Web/Controllers/Areas/Admin/AdminClubController.cs create mode 100644 src/Backend/Geen.Web/Controllers/Areas/Admin/AdminCountryController.cs create mode 100644 src/Backend/Geen.Web/Controllers/Areas/Admin/AdminLeagueController.cs create mode 100644 src/Backend/Geen.Web/Controllers/Areas/Admin/AdminMentionController.cs create mode 100644 src/Backend/Geen.Web/Controllers/Areas/Admin/AdminPlayerController.cs create mode 100644 src/Backend/Geen.Web/Controllers/Areas/Admin/AdminReplyController.cs create mode 100644 src/Backend/Geen.sln.DotSettings diff --git a/.drone.yml b/.drone.yml index 4d789ec..13b91b9 100644 --- a/.drone.yml +++ b/.drone.yml @@ -44,7 +44,7 @@ steps: commands: - docker run -d -p 172.17.0.1:7000:7000 --restart always --name geen-web geen-web:2.0.0.$$DRONE_BUILD_NUMBER - docker run -d --restart always --name geen-jobs geen-jobs:2.0.0.$$DRONE_BUILD_NUMBER - + volumes: - name: docker_sock host: diff --git a/build/Jobs.Dockerfile b/build/Jobs.Dockerfile index 352053d..40a8414 100644 --- a/build/Jobs.Dockerfile +++ b/build/Jobs.Dockerfile @@ -8,7 +8,7 @@ COPY ./src/Backend/ ./ WORKDIR /app/Geen.Jobs -RUN dotnet publish -c Release -o /app/out -r linux-x64 --self-contained true /p:PublishReadyToRun=true /p:PublishSingleFile=true --packages packages +RUN dotnet publish -c Release -o /app/out -r linux-x64 --self-contained true /p:PublishSingleFile=true --packages packages FROM mcr.microsoft.com/dotnet/runtime-deps:7.0 AS runtime WORKDIR /app diff --git a/build/Web.Dockerfile b/build/Web.Dockerfile index 030eab4..c7a5a1f 100644 --- a/build/Web.Dockerfile +++ b/build/Web.Dockerfile @@ -1,4 +1,4 @@ -FROM node:17-alpine3.14 AS build-frontend +FROM node:19-alpine3.16 AS build-frontend WORKDIR /app @@ -20,7 +20,7 @@ COPY ./src/Backend/ ./ WORKDIR /app/Geen.Web -RUN dotnet publish -c Release -o /app/out -r linux-x64 --self-contained true /p:PublishReadyToRun=true /p:PublishSingleFile=true --packages packages +RUN dotnet publish -c Release -o /app/out -r linux-x64 --self-contained true /p:PublishSingleFile=true --packages packages FROM mcr.microsoft.com/dotnet/runtime-deps:7.0 AS runtime WORKDIR /app diff --git a/src/Backend/Geen.Core/Domains/Clubs/ClubModel.cs b/src/Backend/Geen.Core/Domains/Clubs/ClubModel.cs index f5d4465..608147f 100644 --- a/src/Backend/Geen.Core/Domains/Clubs/ClubModel.cs +++ b/src/Backend/Geen.Core/Domains/Clubs/ClubModel.cs @@ -1,18 +1,17 @@ -namespace Geen.Core.Domains.Clubs +namespace Geen.Core.Domains.Clubs; + +public class ClubModel { - public class ClubModel - { - public int Id { get; set; } + public int Id { get; set; } - public string Name { get; set; } - public string UrlName { get; set; } + public string Name { get; set; } + public string UrlName { get; set; } - public string OfficialProfile { get; set; } + public string OfficialProfile { get; set; } - public int LeagueId { get; set; } + public int LeagueId { get; set; } - public bool IsNational { get; set; } + public bool IsNational { get; set; } - public long Votes { get; set; } - } -} + public long Votes { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Clubs/Commands/ClubSaveCommand.cs b/src/Backend/Geen.Core/Domains/Clubs/Commands/ClubSaveCommand.cs index 10c1185..5a324c4 100644 --- a/src/Backend/Geen.Core/Domains/Clubs/Commands/ClubSaveCommand.cs +++ b/src/Backend/Geen.Core/Domains/Clubs/Commands/ClubSaveCommand.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Clubs.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Clubs.Commands +namespace Geen.Core.Domains.Clubs.Commands; + +public record ClubSaveCommand : ICommand +{ + public ClubModel Model { get; set; } +} + +public class ClubSaveCommandDispatcher : ICommandDispatcher { - public class ClubSaveCommand : ICommand + private readonly IClubRepository _clubRepository; + + public ClubSaveCommandDispatcher(IClubRepository clubRepository) { - public ClubModel Model { get; set; } + _clubRepository = clubRepository; } - public class ClubSaveCommandDispatcher : ICommandDispatcher + public Task Execute(ClubSaveCommand command) { - private readonly IClubRepository _clubRepository; - - public ClubSaveCommandDispatcher(IClubRepository clubRepository) - { - _clubRepository = clubRepository; - } - - public Task Execute(ClubSaveCommand command) - { - return _clubRepository.Save(command.Model); - } + return _clubRepository.Save(command.Model); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubForCacheQuery.cs b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubForCacheQuery.cs index 7a6f9f5..9a67bb8 100644 --- a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubForCacheQuery.cs +++ b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubForCacheQuery.cs @@ -3,42 +3,42 @@ using Geen.Core.Domains.Clubs.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Clubs.Queries +namespace Geen.Core.Domains.Clubs.Queries; + +public class ClubsForCacheQuery : IQuery>> { - public class ClubsForCacheQuery : IQuery>> + public string ClubUrlName { get; set; } +} + +public class + ClubsForCacheQueryHandler : IQueryHandler>> +{ + private readonly IClubRepository _clubRepository; + + public ClubsForCacheQueryHandler(IClubRepository clubRepository) { - public string ClubUrlName { get; set; } + _clubRepository = clubRepository; } - public class ClubsForCacheQueryHandler : IQueryHandler>> + public async Task> Execute(ClubsForCacheQuery query) { - private readonly IClubRepository _clubRepository; + var items = await _clubRepository.GetCached(); - public ClubsForCacheQueryHandler(IClubRepository clubRepository) - { - _clubRepository = clubRepository; - } + var result = new ConcurrentDictionary(); - public async Task> Execute(ClubsForCacheQuery query) - { - var items = await _clubRepository.GetCached(); + foreach (var club in items) + result.TryAdd(GetCleanName(club.Name), club); - var result = new ConcurrentDictionary(); - - foreach (var club in items) - result.TryAdd(GetCleanName(club.Name), club); - - return result; - } + return result; + } - private static string GetCleanName(string clubName) - { - var ind = clubName.IndexOf(' '); + private static string GetCleanName(string clubName) + { + var ind = clubName.IndexOf(' '); - if (ind == -1) - return clubName.ToLower(); + if (ind == -1) + return clubName.ToLower(); - return clubName.Substring(0, ind).ToLower(); - } + return clubName.Substring(0, ind).ToLower(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetAverageAgeQuery.cs b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetAverageAgeQuery.cs index 764cec2..1ce2d6d 100644 --- a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetAverageAgeQuery.cs +++ b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetAverageAgeQuery.cs @@ -4,40 +4,39 @@ using Geen.Core.Domains.Clubs.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Clubs.Queries +namespace Geen.Core.Domains.Clubs.Queries; + +public class ClubGetAverageAgeQuery : IQuery> { - public class ClubGetAverageAgeQuery : IQuery> + public string UrlName { get; set; } +} + +public class ClubGetAverageAgeQueryHandler : IQueryHandler> +{ + private readonly IClubRepository _clubRepository; + + public ClubGetAverageAgeQueryHandler(IClubRepository clubRepository) { - public string UrlName { get; set; } + _clubRepository = clubRepository; } - public class ClubGetAverageAgeQueryHandler : IQueryHandler> + public async Task Execute(ClubGetAverageAgeQuery query) { - private readonly IClubRepository _clubRepository; + var birthdays = await _clubRepository.GetBirthdays(query.UrlName); - public ClubGetAverageAgeQueryHandler(IClubRepository clubRepository) - { - _clubRepository = clubRepository; - } + if (!birthdays.Any()) + return null; - public async Task Execute(ClubGetAverageAgeQuery query) - { - var birthdays = await _clubRepository.GetBirthdays(query.UrlName); - - if (!birthdays.Any()) - return null; - - return Math.Round(birthdays.Select(GetAge).Average(), 1); - } + return Math.Round(birthdays.Select(GetAge).Average(), 1); + } - private static int GetAge(DateTime dateOfBirth) - { - var today = DateTime.Today; + private static int GetAge(DateTime dateOfBirth) + { + var today = DateTime.Today; - var a = (today.Year * 100 + today.Month) * 100 + today.Day; - var b = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 + dateOfBirth.Day; + var a = (today.Year * 100 + today.Month) * 100 + today.Day; + var b = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 + dateOfBirth.Day; - return (a - b) / 10000; - } + return (a - b) / 10000; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetByIdQuery.cs b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetByIdQuery.cs index aa640b9..7aa6a17 100644 --- a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetByIdQuery.cs +++ b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetByIdQuery.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Clubs.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Clubs.Queries +namespace Geen.Core.Domains.Clubs.Queries; + +public class ClubGetByIdQuery : IQuery> +{ + public int Id { get; set; } +} + +public class ClubGetByIdQueryHandler : IQueryHandler> { - public class ClubGetByIdQuery : IQuery> + private readonly IClubRepository _clubRepository; + + public ClubGetByIdQueryHandler(IClubRepository clubRepository) { - public int Id { get; set; } + _clubRepository = clubRepository; } - public class ClubGetByIdQueryHandler : IQueryHandler> + public Task Execute(ClubGetByIdQuery query) { - private readonly IClubRepository _clubRepository; - - public ClubGetByIdQueryHandler(IClubRepository clubRepository) - { - _clubRepository = clubRepository; - } - - public Task Execute(ClubGetByIdQuery query) - { - return _clubRepository.GetById(query.Id); - } + return _clubRepository.GetById(query.Id); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetByUrlNameQuery.cs b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetByUrlNameQuery.cs index 9251889..8217a38 100644 --- a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetByUrlNameQuery.cs +++ b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetByUrlNameQuery.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Clubs.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Clubs.Queries +namespace Geen.Core.Domains.Clubs.Queries; + +public class ClubGetByUrlNameQuery : IQuery> +{ + public string UrlName { get; set; } +} + +public class ClubGetByUrlNameQueryHandler : IQueryHandler> { - public class ClubGetByUrlNameQuery : IQuery> + private readonly IClubRepository _clubRepository; + + public ClubGetByUrlNameQueryHandler(IClubRepository clubRepository) { - public string UrlName { get; set; } + _clubRepository = clubRepository; } - public class ClubGetByUrlNameQueryHandler : IQueryHandler> + public Task Execute(ClubGetByUrlNameQuery query) { - private readonly IClubRepository _clubRepository; - - public ClubGetByUrlNameQueryHandler(IClubRepository clubRepository) - { - _clubRepository = clubRepository; - } - - public Task Execute(ClubGetByUrlNameQuery query) - { - return _clubRepository.GetByUrlName(query.UrlName); - } + return _clubRepository.GetByUrlName(query.UrlName); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetCoachQuery.cs b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetCoachQuery.cs index a63dc46..6da26fc 100644 --- a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetCoachQuery.cs +++ b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetCoachQuery.cs @@ -3,25 +3,24 @@ using Geen.Core.Domains.Players.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Clubs.Queries +namespace Geen.Core.Domains.Clubs.Queries; + +public class ClubGetCoachQuery : IQuery> +{ + public string ClubUrlName { get; set; } +} + +public class ClubGetCoachQueryHandler : IQueryHandler> { - public class ClubGetCoachQuery : IQuery> + private readonly IPlayerRepository _playerRepository; + + public ClubGetCoachQueryHandler(IPlayerRepository playerRepository) { - public string ClubUrlName { get; set; } + _playerRepository = playerRepository; } - public class ClubGetCoachQueryHandler : IQueryHandler> + public Task Execute(ClubGetCoachQuery query) { - private readonly IPlayerRepository _playerRepository; - - public ClubGetCoachQueryHandler(IPlayerRepository playerRepository) - { - _playerRepository = playerRepository; - } - - public Task Execute(ClubGetCoachQuery query) - { - return _playerRepository.GetClubCoach(query.ClubUrlName); - } + return _playerRepository.GetClubCoach(query.ClubUrlName); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetListQuery.cs b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetListQuery.cs index 12d1ece..0e108b9 100644 --- a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetListQuery.cs +++ b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetListQuery.cs @@ -3,24 +3,23 @@ using Geen.Core.Domains.Clubs.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Clubs.Queries +namespace Geen.Core.Domains.Clubs.Queries; + +public class ClubGetListQuery : IQuery>> +{ +} + +public class ClubGetListQueryHandler : IQueryHandler>> { - public class ClubGetListQuery : IQuery>> + private readonly IClubRepository _clubRepository; + + public ClubGetListQueryHandler(IClubRepository clubRepository) { + _clubRepository = clubRepository; } - public class ClubGetListQueryHandler : IQueryHandler>> + public Task> Execute(ClubGetListQuery query) { - private readonly IClubRepository _clubRepository; - - public ClubGetListQueryHandler(IClubRepository clubRepository) - { - _clubRepository = clubRepository; - } - - public Task> Execute(ClubGetListQuery query) - { - return _clubRepository.GetAll(); - } + return _clubRepository.GetAll(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetUrlsQuery.cs b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetUrlsQuery.cs index 3912435..430b955 100644 --- a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetUrlsQuery.cs +++ b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubGetUrlsQuery.cs @@ -3,24 +3,23 @@ using Geen.Core.Domains.Clubs.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Clubs.Queries +namespace Geen.Core.Domains.Clubs.Queries; + +public class ClubGetUrlsQuery : IQuery>> +{ +} + +public class ClubGetUrlsQueryHandler : IQueryHandler>> { - public class ClubGetUrlsQuery : IQuery>> + private readonly IClubRepository _clubRepository; + + public ClubGetUrlsQueryHandler(IClubRepository clubRepository) { + _clubRepository = clubRepository; } - public class ClubGetUrlsQueryHandler : IQueryHandler>> + public Task> Execute(ClubGetUrlsQuery query) { - private readonly IClubRepository _clubRepository; - - public ClubGetUrlsQueryHandler(IClubRepository clubRepository) - { - _clubRepository = clubRepository; - } - - public Task> Execute(ClubGetUrlsQuery query) - { - return _clubRepository.GetAllUrls(); - } + return _clubRepository.GetAllUrls(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubNextIdQuery.cs b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubNextIdQuery.cs index 389c7b2..b04514e 100644 --- a/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubNextIdQuery.cs +++ b/src/Backend/Geen.Core/Domains/Clubs/Queries/ClubNextIdQuery.cs @@ -2,24 +2,23 @@ using Geen.Core.Domains.Clubs.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Clubs.Queries +namespace Geen.Core.Domains.Clubs.Queries; + +public class ClubNextIdQuery : IQuery> +{ +} + +public class ClubNextIdQueryHandler : IQueryHandler> { - public class ClubNextIdQuery : IQuery> + private readonly IClubRepository _clubRepository; + + public ClubNextIdQueryHandler(IClubRepository clubRepository) { + _clubRepository = clubRepository; } - public class ClubNextIdQueryHandler : IQueryHandler> + public Task Execute(ClubNextIdQuery query) { - private readonly IClubRepository _clubRepository; - - public ClubNextIdQueryHandler(IClubRepository clubRepository) - { - _clubRepository = clubRepository; - } - - public Task Execute(ClubNextIdQuery query) - { - return _clubRepository.GetNextId(); - } + return _clubRepository.GetNextId(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Clubs/Repositories/IClubRepository.cs b/src/Backend/Geen.Core/Domains/Clubs/Repositories/IClubRepository.cs index e0d29f9..6a5b3ff 100644 --- a/src/Backend/Geen.Core/Domains/Clubs/Repositories/IClubRepository.cs +++ b/src/Backend/Geen.Core/Domains/Clubs/Repositories/IClubRepository.cs @@ -2,20 +2,19 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace Geen.Core.Domains.Clubs.Repositories +namespace Geen.Core.Domains.Clubs.Repositories; + +public interface IClubRepository { - public interface IClubRepository - { - Task GetById(int id); - Task GetByUrlName(string urlName); + Task GetById(int id); + Task GetByUrlName(string urlName); - Task> GetAll(); - Task> GetAllUrls(); - Task> GetCached(); + Task> GetAll(); + Task> GetAllUrls(); + Task> GetCached(); - Task GetNextId(); - Task> GetBirthdays(string urlName); + Task GetNextId(); + Task> GetBirthdays(string urlName); - Task Save(ClubModel model); - } -} + Task Save(ClubModel model); +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Countries/Commands/CountrySaveCommand.cs b/src/Backend/Geen.Core/Domains/Countries/Commands/CountrySaveCommand.cs index ee1e0cd..6d50983 100644 --- a/src/Backend/Geen.Core/Domains/Countries/Commands/CountrySaveCommand.cs +++ b/src/Backend/Geen.Core/Domains/Countries/Commands/CountrySaveCommand.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Countries.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Countries.Commands +namespace Geen.Core.Domains.Countries.Commands; + +public record CountrySaveCommand : ICommand +{ + public CountryModel Model { get; set; } +} + +public class CountrySaveCommandDispatcher : ICommandDispatcher { - public class CountrySaveCommand : ICommand + private readonly ICountryRepository _countryRepository; + + public CountrySaveCommandDispatcher(ICountryRepository countryRepository) { - public CountryModel Model { get; set; } + _countryRepository = countryRepository; } - public class CountrySaveCommandDispatcher : ICommandDispatcher + public Task Execute(CountrySaveCommand command) { - private readonly ICountryRepository _countryRepository; - - public CountrySaveCommandDispatcher(ICountryRepository countryRepository) - { - _countryRepository = countryRepository; - } - - public Task Execute(CountrySaveCommand command) - { - return _countryRepository.Save(command.Model); - } + return _countryRepository.Save(command.Model); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Countries/CountryModel.cs b/src/Backend/Geen.Core/Domains/Countries/CountryModel.cs index 17f8619..e64d76b 100644 --- a/src/Backend/Geen.Core/Domains/Countries/CountryModel.cs +++ b/src/Backend/Geen.Core/Domains/Countries/CountryModel.cs @@ -1,10 +1,9 @@ -namespace Geen.Core.Domains.Countries +namespace Geen.Core.Domains.Countries; + +public record CountryModel { - public class CountryModel - { - public int Id { get; set; } + public int Id { get; set; } - public string Name { get; set; } - public string UrlName { get; set; } - } -} + public string Name { get; set; } + public string UrlName { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Countries/Queries/CountryGetByIdQuery.cs b/src/Backend/Geen.Core/Domains/Countries/Queries/CountryGetByIdQuery.cs index a7e2e9c..a2d6e28 100644 --- a/src/Backend/Geen.Core/Domains/Countries/Queries/CountryGetByIdQuery.cs +++ b/src/Backend/Geen.Core/Domains/Countries/Queries/CountryGetByIdQuery.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Countries.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Countries.Queries +namespace Geen.Core.Domains.Countries.Queries; + +public record CountryGetByIdQuery : IQuery> +{ + public int Id { get; set; } +} + +public class CountryGetByIdQueryHandler : IQueryHandler> { - public class CountryGetByIdQuery : IQuery> + private readonly ICountryRepository _countryRepository; + + public CountryGetByIdQueryHandler(ICountryRepository countryRepository) { - public int Id { get; set; } + _countryRepository = countryRepository; } - public class CountryGetByIdQueryHandler : IQueryHandler> + public Task Execute(CountryGetByIdQuery query) { - private readonly ICountryRepository _countryRepository; - - public CountryGetByIdQueryHandler(ICountryRepository countryRepository) - { - _countryRepository = countryRepository; - } - - public Task Execute(CountryGetByIdQuery query) - { - return _countryRepository.GetById(query.Id); - } + return _countryRepository.GetById(query.Id); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Countries/Queries/CountryGetByUrlName.cs b/src/Backend/Geen.Core/Domains/Countries/Queries/CountryGetByUrlName.cs index 9256c97..01d24dd 100644 --- a/src/Backend/Geen.Core/Domains/Countries/Queries/CountryGetByUrlName.cs +++ b/src/Backend/Geen.Core/Domains/Countries/Queries/CountryGetByUrlName.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Countries.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Countries.Queries +namespace Geen.Core.Domains.Countries.Queries; + +public record CountryGetByUrlName : IQuery> +{ + public string UrlName { get; set; } +} + +public class CountryGetByUrlNameHandler : IQueryHandler> { - public class CountryGetByUrlName : IQuery> + private readonly ICountryRepository _countryRepository; + + public CountryGetByUrlNameHandler(ICountryRepository countryRepository) { - public string UrlName { get; set; } + _countryRepository = countryRepository; } - public class CountryGetByUrlNameHandler : IQueryHandler> + public Task Execute(CountryGetByUrlName query) { - private readonly ICountryRepository _countryRepository; - - public CountryGetByUrlNameHandler(ICountryRepository countryRepository) - { - _countryRepository = countryRepository; - } - - public Task Execute(CountryGetByUrlName query) - { - return _countryRepository.GetByUrlName(query.UrlName); - } + return _countryRepository.GetByUrlName(query.UrlName); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Countries/Queries/CountryGetListQuery.cs b/src/Backend/Geen.Core/Domains/Countries/Queries/CountryGetListQuery.cs index 52f2360..cd38219 100644 --- a/src/Backend/Geen.Core/Domains/Countries/Queries/CountryGetListQuery.cs +++ b/src/Backend/Geen.Core/Domains/Countries/Queries/CountryGetListQuery.cs @@ -3,24 +3,23 @@ using Geen.Core.Domains.Countries.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Countries.Queries +namespace Geen.Core.Domains.Countries.Queries; + +public record CountryGetListQuery : IQuery>> +{ +} + +public class CountryGetListQueryHandler : IQueryHandler>> { - public class CountryGetListQuery : IQuery>> + private readonly ICountryRepository _countryRepository; + + public CountryGetListQueryHandler(ICountryRepository countryRepository) { + _countryRepository = countryRepository; } - public class CountryGetListQueryHandler : IQueryHandler>> + public Task> Execute(CountryGetListQuery query) { - private readonly ICountryRepository _countryRepository; - - public CountryGetListQueryHandler(ICountryRepository countryRepository) - { - _countryRepository = countryRepository; - } - - public Task> Execute(CountryGetListQuery query) - { - return _countryRepository.GetAll(); - } + return _countryRepository.GetAll(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Countries/Queries/CountryNextIdQuery.cs b/src/Backend/Geen.Core/Domains/Countries/Queries/CountryNextIdQuery.cs index 8564cb6..698c652 100644 --- a/src/Backend/Geen.Core/Domains/Countries/Queries/CountryNextIdQuery.cs +++ b/src/Backend/Geen.Core/Domains/Countries/Queries/CountryNextIdQuery.cs @@ -2,24 +2,23 @@ using Geen.Core.Domains.Countries.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Countries.Queries +namespace Geen.Core.Domains.Countries.Queries; + +public record CountryNextIdQuery : IQuery> +{ +} + +public class CountryNextIdQueryHandler : IQueryHandler> { - public class CountryNextIdQuery : IQuery> + private readonly ICountryRepository _countryRepository; + + public CountryNextIdQueryHandler(ICountryRepository countryRepository) { + _countryRepository = countryRepository; } - public class CountryNextIdQueryHandler : IQueryHandler> + public Task Execute(CountryNextIdQuery query) { - private readonly ICountryRepository _countryRepository; - - public CountryNextIdQueryHandler(ICountryRepository countryRepository) - { - _countryRepository = countryRepository; - } - - public Task Execute(CountryNextIdQuery query) - { - return _countryRepository.GetNextId(); - } + return _countryRepository.GetNextId(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Countries/Repositories/ICountryRepository.cs b/src/Backend/Geen.Core/Domains/Countries/Repositories/ICountryRepository.cs index bff6f94..b510344 100644 --- a/src/Backend/Geen.Core/Domains/Countries/Repositories/ICountryRepository.cs +++ b/src/Backend/Geen.Core/Domains/Countries/Repositories/ICountryRepository.cs @@ -1,17 +1,16 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace Geen.Core.Domains.Countries.Repositories +namespace Geen.Core.Domains.Countries.Repositories; + +public interface ICountryRepository { - public interface ICountryRepository - { - Task GetById(int id); - Task GetByUrlName(string urlName); + Task GetById(int id); + Task GetByUrlName(string urlName); - Task> GetAll(); + Task> GetAll(); - Task GetNextId(); + Task GetNextId(); - Task Save(CountryModel model); - } -} + Task Save(CountryModel model); +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Leagues/Commands/LeagueSaveCommand.cs b/src/Backend/Geen.Core/Domains/Leagues/Commands/LeagueSaveCommand.cs index 669850c..0234b27 100644 --- a/src/Backend/Geen.Core/Domains/Leagues/Commands/LeagueSaveCommand.cs +++ b/src/Backend/Geen.Core/Domains/Leagues/Commands/LeagueSaveCommand.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Leagues.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Leagues.Commands +namespace Geen.Core.Domains.Leagues.Commands; + +public record LeagueSaveCommand : ICommand +{ + public LeagueModel Model { get; set; } +} + +public class LeagueSaveCommandDispatcher : ICommandDispatcher { - public class LeagueSaveCommand : ICommand + private readonly ILeagueRepository _leagueRepository; + + public LeagueSaveCommandDispatcher(ILeagueRepository leagueRepository) { - public LeagueModel Model { get; set; } + _leagueRepository = leagueRepository; } - public class LeagueSaveCommandDispatcher : ICommandDispatcher + public Task Execute(LeagueSaveCommand command) { - private readonly ILeagueRepository _leagueRepository; - - public LeagueSaveCommandDispatcher(ILeagueRepository leagueRepository) - { - _leagueRepository = leagueRepository; - } - - public Task Execute(LeagueSaveCommand command) - { - return _leagueRepository.Save(command.Model); - } + return _leagueRepository.Save(command.Model); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Leagues/LeagueModel.cs b/src/Backend/Geen.Core/Domains/Leagues/LeagueModel.cs index 55ac9cd..c00f4a5 100644 --- a/src/Backend/Geen.Core/Domains/Leagues/LeagueModel.cs +++ b/src/Backend/Geen.Core/Domains/Leagues/LeagueModel.cs @@ -1,12 +1,11 @@ -namespace Geen.Core.Domains.Leagues +namespace Geen.Core.Domains.Leagues; + +public record LeagueModel { - public class LeagueModel - { - public int Id { get; set; } + public int Id { get; set; } - public string Name { get; set; } - public string UrlName { get; set; } + public string Name { get; set; } + public string UrlName { get; set; } - public int CountryId { get; set; } - } -} + public int CountryId { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueGetByIdQuery.cs b/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueGetByIdQuery.cs index 04d7b2c..3d1706c 100644 --- a/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueGetByIdQuery.cs +++ b/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueGetByIdQuery.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Leagues.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Leagues.Queries +namespace Geen.Core.Domains.Leagues.Queries; + +public record LeagueGetByIdQuery : IQuery> +{ + public int Id { get; set; } +} + +public class LeagueGetByIdQueryHandler : IQueryHandler> { - public class LeagueGetByIdQuery : IQuery> + private readonly ILeagueRepository _leagueRepository; + + public LeagueGetByIdQueryHandler(ILeagueRepository leagueRepository) { - public int Id { get; set; } + _leagueRepository = leagueRepository; } - public class LeagueGetByIdQueryHandler : IQueryHandler> + public Task Execute(LeagueGetByIdQuery query) { - private readonly ILeagueRepository _leagueRepository; - - public LeagueGetByIdQueryHandler(ILeagueRepository leagueRepository) - { - _leagueRepository = leagueRepository; - } - - public Task Execute(LeagueGetByIdQuery query) - { - return _leagueRepository.GetById(query.Id); - } + return _leagueRepository.GetById(query.Id); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueGetByUrlName.cs b/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueGetByUrlName.cs index 8fdcf72..c6e006c 100644 --- a/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueGetByUrlName.cs +++ b/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueGetByUrlName.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Leagues.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Leagues.Queries +namespace Geen.Core.Domains.Leagues.Queries; + +public record LeagueModelGetByUrlName : IQuery> +{ + public string UrlName { get; set; } +} + +public class LeagueModelGetByUrlNameHandler : IQueryHandler> { - public class LeagueModelGetByUrlName : IQuery> + private readonly ILeagueRepository _leagueRepository; + + public LeagueModelGetByUrlNameHandler(ILeagueRepository leagueRepository) { - public string UrlName { get; set; } + _leagueRepository = leagueRepository; } - public class LeagueModelGetByUrlNameHandler : IQueryHandler> + public Task Execute(LeagueModelGetByUrlName query) { - private readonly ILeagueRepository _leagueRepository; - - public LeagueModelGetByUrlNameHandler(ILeagueRepository leagueRepository) - { - _leagueRepository = leagueRepository; - } - - public Task Execute(LeagueModelGetByUrlName query) - { - return _leagueRepository.GetByUrlName(query.UrlName); - } + return _leagueRepository.GetByUrlName(query.UrlName); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueGetListQuery.cs b/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueGetListQuery.cs index 12e5898..dab7e58 100644 --- a/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueGetListQuery.cs +++ b/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueGetListQuery.cs @@ -3,25 +3,24 @@ using Geen.Core.Domains.Leagues.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Leagues.Queries +namespace Geen.Core.Domains.Leagues.Queries; + +public record LeagueGetListQuery : IQuery>> +{ + public int? CountryId { get; set; } +} + +public class LeagueGetListQueryHandler : IQueryHandler>> { - public class LeagueGetListQuery : IQuery>> + private readonly ILeagueRepository _leagueRepository; + + public LeagueGetListQueryHandler(ILeagueRepository leagueRepository) { - public int? CountryId { get; set; } + _leagueRepository = leagueRepository; } - public class LeagueGetListQueryHandler : IQueryHandler>> + public Task> Execute(LeagueGetListQuery query) { - private readonly ILeagueRepository _leagueRepository; - - public LeagueGetListQueryHandler(ILeagueRepository leagueRepository) - { - _leagueRepository = leagueRepository; - } - - public Task> Execute(LeagueGetListQuery query) - { - return _leagueRepository.GetAll(); - } + return _leagueRepository.GetAll(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueNextIdQuery.cs b/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueNextIdQuery.cs index 0136176..0429044 100644 --- a/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueNextIdQuery.cs +++ b/src/Backend/Geen.Core/Domains/Leagues/Queries/LeagueNextIdQuery.cs @@ -2,24 +2,23 @@ using Geen.Core.Domains.Leagues.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Leagues.Queries +namespace Geen.Core.Domains.Leagues.Queries; + +public record LeagueNextIdQuery : IQuery> +{ +} + +public class LeagueNextIdQueryHandler : IQueryHandler> { - public class LeagueNextIdQuery : IQuery> + private readonly ILeagueRepository _leagueRepository; + + public LeagueNextIdQueryHandler(ILeagueRepository leagueRepository) { + _leagueRepository = leagueRepository; } - public class LeagueNextIdQueryHandler : IQueryHandler> + public Task Execute(LeagueNextIdQuery query) { - private readonly ILeagueRepository _leagueRepository; - - public LeagueNextIdQueryHandler(ILeagueRepository leagueRepository) - { - _leagueRepository = leagueRepository; - } - - public Task Execute(LeagueNextIdQuery query) - { - return _leagueRepository.GetNextId(); - } + return _leagueRepository.GetNextId(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Leagues/Repositories/ILeagueRepository.cs b/src/Backend/Geen.Core/Domains/Leagues/Repositories/ILeagueRepository.cs index be83fa1..f9e410c 100644 --- a/src/Backend/Geen.Core/Domains/Leagues/Repositories/ILeagueRepository.cs +++ b/src/Backend/Geen.Core/Domains/Leagues/Repositories/ILeagueRepository.cs @@ -1,17 +1,16 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace Geen.Core.Domains.Leagues.Repositories +namespace Geen.Core.Domains.Leagues.Repositories; + +public interface ILeagueRepository { - public interface ILeagueRepository - { - Task GetById(int id); - Task GetByUrlName(string urlName); + Task GetById(int id); + Task GetByUrlName(string urlName); - Task> GetAll(); + Task> GetAll(); - Task GetNextId(); + Task GetNextId(); - Task Save(LeagueModel model); - } -} + Task Save(LeagueModel model); +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionApproveCommand.cs b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionApproveCommand.cs index d5a2471..973668d 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionApproveCommand.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionApproveCommand.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Mentions.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Mentions.Commands +namespace Geen.Core.Domains.Mentions.Commands; + +public record MentionApproveCommand : ICommand +{ + public long Id { get; set; } +} + +public class MentionApproveCommandDispatcher : ICommandDispatcher { - public class MentionApproveCommand : ICommand + private readonly IMentionRepository _mentionRepository; + + public MentionApproveCommandDispatcher(IMentionRepository mentionRepository) { - public long Id { get; set; } + _mentionRepository = mentionRepository; } - public class MentionApproveCommandDispatcher : ICommandDispatcher + public Task Execute(MentionApproveCommand command) { - private readonly IMentionRepository _mentionRepository; - - public MentionApproveCommandDispatcher(IMentionRepository mentionRepository) - { - _mentionRepository = mentionRepository; - } - - public Task Execute(MentionApproveCommand command) - { - return _mentionRepository.Approve(command.Id); - } + return _mentionRepository.Approve(command.Id); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionChangeTextCommand.cs b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionChangeTextCommand.cs index 7078b08..1bde3f5 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionChangeTextCommand.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionChangeTextCommand.cs @@ -2,26 +2,25 @@ using Geen.Core.Domains.Mentions.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Mentions.Commands +namespace Geen.Core.Domains.Mentions.Commands; + +public record MentionChangeTextCommand : ICommand +{ + public long Id { get; set; } + public string Text { get; set; } +} + +public class MentionChangeTextCommandDispatcher : ICommandDispatcher { - public class MentionChangeTextCommand : ICommand + private readonly IMentionRepository _mentionRepository; + + public MentionChangeTextCommandDispatcher(IMentionRepository mentionRepository) { - public long Id { get; set; } - public string Text { get; set; } + _mentionRepository = mentionRepository; } - public class MentionChangeTextCommandDispatcher : ICommandDispatcher + public Task Execute(MentionChangeTextCommand command) { - private readonly IMentionRepository _mentionRepository; - - public MentionChangeTextCommandDispatcher(IMentionRepository mentionRepository) - { - _mentionRepository = mentionRepository; - } - - public Task Execute(MentionChangeTextCommand command) - { - return _mentionRepository.UpdateText(command.Id, command.Text); - } + return _mentionRepository.UpdateText(command.Id, command.Text); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionChangeTitleCommand.cs b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionChangeTitleCommand.cs index 05b5d19..ec9b3cf 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionChangeTitleCommand.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionChangeTitleCommand.cs @@ -2,26 +2,25 @@ using Geen.Core.Domains.Mentions.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Mentions.Commands +namespace Geen.Core.Domains.Mentions.Commands; + +public record MentionChangeTitleCommand : ICommand +{ + public long Id { get; set; } + public string Title { get; set; } +} + +public class MentionChangeTitleCommandDispatcher : ICommandDispatcher { - public class MentionChangeTitleCommand : ICommand + private readonly IMentionRepository _mentionRepository; + + public MentionChangeTitleCommandDispatcher(IMentionRepository mentionRepository) { - public long Id { get; set; } - public string Title { get; set; } + _mentionRepository = mentionRepository; } - public class MentionChangeTitleCommandDispatcher : ICommandDispatcher + public Task Execute(MentionChangeTitleCommand command) { - private readonly IMentionRepository _mentionRepository; - - public MentionChangeTitleCommandDispatcher(IMentionRepository mentionRepository) - { - _mentionRepository = mentionRepository; - } - - public Task Execute(MentionChangeTitleCommand command) - { - return _mentionRepository.UpdateTitle(command.Id, command.Title); - } + return _mentionRepository.UpdateTitle(command.Id, command.Title); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionCreateCommand.cs b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionCreateCommand.cs index 7fae384..6396723 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionCreateCommand.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionCreateCommand.cs @@ -10,73 +10,66 @@ using Geen.Core.Models.Mentions; using Geen.Core.Services.Text; -namespace Geen.Core.Domains.Mentions.Commands +namespace Geen.Core.Domains.Mentions.Commands; + +public record MentionCreateCommand : ICommand> +{ + public MentionCreateModel Model { get; set; } + public UserModel User { get; set; } +} + +public class MentionCreateCommandDispatcher : ICommandDispatcher> { - public class MentionCreateCommand : ICommand> + private readonly IClubRepository _clubRepository; + private readonly IContentService _contentService; + private readonly IMentionRepository _mentionRepository; + private readonly IPlayerRepository _playerRepository; + + private readonly ITextService _textService; + + public MentionCreateCommandDispatcher( + IMentionRepository mentionRepository, + ITextService textService, + IContentService contentService, + IPlayerRepository playerRepository, + IClubRepository clubRepository) { - public MentionCreateModel Model { get; set; } - public UserModel User { get; set; } + _mentionRepository = mentionRepository; + _textService = textService; + _contentService = contentService; + _playerRepository = playerRepository; + _clubRepository = clubRepository; } - public class MentionCreateCommandDispatcher : ICommandDispatcher> + public async Task Execute(MentionCreateCommand command) { - private readonly IMentionRepository _mentionRepository; - private readonly IPlayerRepository _playerRepository; - private readonly IClubRepository _clubRepository; - - private readonly ITextService _textService; - private readonly IContentService _contentService; - - public MentionCreateCommandDispatcher( - IMentionRepository mentionRepository, - ITextService textService, - IContentService contentService, - IPlayerRepository playerRepository, - IClubRepository clubRepository) + var mention = new MentionModel { - _mentionRepository = mentionRepository; - _textService = textService; - _contentService = contentService; - _playerRepository = playerRepository; - _clubRepository = clubRepository; - } + User = command.User, + Date = DateTime.UtcNow, + IsApproved = _textService.CanApproveMention(command.Model.Text) + }; - public async Task Execute(MentionCreateCommand command) + if (command.Model.PlayerId.HasValue) { - var mention = new MentionModel - { - User = command.User, - Date = DateTime.UtcNow, - IsApproved = _textService.CanApproveMention(command.Model.Text) - }; + mention.Player = await _playerRepository.GetById(command.Model.PlayerId.Value); - if (command.Model.PlayerId.HasValue) - { - mention.Player = await _playerRepository.GetById(command.Model.PlayerId.Value); + if (mention.IsApproved) await _playerRepository.IncrementMentionsCount(command.Model.PlayerId.Value); + } - if (mention.IsApproved) - { - await _playerRepository.IncrementMentionsCount(command.Model.PlayerId.Value); - } - } + if (command.Model.ClubId.HasValue) mention.Club = await _clubRepository.GetById(command.Model.ClubId.Value); - if (command.Model.ClubId.HasValue) - { - mention.Club = await _clubRepository.GetById(command.Model.ClubId.Value); - } + var processingInfo = _contentService.Process(command.Model.Text, mention.ToContentContext()); - var processingInfo = _contentService.Process(command.Model.Text, mention.ToContentContext()); + mention.Text = processingInfo.Text; - mention.Text = processingInfo.Text; + mention.Related.Players = processingInfo.PlayerIds.ToList(); + mention.Related.Clubs = processingInfo.ClubIds.ToList(); - mention.Related.Players = processingInfo.PlayerIds.ToList(); - mention.Related.Clubs = processingInfo.ClubIds.ToList(); + mention.Title = _contentService.GenerateBasicTitle(mention); - mention.Title = _contentService.GenerateBasicTitle(mention); + await _mentionRepository.Save(mention); - await _mentionRepository.Save(mention); - - return mention; - } + return mention; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionDisapproveCommand.cs b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionDisapproveCommand.cs index 87a869d..5a76c6c 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionDisapproveCommand.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionDisapproveCommand.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Mentions.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Mentions.Commands +namespace Geen.Core.Domains.Mentions.Commands; + +public record MentionDisapproveCommand : ICommand +{ + public long Id { get; set; } +} + +public class MentionDisapproveCommandDispatcher : ICommandDispatcher { - public class MentionDisapproveCommand : ICommand + private readonly IMentionRepository _mentionRepository; + + public MentionDisapproveCommandDispatcher(IMentionRepository mentionRepository) { - public long Id { get; set; } + _mentionRepository = mentionRepository; } - public class MentionDisapproveCommandDispatcher : ICommandDispatcher + public Task Execute(MentionDisapproveCommand command) { - private readonly IMentionRepository _mentionRepository; - - public MentionDisapproveCommandDispatcher(IMentionRepository mentionRepository) - { - _mentionRepository = mentionRepository; - } - - public Task Execute(MentionDisapproveCommand command) - { - return _mentionRepository.Disapprove(command.Id); - } + return _mentionRepository.Disapprove(command.Id); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionDislikeCommand.cs b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionDislikeCommand.cs index 931b157..20391d9 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionDislikeCommand.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionDislikeCommand.cs @@ -3,66 +3,65 @@ using Geen.Core.Domains.Mentions.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Mentions.Commands +namespace Geen.Core.Domains.Mentions.Commands; + +public record MentionDislikeCommand : ICommand { - public class MentionDislikeCommand : ICommand + public long Id { get; set; } + public string UserId { get; set; } +} + +public class MentionDislikeCommandDispatcher : ICommandDispatcher +{ + private readonly IMentionLikeRepository _mentionLikeRepository; + private readonly IMentionRepository _mentionRepository; + + public MentionDislikeCommandDispatcher(IMentionLikeRepository mentionLikeRepository, + IMentionRepository mentionRepository) { - public long Id { get; set; } - public string UserId { get; set; } + _mentionLikeRepository = mentionLikeRepository; + _mentionRepository = mentionRepository; } - public class MentionDislikeCommandDispatcher : ICommandDispatcher + public async Task Execute(MentionDislikeCommand command) { - private readonly IMentionLikeRepository _mentionLikeRepository; - private readonly IMentionRepository _mentionRepository; + var redisResult = await GetRedisResult(command); + + await _mentionRepository.Dislike(command.Id, redisResult); + } + + private async Task GetRedisResult(MentionDislikeCommand command) + { + var status = await _mentionLikeRepository.GetLikeStatus(command.Id, command.UserId); + + var likesIncrement = 0; + var dislikesIncrement = 0; - public MentionDislikeCommandDispatcher(IMentionLikeRepository mentionLikeRepository, - IMentionRepository mentionRepository) + if (!status.Dislikes && !status.Likes) { - _mentionLikeRepository = mentionLikeRepository; - _mentionRepository = mentionRepository; + await _mentionLikeRepository.DislikeAddUser(command.Id, command.UserId); + dislikesIncrement = 1; } - - public async Task Execute(MentionDislikeCommand command) + else if (status.Dislikes && !status.Likes) { - var redisResult = await GetRedisResult(command); - - await _mentionRepository.Dislike(command.Id, redisResult); + await _mentionLikeRepository.DislikeRemoveUser(command.Id, command.UserId); + dislikesIncrement = -1; } - - private async Task GetRedisResult(MentionDislikeCommand command) + else if (!status.Dislikes && status.Likes) { - var status = await _mentionLikeRepository.GetLikeStatus(command.Id, command.UserId); - - var likesIncrement = 0; - var dislikesIncrement = 0; - - if (!status.Dislikes && !status.Likes) - { - await _mentionLikeRepository.DislikeAddUser(command.Id, command.UserId); - dislikesIncrement = 1; - } - else if (status.Dislikes && !status.Likes) - { - await _mentionLikeRepository.DislikeRemoveUser(command.Id, command.UserId); - dislikesIncrement = -1; - } - else if (!status.Dislikes && status.Likes) - { - await Task.WhenAll( - _mentionLikeRepository.DislikeAddUser(command.Id, command.UserId), - _mentionLikeRepository.LikeRemoveUser(command.Id, command.UserId) - ); + await Task.WhenAll( + _mentionLikeRepository.DislikeAddUser(command.Id, command.UserId), + _mentionLikeRepository.LikeRemoveUser(command.Id, command.UserId) + ); - likesIncrement = -1; - dislikesIncrement = 1; - } - - return new IncrementStatus - { - Likes = likesIncrement, - Dislikes = dislikesIncrement - }; + likesIncrement = -1; + dislikesIncrement = 1; } + + return new IncrementStatus + { + Likes = likesIncrement, + Dislikes = dislikesIncrement + }; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionLikeCommand.cs b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionLikeCommand.cs index 87fb606..f61a1e5 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionLikeCommand.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionLikeCommand.cs @@ -3,66 +3,65 @@ using Geen.Core.Domains.Mentions.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Mentions.Commands +namespace Geen.Core.Domains.Mentions.Commands; + +public record MentionLikeCommand : ICommand { - public class MentionLikeCommand : ICommand + public long Id { get; set; } + public string UserId { get; set; } +} + +public class MentionLikeCommandDispatcher : ICommandDispatcher +{ + private readonly IMentionLikeRepository _mentionLikeRepository; + private readonly IMentionRepository _mentionRepository; + + public MentionLikeCommandDispatcher(IMentionLikeRepository mentionLikeRepository, + IMentionRepository mentionRepository) { - public long Id { get; set; } - public string UserId { get; set; } + _mentionLikeRepository = mentionLikeRepository; + _mentionRepository = mentionRepository; } - public class MentionLikeCommandDispatcher : ICommandDispatcher + public async Task Execute(MentionLikeCommand command) { - private readonly IMentionLikeRepository _mentionLikeRepository; - private readonly IMentionRepository _mentionRepository; + var redisResult = await GetRedisResult(command); + + await _mentionRepository.Like(command.Id, redisResult); + } + + private async Task GetRedisResult(MentionLikeCommand command) + { + var likesStatus = await _mentionLikeRepository.GetLikeStatus(command.Id, command.UserId); + + var likesIncrement = 0; + var dislikesIncrement = 0; - public MentionLikeCommandDispatcher(IMentionLikeRepository mentionLikeRepository, - IMentionRepository mentionRepository) + if (!likesStatus.Likes && !likesStatus.Dislikes) { - _mentionLikeRepository = mentionLikeRepository; - _mentionRepository = mentionRepository; + await _mentionLikeRepository.LikeAddUser(command.Id, command.UserId); + likesIncrement = 1; } - - public async Task Execute(MentionLikeCommand command) + else if (likesStatus.Likes && !likesStatus.Dislikes) { - var redisResult = await GetRedisResult(command); - - await _mentionRepository.Like(command.Id, redisResult); + await _mentionLikeRepository.LikeRemoveUser(command.Id, command.UserId); + likesIncrement = -1; } - - private async Task GetRedisResult(MentionLikeCommand command) + else if (!likesStatus.Likes && likesStatus.Dislikes) { - var likesStatus = await _mentionLikeRepository.GetLikeStatus(command.Id, command.UserId); - - var likesIncrement = 0; - var dislikesIncrement = 0; - - if (!likesStatus.Likes && !likesStatus.Dislikes) - { - await _mentionLikeRepository.LikeAddUser(command.Id, command.UserId); - likesIncrement = 1; - } - else if (likesStatus.Likes && !likesStatus.Dislikes) - { - await _mentionLikeRepository.LikeRemoveUser(command.Id, command.UserId); - likesIncrement = -1; - } - else if (!likesStatus.Likes && likesStatus.Dislikes) - { - await Task.WhenAll( - _mentionLikeRepository.LikeAddUser(command.Id, command.UserId), - _mentionLikeRepository.DislikeRemoveUser(command.Id, command.UserId) - ); + await Task.WhenAll( + _mentionLikeRepository.LikeAddUser(command.Id, command.UserId), + _mentionLikeRepository.DislikeRemoveUser(command.Id, command.UserId) + ); - likesIncrement = 1; - dislikesIncrement = -1; - } - - return new IncrementStatus - { - Likes = likesIncrement, - Dislikes = dislikesIncrement - }; + likesIncrement = 1; + dislikesIncrement = -1; } + + return new IncrementStatus + { + Likes = likesIncrement, + Dislikes = dislikesIncrement + }; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionRandomLikerCommand.cs b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionRandomLikerCommand.cs index 1668820..1ff6bf1 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionRandomLikerCommand.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionRandomLikerCommand.cs @@ -2,30 +2,29 @@ using Geen.Core.Domains.Mentions.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Mentions.Commands +namespace Geen.Core.Domains.Mentions.Commands; + +public record MentionRandomLikerCommand : ICommand { - public class MentionRandomLikerCommand : ICommand - { - public int Count { get; set; } + public int Count { get; set; } - public int MaxLikes { get; set; } - public int MaxDislikes { get; set; } + public int MaxLikes { get; set; } + public int MaxDislikes { get; set; } - public int DaysInteval { get; set; } - } + public int DaysInteval { get; set; } +} - public class MentionRandomLikerCommandDispatcher : ICommandDispatcher - { - private readonly IMentionRepository _mentionRepository; +public class MentionRandomLikerCommandDispatcher : ICommandDispatcher +{ + private readonly IMentionRepository _mentionRepository; - public MentionRandomLikerCommandDispatcher(IMentionRepository mentionRepository) - { - _mentionRepository = mentionRepository; - } + public MentionRandomLikerCommandDispatcher(IMentionRepository mentionRepository) + { + _mentionRepository = mentionRepository; + } - public Task Execute(MentionRandomLikerCommand command) - { - return _mentionRepository.RandomLikes(command); - } + public Task Execute(MentionRandomLikerCommand command) + { + return _mentionRepository.RandomLikes(command); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionRemoveCommand.cs b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionRemoveCommand.cs index 94e52c1..9422845 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionRemoveCommand.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionRemoveCommand.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Mentions.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Mentions.Commands +namespace Geen.Core.Domains.Mentions.Commands; + +public record MentionRemoveCommand : ICommand +{ + public long Id { get; set; } +} + +public class MentionRemoveCommandDispatcher : ICommandDispatcher { - public class MentionRemoveCommand : ICommand + private readonly IMentionRepository _mentionRepository; + + public MentionRemoveCommandDispatcher(IMentionRepository mentionRepository) { - public long Id { get; set; } + _mentionRepository = mentionRepository; } - public class MentionRemoveCommandDispatcher : ICommandDispatcher + public Task Execute(MentionRemoveCommand command) { - private readonly IMentionRepository _mentionRepository; - - public MentionRemoveCommandDispatcher(IMentionRepository mentionRepository) - { - _mentionRepository = mentionRepository; - } - - public Task Execute(MentionRemoveCommand command) - { - return _mentionRepository.Delete(command.Id); - } + return _mentionRepository.Delete(command.Id); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionSetDefaultAvatarCommand.cs b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionSetDefaultAvatarCommand.cs index a6233ca..0045a21 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionSetDefaultAvatarCommand.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Commands/MentionSetDefaultAvatarCommand.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Mentions.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Mentions.Commands +namespace Geen.Core.Domains.Mentions.Commands; + +public record MentionSetDefaultAvatarCommand : ICommand +{ + public long Id { get; set; } +} + +public class MentionSetDefaultAvatarCommandDispatcher : ICommandDispatcher { - public class MentionSetDefaultAvatarCommand : ICommand + private readonly IMentionRepository _mentionRepository; + + public MentionSetDefaultAvatarCommandDispatcher(IMentionRepository mentionRepository) { - public long Id { get; set; } + _mentionRepository = mentionRepository; } - public class MentionSetDefaultAvatarCommandDispatcher : ICommandDispatcher + public Task Execute(MentionSetDefaultAvatarCommand command) { - private readonly IMentionRepository _mentionRepository; - - public MentionSetDefaultAvatarCommandDispatcher(IMentionRepository mentionRepository) - { - _mentionRepository = mentionRepository; - } - - public Task Execute(MentionSetDefaultAvatarCommand command) - { - return _mentionRepository.SetDefaultAvatar(command.Id); - } + return _mentionRepository.SetDefaultAvatar(command.Id); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/MentionModel.cs b/src/Backend/Geen.Core/Domains/Mentions/MentionModel.cs index 618cfa8..111baba 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/MentionModel.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/MentionModel.cs @@ -4,60 +4,59 @@ using Geen.Core.Domains.Players; using Geen.Core.Domains.Users; -namespace Geen.Core.Domains.Mentions +namespace Geen.Core.Domains.Mentions; + +public class MentionModel { - public class MentionModel + public MentionModel() { - public MentionModel() - { - Related = new MentionRelatedModel(); - } + Related = new MentionRelatedModel(); + } - public long Id { get; set; } + public long Id { get; set; } - public string Title { get; set; } + public string Title { get; set; } - public string Text { get; set; } + public string Text { get; set; } - public DateTime Date { get; set; } + public DateTime Date { get; set; } - public UserModel User { get; set; } + public UserModel User { get; set; } - public PlayerModel Player { get; set; } + public PlayerModel Player { get; set; } - public ClubModel Club { get; set; } + public ClubModel Club { get; set; } - public int Likes { get; set; } + public int Likes { get; set; } - public int Dislikes { get; set; } + public int Dislikes { get; set; } - public double[] Location { get; set; } + public double[] Location { get; set; } - public int RepliesCount { get; set; } + public int RepliesCount { get; set; } - public string SourceUrl { get; set; } + public string SourceUrl { get; set; } - public bool IsApproved { get; set; } + public bool IsApproved { get; set; } - public MentionRelatedModel Related { get; set; } + public MentionRelatedModel Related { get; set; } - public DateTime? TitleChangeDate { get; set; } + public DateTime? TitleChangeDate { get; set; } - public bool ContainsUrlName(string urlName) - { - return Player?.UrlName == urlName || Club?.UrlName == urlName; - } + public bool ContainsUrlName(string urlName) + { + return Player?.UrlName == urlName || Club?.UrlName == urlName; + } - public class MentionRelatedModel + public class MentionRelatedModel + { + public MentionRelatedModel() { - public MentionRelatedModel() - { - Players = new List(); - Clubs = new List(); - } - - public List Players { get; set; } - public List Clubs { get; set; } + Players = new List(); + Clubs = new List(); } + + public List Players { get; set; } + public List Clubs { get; set; } } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Models/IncrementStatus.cs b/src/Backend/Geen.Core/Domains/Mentions/Models/IncrementStatus.cs index af9e1c7..6f77f84 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Models/IncrementStatus.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Models/IncrementStatus.cs @@ -1,8 +1,7 @@ -namespace Geen.Core.Domains.Mentions.Models +namespace Geen.Core.Domains.Mentions.Models; + +public class IncrementStatus { - public class IncrementStatus - { - public int Likes; - public int Dislikes; - } -} + public int Dislikes; + public int Likes; +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Queries/GetFreshMentionsQuery.cs b/src/Backend/Geen.Core/Domains/Mentions/Queries/GetFreshMentionsQuery.cs index d820b06..d73096f 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Queries/GetFreshMentionsQuery.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Queries/GetFreshMentionsQuery.cs @@ -7,120 +7,110 @@ using Geen.Core.Interfaces.Common; using Geen.Core.Utils; -namespace Geen.Core.Domains.Mentions.Queries +namespace Geen.Core.Domains.Mentions.Queries; + +public record GetFreshMentionsQuery : IQuery>> +{ + public DateTime? DateStart { get; set; } +} + +public class GetFreshMentionsQueryHandler : IQueryHandler>> { - public class GetFreshMentionsQuery : IQuery>> + private readonly ConcurrentDictionary _cache = new(); + + private readonly IMentionRepository _mentionRepository; + + public GetFreshMentionsQueryHandler(IMentionRepository mentionRepository) { - public DateTime? DateStart { get; set; } + _mentionRepository = mentionRepository; } - public class GetFreshMentionsQueryHandler : IQueryHandler>> + public async Task> Execute(GetFreshMentionsQuery query) { - private readonly IMentionRepository _mentionRepository; - - private readonly ConcurrentDictionary _cache - = new ConcurrentDictionary(); + var mentionTask = _mentionRepository.GetFreshMentions(query.DateStart); + var titledMentionTask = _mentionRepository.GetFreshTitledMentions(query.DateStart); + var repliedMentionTask = _mentionRepository.GetFreshRepliedMentionIds(query.DateStart); - public GetFreshMentionsQueryHandler(IMentionRepository mentionRepository) - { - _mentionRepository = mentionRepository; - } - - public async Task> Execute(GetFreshMentionsQuery query) - { - var mentionTask = _mentionRepository.GetFreshMentions(query.DateStart); - var titledMentionTask = _mentionRepository.GetFreshTitledMentions(query.DateStart); - var repliedMentionTask = _mentionRepository.GetFreshRepliedMentionIds(query.DateStart); + await Task.WhenAll(mentionTask, titledMentionTask, repliedMentionTask); - await Task.WhenAll(mentionTask, titledMentionTask, repliedMentionTask); + var fullMentions = mentionTask.Result + .SelectMany(x => GetMentionUrls(x)); - var fullMentions = mentionTask.Result - .SelectMany(x => GetMentionUrls(x)); + var titleMentions = titledMentionTask.Result + .SelectMany(x => GetMentionUrls(x, false, true)); - var titleMentions = titledMentionTask.Result - .SelectMany(x => GetMentionUrls(x, fromReply: false, forTitle: true)); + var fromReplyMentions = repliedMentionTask.Result + .SelectMany(x => GetMentionUrls(x, true)); - var fromReplyMentions = repliedMentionTask.Result - .SelectMany(x => GetMentionUrls(x, fromReply: true)); + return fullMentions + .Union(titleMentions) + .Union(fromReplyMentions) + .ToList(); + } - return fullMentions - .Union(titleMentions) - .Union(fromReplyMentions) - .ToList(); - } + private IEnumerable GetMentionUrls(MentionModel mention, bool fromReply = false, bool forTitle = false) + { + if (mention.Club != null) + return GetClubUrls(mention, fromReply, forTitle); - private IEnumerable GetMentionUrls(MentionModel mention, bool fromReply = false, bool forTitle = false) - { - if(mention.Club != null) - return GetClubUrls(mention, fromReply, forTitle); + return GetPlayerUrls(mention, fromReply, forTitle); + } - return GetPlayerUrls(mention, fromReply, forTitle); - } + private IEnumerable GetClubUrls(MentionModel mention, bool fromReply, bool forTitle) + { + yield return "https://geen.one/"; - private IEnumerable GetClubUrls(MentionModel mention, bool fromReply, bool forTitle) - { - yield return "https://geen.one/"; + yield return $"https://geen.one/club/{mention.Club.UrlName}/{mention.Id}"; - yield return $"https://geen.one/club/{mention.Club.UrlName}/{mention.Id}"; + if (forTitle) + yield break; - if (forTitle) - yield break; + yield return $"https://geen.one/club/{mention.Club.UrlName}"; - yield return $"https://geen.one/club/{mention.Club.UrlName}"; - - if (!fromReply) - { - var clubMentionCount = _cache.GetOrAdd(mention.Club.UrlName, clubUrlName => - _mentionRepository.GetClubItemsCount(clubUrlName)); + if (!fromReply) + { + var clubMentionCount = _cache.GetOrAdd(mention.Club.UrlName, clubUrlName => + _mentionRepository.GetClubItemsCount(clubUrlName)); - var clubPages = PagingExtensions.GetTotalPages(clubMentionCount); + var clubPages = PagingExtensions.GetTotalPages(clubMentionCount); - for (int clubPage = 2; clubPage < clubPages; clubPage++) - { - yield return $"https://geen.one/club/{mention.Club.UrlName}/page/{clubPage}"; - } - } + for (var clubPage = 2; clubPage < clubPages; clubPage++) + yield return $"https://geen.one/club/{mention.Club.UrlName}/page/{clubPage}"; + } - //---------------------- + //---------------------- - var pages = PagingExtensions.GetTotalPages(mention.RepliesCount); + var pages = PagingExtensions.GetTotalPages(mention.RepliesCount); - for(int page = 2; page <= pages; page++) - { - yield return $"https://geen.one/club/{mention.Club.UrlName}/{mention.Id}/page/{page}"; - } - } + for (var page = 2; page <= pages; page++) + yield return $"https://geen.one/club/{mention.Club.UrlName}/{mention.Id}/page/{page}"; + } - private IEnumerable GetPlayerUrls(MentionModel mention, bool fromReply, bool forTitle) - { - yield return $"https://geen.one/player/{mention.Player.UrlName}/{mention.Id}"; + private IEnumerable GetPlayerUrls(MentionModel mention, bool fromReply, bool forTitle) + { + yield return $"https://geen.one/player/{mention.Player.UrlName}/{mention.Id}"; - if (forTitle) - yield break; + if (forTitle) + yield break; - yield return $"https://geen.one/player/{mention.Player.UrlName}"; + yield return $"https://geen.one/player/{mention.Player.UrlName}"; - if (!fromReply) - { - var playerMentionCount = _cache.GetOrAdd(mention.Player.UrlName, playerUrlName => - _mentionRepository.GetClubItemsCount(playerUrlName)); + if (!fromReply) + { + var playerMentionCount = _cache.GetOrAdd(mention.Player.UrlName, playerUrlName => + _mentionRepository.GetClubItemsCount(playerUrlName)); - var playerPages = PagingExtensions.GetTotalPages(playerMentionCount); + var playerPages = PagingExtensions.GetTotalPages(playerMentionCount); - for (int playerPage = 2; playerPage < playerPages; playerPage++) - { - yield return $"https://geen.one/player/{mention.Player.UrlName}/page/{playerPage}"; - } - } + for (var playerPage = 2; playerPage < playerPages; playerPage++) + yield return $"https://geen.one/player/{mention.Player.UrlName}/page/{playerPage}"; + } - //---------------------- + //---------------------- - var pages = PagingExtensions.GetTotalPages(mention.RepliesCount); + var pages = PagingExtensions.GetTotalPages(mention.RepliesCount); - for (int page = 2; page <= pages; page++) - { - yield return $"https://geen.one/player/{mention.Player.UrlName}/{mention.Id}/page/{page}"; - } - } + for (var page = 2; page <= pages; page++) + yield return $"https://geen.one/player/{mention.Player.UrlName}/{mention.Id}/page/{page}"; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionByIdQuery.cs b/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionByIdQuery.cs index fe580b6..be93e1f 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionByIdQuery.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionByIdQuery.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Mentions.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Mentions.Queries +namespace Geen.Core.Domains.Mentions.Queries; + +public record GetMentionByIdQuery : IQuery> +{ + public long Id { get; set; } +} + +public class GetMentionByIdentityQueryHandler : IQueryHandler> { - public class GetMentionByIdQuery : IQuery> + private readonly IMentionRepository _mentionRepository; + + public GetMentionByIdentityQueryHandler(IMentionRepository mentionRepository) { - public long Id { get; set; } + _mentionRepository = mentionRepository; } - public class GetMentionByIdentityQueryHandler : IQueryHandler> + public Task Execute(GetMentionByIdQuery query) { - private readonly IMentionRepository _mentionRepository; - - public GetMentionByIdentityQueryHandler(IMentionRepository mentionRepository) - { - _mentionRepository = mentionRepository; - } - - public Task Execute(GetMentionByIdQuery query) - { - return _mentionRepository.GetById(query.Id); - } + return _mentionRepository.GetById(query.Id); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionIdentitiesQuery.cs b/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionIdentitiesQuery.cs index 44becf6..13f8531 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionIdentitiesQuery.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionIdentitiesQuery.cs @@ -3,24 +3,23 @@ using Geen.Core.Domains.Mentions.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Mentions.Queries +namespace Geen.Core.Domains.Mentions.Queries; + +public record GetMentionIdentitiesQuery : IQuery>> +{ +} + +public class GetMentionIdentitiesQueryHandler : IQueryHandler>> { - public class GetMentionIdentitiesQuery : IQuery>> + private readonly IMentionRepository _mentionRepository; + + public GetMentionIdentitiesQueryHandler(IMentionRepository mentionRepository) { + _mentionRepository = mentionRepository; } - public class GetMentionIdentitiesQueryHandler : IQueryHandler>> + public Task> Execute(GetMentionIdentitiesQuery query) { - private readonly IMentionRepository _mentionRepository; - - public GetMentionIdentitiesQueryHandler(IMentionRepository mentionRepository) - { - _mentionRepository = mentionRepository; - } - - public Task> Execute(GetMentionIdentitiesQuery query) - { - return _mentionRepository.GetMentionIdentities(); - } + return _mentionRepository.GetMentionIdentities(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionLikeStatus.cs b/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionLikeStatus.cs index e9c3fbd..f0dcaf9 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionLikeStatus.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionLikeStatus.cs @@ -3,25 +3,24 @@ using Geen.Core.Interfaces.Common; using Geen.Core.Models.Likes; -namespace Geen.Core.Domains.Mentions.Queries +namespace Geen.Core.Domains.Mentions.Queries; + +public record GetMentionLikeStatus : IQuery> +{ + public long Id { get; set; } +} + +public class GetLikeStatusQueryHandler : IQueryHandler> { - public class GetMentionLikeStatus : IQuery> + private readonly IMentionRepository _mentionRepository; + + public GetLikeStatusQueryHandler(IMentionRepository mentionRepository) { - public long Id { get; set; } + _mentionRepository = mentionRepository; } - public class GetLikeStatusQueryHandler : IQueryHandler> + public Task Execute(GetMentionLikeStatus query) { - private readonly IMentionRepository _mentionRepository; - - public GetLikeStatusQueryHandler(IMentionRepository mentionRepository) - { - _mentionRepository = mentionRepository; - } - - public Task Execute(GetMentionLikeStatus query) - { - return _mentionRepository.GetLikeStatus(query.Id); - } + return _mentionRepository.GetLikeStatus(query.Id); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionListQuery.cs b/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionListQuery.cs index 98621f3..d99db0d 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionListQuery.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionListQuery.cs @@ -3,42 +3,41 @@ using Geen.Core.Domains.Mentions.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Mentions.Queries +namespace Geen.Core.Domains.Mentions.Queries; + +public record GetMentionListQuery : IQuery>> { - public class GetMentionListQuery : IQuery>> - { - public int? PlayerId { get; set; } + public int? PlayerId { get; set; } - public string ClubUrlName { get; set; } - public string PlayerClubUrlName { get; set; } + public string ClubUrlName { get; set; } + public string PlayerClubUrlName { get; set; } - public string UserId { get; set; } + public string UserId { get; set; } - public double? Latitude { get; set; } - public double? Longitude { get; set; } + public double? Latitude { get; set; } + public double? Longitude { get; set; } - public bool? IsApproved { get; set; } + public bool? IsApproved { get; set; } - public bool? ForPlayer { get; set; } - public bool? ForClub { get; set; } + public bool? ForPlayer { get; set; } + public bool? ForClub { get; set; } - public bool Cached { get; set; } - - public int Page { get; set; } - } + public bool Cached { get; set; } - public class GetMentionListQueryHandler : IQueryHandler>> - { - private readonly IMentionRepository _mentionRepository; + public int Page { get; set; } +} - public GetMentionListQueryHandler(IMentionRepository mentionRepository) - { - _mentionRepository = mentionRepository; - } +public class GetMentionListQueryHandler : IQueryHandler>> +{ + private readonly IMentionRepository _mentionRepository; - public Task> Execute(GetMentionListQuery query) - { - return _mentionRepository.GetList(query); - } + public GetMentionListQueryHandler(IMentionRepository mentionRepository) + { + _mentionRepository = mentionRepository; } -} + + public Task> Execute(GetMentionListQuery query) + { + return _mentionRepository.GetList(query); + } +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionTitleListQuery.cs b/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionTitleListQuery.cs index 024f7a5..c771c21 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionTitleListQuery.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Queries/GetMentionTitleListQuery.cs @@ -3,26 +3,25 @@ using Geen.Core.Domains.Mentions.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Mentions.Queries +namespace Geen.Core.Domains.Mentions.Queries; + +public record GetMentionTitleListQuery : IQuery>> +{ + public long? Id { get; set; } + public int Page { get; set; } +} + +public class GetMentionTitleListQueryHandler : IQueryHandler>> { - public class GetMentionTitleListQuery : IQuery>> + private readonly IMentionRepository _mentionRepository; + + public GetMentionTitleListQueryHandler(IMentionRepository mentionRepository) { - public long? Id { get; set; } - public int Page { get; set; } + _mentionRepository = mentionRepository; } - public class GetMentionTitleListQueryHandler : IQueryHandler>> + public Task> Execute(GetMentionTitleListQuery query) { - private readonly IMentionRepository _mentionRepository; - - public GetMentionTitleListQueryHandler(IMentionRepository mentionRepository) - { - _mentionRepository = mentionRepository; - } - - public Task> Execute(GetMentionTitleListQuery query) - { - return _mentionRepository.GetMentionTitleList(query.Id, query.Page); - } + return _mentionRepository.GetMentionTitleList(query.Id, query.Page); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Repositories/IMentionLikeRepository.cs b/src/Backend/Geen.Core/Domains/Mentions/Repositories/IMentionLikeRepository.cs index 60b1f84..5c48391 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Repositories/IMentionLikeRepository.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Repositories/IMentionLikeRepository.cs @@ -1,16 +1,15 @@ using System.Threading.Tasks; using Geen.Core.Models.Likes; -namespace Geen.Core.Domains.Mentions.Repositories +namespace Geen.Core.Domains.Mentions.Repositories; + +public interface IMentionLikeRepository { - public interface IMentionLikeRepository - { - Task GetLikeStatus(long id, string userId); + Task GetLikeStatus(long id, string userId); - Task LikeAddUser(long id, string userId); - Task LikeRemoveUser(long id, string userId); + Task LikeAddUser(long id, string userId); + Task LikeRemoveUser(long id, string userId); - Task DislikeAddUser(long id, string userId); - Task DislikeRemoveUser(long id, string userId); - } -} + Task DislikeAddUser(long id, string userId); + Task DislikeRemoveUser(long id, string userId); +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Mentions/Repositories/IMentionRepository.cs b/src/Backend/Geen.Core/Domains/Mentions/Repositories/IMentionRepository.cs index 35113be..67a3312 100644 --- a/src/Backend/Geen.Core/Domains/Mentions/Repositories/IMentionRepository.cs +++ b/src/Backend/Geen.Core/Domains/Mentions/Repositories/IMentionRepository.cs @@ -6,48 +6,47 @@ using Geen.Core.Domains.Mentions.Queries; using Geen.Core.Models.Likes; -namespace Geen.Core.Domains.Mentions.Repositories +namespace Geen.Core.Domains.Mentions.Repositories; + +public interface IMentionRepository { - public interface IMentionRepository - { - Task GetById(long id); - Task> GetMentionIdentities(); - Task> GetMentionTitleList(long? id, int page); - Task> GetList(GetMentionListQuery query); + Task GetById(long id); + Task> GetMentionIdentities(); + Task> GetMentionTitleList(long? id, int page); + Task> GetList(GetMentionListQuery query); + + Task> GetFreshMentions(DateTime? dateStart); + Task> GetFreshTitledMentions(DateTime? dateStart); + Task> GetFreshRepliedMentionIds(DateTime? dateStart); + long GetClubItemsCount(string clubUrlName); + long GetPlayerItemsCount(string playerUrlName); + + Task GetLikeStatus(long id); - Task> GetFreshMentions(DateTime? dateStart); - Task> GetFreshTitledMentions(DateTime? dateStart); - Task> GetFreshRepliedMentionIds(DateTime? dateStart); - long GetClubItemsCount(string clubUrlName); - long GetPlayerItemsCount(string playerUrlName); + Task Approve(long id); + Task Disapprove(long id); - Task GetLikeStatus(long id); + Task Like(long id, IncrementStatus status); + Task Dislike(long id, IncrementStatus status); - Task Approve(long id); - Task Disapprove(long id); + Task UpdateTitle(long id, string title); + Task UpdateText(long id, string text); + Task UpdateUser(long id, string userName); - Task Like(long id, IncrementStatus status); - Task Dislike(long id, IncrementStatus status); + Task SetDefaultAvatar(long id); - Task UpdateTitle(long id, string title); - Task UpdateText(long id, string text); - Task UpdateUser(long id, string userName); + Task Save(MentionModel model); - Task SetDefaultAvatar(long id); - - Task Save(MentionModel model); + Task Delete(long id); - Task Delete(long id); + Task IncrementRepliesCount(long id); + Task DecrementRepliesCount(long id); - Task IncrementRepliesCount(long id); - Task DecrementRepliesCount(long id); + #region Temp - #region Temp + Task RandomLikes(MentionRandomLikerCommand command); - Task RandomLikes(MentionRandomLikerCommand command); - - Task> GetAll(int count); + Task> GetAll(int count); - #endregion - } -} + #endregion +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Players/Commands/PlayerSaveCommand.cs b/src/Backend/Geen.Core/Domains/Players/Commands/PlayerSaveCommand.cs index 0a66926..99124a5 100644 --- a/src/Backend/Geen.Core/Domains/Players/Commands/PlayerSaveCommand.cs +++ b/src/Backend/Geen.Core/Domains/Players/Commands/PlayerSaveCommand.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Players.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Players.Commands +namespace Geen.Core.Domains.Players.Commands; + +public record PlayerSaveCommand : ICommand +{ + public PlayerModel Model { get; set; } +} + +public class PlayerSaveCommandDispatcher : ICommandDispatcher { - public class PlayerSaveCommand : ICommand + private readonly IPlayerRepository _playerRepository; + + public PlayerSaveCommandDispatcher(IPlayerRepository playerRepository) { - public PlayerModel Model { get; set; } + _playerRepository = playerRepository; } - public class PlayerSaveCommandDispatcher : ICommandDispatcher + public Task Execute(PlayerSaveCommand command) { - private readonly IPlayerRepository _playerRepository; - - public PlayerSaveCommandDispatcher(IPlayerRepository playerRepository) - { - _playerRepository = playerRepository; - } - - public Task Execute(PlayerSaveCommand command) - { - return _playerRepository.Save(command.Model); - } + return _playerRepository.Save(command.Model); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Players/PlayerModel.cs b/src/Backend/Geen.Core/Domains/Players/PlayerModel.cs index 4c250b1..1677900 100644 --- a/src/Backend/Geen.Core/Domains/Players/PlayerModel.cs +++ b/src/Backend/Geen.Core/Domains/Players/PlayerModel.cs @@ -1,25 +1,24 @@ using System; using Geen.Core.Domains.Clubs; -namespace Geen.Core.Domains.Players +namespace Geen.Core.Domains.Players; + +public class PlayerModel { - public class PlayerModel - { - public int Id { get; set; } + public int Id { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } - public string UrlName { get; set; } + public string UrlName { get; set; } - public DateTime BirthDate { get; set; } + public DateTime BirthDate { get; set; } - public int Position { get; set; } + public int Position { get; set; } - public ClubModel Club { get; set; } + public ClubModel Club { get; set; } - public long Votes { get; set; } + public long Votes { get; set; } - public long MentionsCount { get; set; } - } -} + public long MentionsCount { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Players/Queries/GetByClubUrlNameQuery.cs b/src/Backend/Geen.Core/Domains/Players/Queries/GetByClubUrlNameQuery.cs index 67ca259..2ed5925 100644 --- a/src/Backend/Geen.Core/Domains/Players/Queries/GetByClubUrlNameQuery.cs +++ b/src/Backend/Geen.Core/Domains/Players/Queries/GetByClubUrlNameQuery.cs @@ -5,7 +5,7 @@ namespace Geen.Core.Domains.Players.Queries; -public class PlayerGetByClubUrlNameQuery : IQuery>> +public record PlayerGetByClubUrlNameQuery : IQuery>> { public string ClubUrlName { get; set; } } diff --git a/src/Backend/Geen.Core/Domains/Players/Queries/GetPlayerIdsByClubAndPositionQuery.cs b/src/Backend/Geen.Core/Domains/Players/Queries/GetPlayerIdsByClubAndPositionQuery.cs index e53f919..35cb344 100644 --- a/src/Backend/Geen.Core/Domains/Players/Queries/GetPlayerIdsByClubAndPositionQuery.cs +++ b/src/Backend/Geen.Core/Domains/Players/Queries/GetPlayerIdsByClubAndPositionQuery.cs @@ -5,13 +5,14 @@ namespace Geen.Core.Domains.Players.Queries; -public class GetPlayerIdsByClubAndPositionQuery : IQuery>> +public record GetPlayerIdsByClubAndPositionQuery : IQuery>> { public string ClubUrlName { get; set; } public int Position { get; set; } } -public class GetPlayerIdsByClubAndPositionQueryHandler : IQueryHandler>> +public class + GetPlayerIdsByClubAndPositionQueryHandler : IQueryHandler>> { private readonly IPlayerRepository _playerRepository; diff --git a/src/Backend/Geen.Core/Domains/Players/Queries/GetPlayersByIdsQuery.cs b/src/Backend/Geen.Core/Domains/Players/Queries/GetPlayersByIdsQuery.cs index 849cf1d..72c75da 100644 --- a/src/Backend/Geen.Core/Domains/Players/Queries/GetPlayersByIdsQuery.cs +++ b/src/Backend/Geen.Core/Domains/Players/Queries/GetPlayersByIdsQuery.cs @@ -5,7 +5,7 @@ namespace Geen.Core.Domains.Players.Queries; -public class GetPlayerModelsByIdsQuery : IQuery>> +public record GetPlayerModelsByIdsQuery : IQuery>> { public List PlayerIds { get; set; } } diff --git a/src/Backend/Geen.Core/Domains/Players/Queries/GetRandomPlayerQuery.cs b/src/Backend/Geen.Core/Domains/Players/Queries/GetRandomPlayerQuery.cs index 3b2c418..e0e6d75 100644 --- a/src/Backend/Geen.Core/Domains/Players/Queries/GetRandomPlayerQuery.cs +++ b/src/Backend/Geen.Core/Domains/Players/Queries/GetRandomPlayerQuery.cs @@ -4,7 +4,7 @@ namespace Geen.Core.Domains.Players.Queries; -public class GetRandomPlayerQuery : IQuery> +public record GetRandomPlayerQuery : IQuery> { } diff --git a/src/Backend/Geen.Core/Domains/Players/Queries/GetRelatedPlayersQuery.cs b/src/Backend/Geen.Core/Domains/Players/Queries/GetRelatedPlayersQuery.cs index 4eb3b85..85f0f02 100644 --- a/src/Backend/Geen.Core/Domains/Players/Queries/GetRelatedPlayersQuery.cs +++ b/src/Backend/Geen.Core/Domains/Players/Queries/GetRelatedPlayersQuery.cs @@ -5,7 +5,7 @@ namespace Geen.Core.Domains.Players.Queries; -public class GetRelatedPlayerQuery : IQuery>> +public record GetRelatedPlayerQuery : IQuery>> { public string UrlName { get; set; } } diff --git a/src/Backend/Geen.Core/Domains/Players/Queries/GetTopPlayersQuery.cs b/src/Backend/Geen.Core/Domains/Players/Queries/GetTopPlayersQuery.cs index 4528d6c..d3e4da4 100644 --- a/src/Backend/Geen.Core/Domains/Players/Queries/GetTopPlayersQuery.cs +++ b/src/Backend/Geen.Core/Domains/Players/Queries/GetTopPlayersQuery.cs @@ -5,7 +5,7 @@ namespace Geen.Core.Domains.Players.Queries; -public class GetTopPlayerQuery : IQuery>> +public record GetTopPlayerQuery : IQuery>> { public string ClubUrlName { get; set; } } diff --git a/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetByIdQuery.cs b/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetByIdQuery.cs index 5923025..5212092 100644 --- a/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetByIdQuery.cs +++ b/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetByIdQuery.cs @@ -4,7 +4,7 @@ namespace Geen.Core.Domains.Players.Queries; -public class PlayerGetByIdQuery : IQuery> +public record PlayerGetByIdQuery : IQuery> { public int Id { get; set; } } diff --git a/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetByUrlName.cs b/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetByUrlName.cs index 8d1f223..4cb42a0 100644 --- a/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetByUrlName.cs +++ b/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetByUrlName.cs @@ -4,7 +4,7 @@ namespace Geen.Core.Domains.Players.Queries; -public class PlayerGetByUrlName : IQuery> +public record PlayerGetByUrlName : IQuery> { public string UrlName { get; set; } } diff --git a/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetListQuery.cs b/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetListQuery.cs index dcce6a4..7d9f807 100644 --- a/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetListQuery.cs +++ b/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetListQuery.cs @@ -7,7 +7,7 @@ namespace Geen.Core.Domains.Players.Queries; public class PlayerGetListQuery : IQuery>> { - public string Query { get;set; } + public string Query { get; set; } public string ClubUrlName { get; set; } diff --git a/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetUrlsQuery.cs b/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetUrlsQuery.cs index 3328ab1..453c73f 100644 --- a/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetUrlsQuery.cs +++ b/src/Backend/Geen.Core/Domains/Players/Queries/PlayerGetUrlsQuery.cs @@ -5,7 +5,7 @@ namespace Geen.Core.Domains.Players.Queries; -public class PlayerGetUrlsQuery : IQuery>> +public record PlayerGetUrlsQuery : IQuery>> { } diff --git a/src/Backend/Geen.Core/Domains/Players/Queries/PlayerNextIdQuery.cs b/src/Backend/Geen.Core/Domains/Players/Queries/PlayerNextIdQuery.cs index 93f2222..e9917c0 100644 --- a/src/Backend/Geen.Core/Domains/Players/Queries/PlayerNextIdQuery.cs +++ b/src/Backend/Geen.Core/Domains/Players/Queries/PlayerNextIdQuery.cs @@ -4,7 +4,7 @@ namespace Geen.Core.Domains.Players.Queries; -public class PlayerNextIdQuery : IQuery> +public record PlayerNextIdQuery : IQuery> { } diff --git a/src/Backend/Geen.Core/Domains/Players/Queries/PlayersForCacheQuery.cs b/src/Backend/Geen.Core/Domains/Players/Queries/PlayersForCacheQuery.cs index d4e2c24..1337847 100644 --- a/src/Backend/Geen.Core/Domains/Players/Queries/PlayersForCacheQuery.cs +++ b/src/Backend/Geen.Core/Domains/Players/Queries/PlayersForCacheQuery.cs @@ -5,7 +5,7 @@ namespace Geen.Core.Domains.Players.Queries; -public class PlayerForCacheQuery : IQuery>> +public record PlayerForCacheQuery : IQuery>> { public string ClubUrlName { get; set; } } diff --git a/src/Backend/Geen.Core/Domains/Players/Queries/SearchPlayerQuery.cs b/src/Backend/Geen.Core/Domains/Players/Queries/SearchPlayerQuery.cs index ee49cca..66a878e 100644 --- a/src/Backend/Geen.Core/Domains/Players/Queries/SearchPlayerQuery.cs +++ b/src/Backend/Geen.Core/Domains/Players/Queries/SearchPlayerQuery.cs @@ -5,7 +5,7 @@ namespace Geen.Core.Domains.Players.Queries; -public class SearchPlayerQuery : IQuery>> +public record SearchPlayerQuery : IQuery>> { public string Query { get; set; } } diff --git a/src/Backend/Geen.Core/Domains/Players/Repositories/IPlayerRepository.cs b/src/Backend/Geen.Core/Domains/Players/Repositories/IPlayerRepository.cs index 4832518..2b44101 100644 --- a/src/Backend/Geen.Core/Domains/Players/Repositories/IPlayerRepository.cs +++ b/src/Backend/Geen.Core/Domains/Players/Repositories/IPlayerRepository.cs @@ -1,39 +1,38 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace Geen.Core.Domains.Players.Repositories +namespace Geen.Core.Domains.Players.Repositories; + +public interface IPlayerRepository { - public interface IPlayerRepository - { - Task GetById(int id); - Task GetByUrlName(string urlName); - - Task GetClubCoach(string clubUrlName); - - Task> GetList(string query, string clubUrlName, int page); - Task> GetCached(); - - Task> GetUrls(); - - Task> GetByClubUrlName(string clubUrlName); - Task> GetIdsByClubAndPosition(string clubUrlName, int position); - - Task> GetByIds(List ids); - Task> GetTopPlayers(string clubUrlName); - Task> GetRelatedPlayers(string urlName); - - Task GetRandom(); - - Task<(PlayerModel Left, PlayerModel Right)> GetForVotes(int position); - - Task> GetAll(); - - Task GetNextId(); - - Task IncrementMentionsCount(int id); - - Task Save(PlayerModel model); - - Task> Search(string query, int count); - } -} + Task GetById(int id); + Task GetByUrlName(string urlName); + + Task GetClubCoach(string clubUrlName); + + Task> GetList(string query, string clubUrlName, int page); + Task> GetCached(); + + Task> GetUrls(); + + Task> GetByClubUrlName(string clubUrlName); + Task> GetIdsByClubAndPosition(string clubUrlName, int position); + + Task> GetByIds(List ids); + Task> GetTopPlayers(string clubUrlName); + Task> GetRelatedPlayers(string urlName); + + Task GetRandom(); + + Task<(PlayerModel Left, PlayerModel Right)> GetForVotes(int position); + + Task> GetAll(); + + Task GetNextId(); + + Task IncrementMentionsCount(int id); + + Task Save(PlayerModel model); + + Task> Search(string query, int count); +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Players/Utils/Randomizer.cs b/src/Backend/Geen.Core/Domains/Players/Utils/Randomizer.cs index 8715110..9693926 100644 --- a/src/Backend/Geen.Core/Domains/Players/Utils/Randomizer.cs +++ b/src/Backend/Geen.Core/Domains/Players/Utils/Randomizer.cs @@ -1,15 +1,13 @@ using System; using System.Threading; -namespace Geen.Core.Domains.Players.Utils +namespace Geen.Core.Domains.Players.Utils; + +public static class Randomizer { - public static class Randomizer - { - private static int _seed; + private static int _seed; - private static readonly ThreadLocal _random - = new ThreadLocal(() => new Random(Interlocked.Increment(ref _seed))); + private static readonly ThreadLocal _random = new(() => new Random(Interlocked.Increment(ref _seed))); - public static Random RandomLocal => _random.Value; - } -} + public static Random RandomLocal => _random.Value; +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyApproveCommand.cs b/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyApproveCommand.cs index e20a29d..873b99e 100644 --- a/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyApproveCommand.cs +++ b/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyApproveCommand.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Replies.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Replies.Commands +namespace Geen.Core.Domains.Replies.Commands; + +public record ReplyApproveCommand : ICommand +{ + public string Id { get; set; } +} + +public class ReplyApproveCommandDispatcher : ICommandDispatcher { - public class ReplyApproveCommand : ICommand + private readonly IReplyRepository _replyRepository; + + public ReplyApproveCommandDispatcher(IReplyRepository replyRepository) { - public string Id { get; set; } + _replyRepository = replyRepository; } - public class ReplyApproveCommandDispatcher : ICommandDispatcher + public Task Execute(ReplyApproveCommand command) { - private readonly IReplyRepository _replyRepository; - - public ReplyApproveCommandDispatcher(IReplyRepository replyRepository) - { - _replyRepository = replyRepository; - } - - public Task Execute(ReplyApproveCommand command) - { - return _replyRepository.Approve(command.Id); - } + return _replyRepository.Approve(command.Id); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyChangeTextCommand.cs b/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyChangeTextCommand.cs index 712157d..54e6155 100644 --- a/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyChangeTextCommand.cs +++ b/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyChangeTextCommand.cs @@ -2,26 +2,25 @@ using Geen.Core.Domains.Replies.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Replies.Commands +namespace Geen.Core.Domains.Replies.Commands; + +public record ReplyChangeTextCommand : ICommand +{ + public string Id { get; set; } + public string Text { get; set; } +} + +public class ReplyChangeTextCommandDispatcher : ICommandDispatcher { - public class ReplyChangeTextCommand : ICommand + private readonly IReplyRepository _replyRepository; + + public ReplyChangeTextCommandDispatcher(IReplyRepository replyRepository) { - public string Id { get; set; } - public string Text { get; set; } + _replyRepository = replyRepository; } - public class ReplyChangeTextCommandDispatcher : ICommandDispatcher + public Task Execute(ReplyChangeTextCommand command) { - private readonly IReplyRepository _replyRepository; - - public ReplyChangeTextCommandDispatcher(IReplyRepository replyRepository) - { - _replyRepository = replyRepository; - } - - public Task Execute(ReplyChangeTextCommand command) - { - return _replyRepository.UpdateText(command.Id, command.Text); - } + return _replyRepository.UpdateText(command.Id, command.Text); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyCreateCommand.cs b/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyCreateCommand.cs index e644ce6..9ab22fd 100644 --- a/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyCreateCommand.cs +++ b/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyCreateCommand.cs @@ -8,58 +8,56 @@ using Geen.Core.Models.Replies; using Geen.Core.Services.Text; -namespace Geen.Core.Domains.Replies.Commands +namespace Geen.Core.Domains.Replies.Commands; + +public record ReplyCreateCommand : ICommand> { - public class ReplyCreateCommand : ICommand> + public ReplyCreateModel Model { get; set; } + public UserModel User { get; set; } +} + +public class ReplyCreateCommandDispatcher : ICommandDispatcher> +{ + private readonly IContentService _contentService; + private readonly IMentionRepository _mentionRepository; + private readonly IReplyRepository _replyRepository; + + private readonly ITextService _textService; + + public ReplyCreateCommandDispatcher(IContentService contentService, + IMentionRepository mentionRepository, + IReplyRepository replyRepository, ITextService textService) { - public ReplyCreateModel Model { get; set; } - public UserModel User { get; set; } + _contentService = contentService; + _replyRepository = replyRepository; + _textService = textService; + _mentionRepository = mentionRepository; + _replyRepository = replyRepository; } - public class ReplyCreateCommandDispatcher : ICommandDispatcher> + public async Task Execute(ReplyCreateCommand command) { - private readonly IReplyRepository _replyRepository; - private readonly IMentionRepository _mentionRepository; - - private readonly ITextService _textService; + var mention = await _mentionRepository.GetById(command.Model.MentionId); - private readonly IContentService _contentService; + if (mention == null) + throw new ArgumentException(nameof(ReplyCreateModel)); - public ReplyCreateCommandDispatcher(IContentService contentService, - IMentionRepository mentionRepository, - IReplyRepository replyRepository, ITextService textService) - { - _contentService = contentService; - _replyRepository = replyRepository; - _textService = textService; - _mentionRepository = mentionRepository; - _replyRepository = replyRepository; - } + var contentProcessingResult = _contentService.Process(command.Model.Text, mention.ToContentContext()); - public async Task Execute(ReplyCreateCommand command) + var reply = new ReplyModel { - var mention = await _mentionRepository.GetById(command.Model.MentionId); - - if (mention == null) - throw new ArgumentException(nameof(ReplyCreateModel)); + MentionId = command.Model.MentionId, + Text = contentProcessingResult.Text, + User = command.User, + Date = DateTime.UtcNow, + IsApproved = _textService.CanApproveMention(command.Model.Text) + }; - var contentProcessingResult = _contentService.Process(command.Model.Text, mention.ToContentContext()); + await _replyRepository.Save(reply); - var reply = new ReplyModel - { - MentionId = command.Model.MentionId, - Text = contentProcessingResult.Text, - User = command.User, - Date = DateTime.UtcNow, - IsApproved = _textService.CanApproveMention(command.Model.Text) - }; + if (reply.IsApproved) + await _mentionRepository.IncrementRepliesCount(reply.MentionId); - await _replyRepository.Save(reply); - - if (reply.IsApproved) - await _mentionRepository.IncrementRepliesCount(reply.MentionId); - - return reply; - } + return reply; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyDisapproveCommand.cs b/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyDisapproveCommand.cs index 819b910..09be058 100644 --- a/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyDisapproveCommand.cs +++ b/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyDisapproveCommand.cs @@ -2,25 +2,24 @@ using Geen.Core.Domains.Replies.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Replies.Commands +namespace Geen.Core.Domains.Replies.Commands; + +public record ReplyDisapproveCommand : ICommand +{ + public string Id { get; set; } +} + +public class ReplyDisapproveCommandDispatcher : ICommandDispatcher { - public class ReplyDisapproveCommand : ICommand + private readonly IReplyRepository _replyRepository; + + public ReplyDisapproveCommandDispatcher(IReplyRepository replyRepository) { - public string Id { get; set; } + _replyRepository = replyRepository; } - public class ReplyDisapproveCommandDispatcher : ICommandDispatcher + public Task Execute(ReplyDisapproveCommand command) { - private readonly IReplyRepository _replyRepository; - - public ReplyDisapproveCommandDispatcher(IReplyRepository replyRepository) - { - _replyRepository = replyRepository; - } - - public Task Execute(ReplyDisapproveCommand command) - { - return _replyRepository.Disapprove(command.Id); - } + return _replyRepository.Disapprove(command.Id); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyRemoveCommand.cs b/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyRemoveCommand.cs index 81e8302..e8fdcf9 100644 --- a/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyRemoveCommand.cs +++ b/src/Backend/Geen.Core/Domains/Replies/Commands/ReplyRemoveCommand.cs @@ -3,33 +3,32 @@ using Geen.Core.Domains.Replies.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Replies.Commands +namespace Geen.Core.Domains.Replies.Commands; + +public record ReplyRemoveCommand : ICommand { - public class ReplyRemoveCommand : ICommand + public string ReplyId { get; set; } +} + +public class ReplyRemoveCommandDispatcher : ICommandDispatcher +{ + private readonly IMentionRepository _mentionRepository; + private readonly IReplyRepository _replyRepository; + + public ReplyRemoveCommandDispatcher(IReplyRepository replyRepository, IMentionRepository mentionRepository) { - public string ReplyId { get; set; } + _replyRepository = replyRepository; + _mentionRepository = mentionRepository; } - public class ReplyRemoveCommandDispatcher : ICommandDispatcher + public async Task Execute(ReplyRemoveCommand command) { - private readonly IReplyRepository _replyRepository; - private readonly IMentionRepository _mentionRepository; - - public ReplyRemoveCommandDispatcher(IReplyRepository replyRepository, IMentionRepository mentionRepository) - { - _replyRepository = replyRepository; - _mentionRepository = mentionRepository; - } - - public async Task Execute(ReplyRemoveCommand command) - { - //TODO Transactioned sessions - - var replyModel = await _replyRepository.GetById(command.ReplyId); - - await _replyRepository.Delete(command.ReplyId); - - await _mentionRepository.DecrementRepliesCount(replyModel.MentionId); - } + //TODO Transactioned sessions + + var replyModel = await _replyRepository.GetById(command.ReplyId); + + await _replyRepository.Delete(command.ReplyId); + + await _mentionRepository.DecrementRepliesCount(replyModel.MentionId); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Replies/Queries/GetReplyLatestQuery.cs b/src/Backend/Geen.Core/Domains/Replies/Queries/GetReplyLatestQuery.cs index c9ca578..dfd8f5c 100644 --- a/src/Backend/Geen.Core/Domains/Replies/Queries/GetReplyLatestQuery.cs +++ b/src/Backend/Geen.Core/Domains/Replies/Queries/GetReplyLatestQuery.cs @@ -3,29 +3,27 @@ using Geen.Core.Domains.Replies.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Replies.Queries +namespace Geen.Core.Domains.Replies.Queries; + +public record GetReplyLatestQuery : IQuery>> +{ + public long? ClubId { get; set; } + public int? PlayerId { get; set; } + + public int Count { get; set; } +} + +public class GetReplyLatestQueryHandler : IQueryHandler>> { - public class GetReplyLatestQuery : IQuery>> + private readonly IReplyRepository _replyRepository; + + public GetReplyLatestQueryHandler(IReplyRepository replyRepository) { - public long? ClubId { get; set; } - public int? PlayerId { get; set; } - - public int Count { get; set; } + _replyRepository = replyRepository; } - public class GetReplyLatestQueryHandler : IQueryHandler>> + public Task> Execute(GetReplyLatestQuery query) { - private readonly IReplyRepository _replyRepository; - - public GetReplyLatestQueryHandler(IReplyRepository replyRepository) - { - _replyRepository = replyRepository; - } - - public Task> Execute(GetReplyLatestQuery query) - { - return _replyRepository.GetLatestList(query); - } + return _replyRepository.GetLatestList(query); } -} - \ No newline at end of file +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Replies/Queries/GetReplyListQuery.cs b/src/Backend/Geen.Core/Domains/Replies/Queries/GetReplyListQuery.cs index 5adf4c8..f540a47 100644 --- a/src/Backend/Geen.Core/Domains/Replies/Queries/GetReplyListQuery.cs +++ b/src/Backend/Geen.Core/Domains/Replies/Queries/GetReplyListQuery.cs @@ -3,28 +3,26 @@ using Geen.Core.Domains.Replies.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Replies.Queries +namespace Geen.Core.Domains.Replies.Queries; + +public record GetReplyListQuery : IQuery>> { - public class GetReplyListQuery : IQuery>> - { - public long MentionId { get; set; } + public long MentionId { get; set; } - public int Page { get; set; } - } + public int Page { get; set; } +} - public class GetReplyListQueryHandler : IQueryHandler>> - { - private readonly IReplyRepository _replyRepository; +public class GetReplyListQueryHandler : IQueryHandler>> +{ + private readonly IReplyRepository _replyRepository; - public GetReplyListQueryHandler(IReplyRepository replyRepository) - { - _replyRepository = replyRepository; - } + public GetReplyListQueryHandler(IReplyRepository replyRepository) + { + _replyRepository = replyRepository; + } - public Task> Execute(GetReplyListQuery query) - { - return _replyRepository.GetList(query); - } + public Task> Execute(GetReplyListQuery query) + { + return _replyRepository.GetList(query); } -} - \ No newline at end of file +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Replies/Queries/GetReplyUnapprovedListQuery.cs b/src/Backend/Geen.Core/Domains/Replies/Queries/GetReplyUnapprovedListQuery.cs index 77af9bf..27caadb 100644 --- a/src/Backend/Geen.Core/Domains/Replies/Queries/GetReplyUnapprovedListQuery.cs +++ b/src/Backend/Geen.Core/Domains/Replies/Queries/GetReplyUnapprovedListQuery.cs @@ -3,30 +3,28 @@ using Geen.Core.Domains.Replies.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Replies.Queries +namespace Geen.Core.Domains.Replies.Queries; + +public record GetReplyUnapprovedListQuery : IQuery>> { - public class GetReplyUnapprovedListQuery : IQuery>> - { - public long? MentionId { get; set; } + public long? MentionId { get; set; } - public bool? IsApproved { get; set; } + public bool? IsApproved { get; set; } - public int Page { get; set; } - } + public int Page { get; set; } +} - public class GetReplyUnapprovedListQueryHandler : IQueryHandler>> - { - private readonly IReplyRepository _replyRepository; +public class GetReplyUnapprovedListQueryHandler : IQueryHandler>> +{ + private readonly IReplyRepository _replyRepository; - public GetReplyUnapprovedListQueryHandler(IReplyRepository replyRepository) - { - _replyRepository = replyRepository; - } + public GetReplyUnapprovedListQueryHandler(IReplyRepository replyRepository) + { + _replyRepository = replyRepository; + } - public Task> Execute(GetReplyUnapprovedListQuery query) - { - return _replyRepository.GetUnapprovedList(query); - } + public Task> Execute(GetReplyUnapprovedListQuery query) + { + return _replyRepository.GetUnapprovedList(query); } -} - \ No newline at end of file +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Replies/ReplyModel.cs b/src/Backend/Geen.Core/Domains/Replies/ReplyModel.cs index 33005dc..b2aece9 100644 --- a/src/Backend/Geen.Core/Domains/Replies/ReplyModel.cs +++ b/src/Backend/Geen.Core/Domains/Replies/ReplyModel.cs @@ -1,20 +1,19 @@ using System; using Geen.Core.Domains.Users; -namespace Geen.Core.Domains.Replies +namespace Geen.Core.Domains.Replies; + +public record ReplyModel { - public class ReplyModel - { - public string Id { get; set; } + public string Id { get; set; } - public long MentionId { get; set; } + public long MentionId { get; set; } - public string Text { get; set; } + public string Text { get; set; } - public DateTime Date { get; set; } + public DateTime Date { get; set; } - public UserModel User { get; set; } + public UserModel User { get; set; } - public bool IsApproved { get; set; } - } -} + public bool IsApproved { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Replies/Repositories/IReplyLikeRepository.cs b/src/Backend/Geen.Core/Domains/Replies/Repositories/IReplyLikeRepository.cs index 82bfa4c..e519fe3 100644 --- a/src/Backend/Geen.Core/Domains/Replies/Repositories/IReplyLikeRepository.cs +++ b/src/Backend/Geen.Core/Domains/Replies/Repositories/IReplyLikeRepository.cs @@ -1,16 +1,15 @@ using System.Threading.Tasks; using Geen.Core.Models.Likes; -namespace Geen.Core.Domains.Replies.Repositories +namespace Geen.Core.Domains.Replies.Repositories; + +public interface IReplyLikeRepository { - public interface IReplyLikeRepository - { - Task GetLikeStatus(string id, string userId); + Task GetLikeStatus(string id, string userId); - Task LikeAddUser(string id, string userId); - Task LikeRemoveUser(string id, string userId); + Task LikeAddUser(string id, string userId); + Task LikeRemoveUser(string id, string userId); - Task DislikeAddUser(string id, string userId); - Task DislikeRemoveUser(string id, string userId); - } -} + Task DislikeAddUser(string id, string userId); + Task DislikeRemoveUser(string id, string userId); +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Replies/Repositories/IReplyRepository.cs b/src/Backend/Geen.Core/Domains/Replies/Repositories/IReplyRepository.cs index bd30cd9..2280f55 100644 --- a/src/Backend/Geen.Core/Domains/Replies/Repositories/IReplyRepository.cs +++ b/src/Backend/Geen.Core/Domains/Replies/Repositories/IReplyRepository.cs @@ -2,27 +2,26 @@ using System.Threading.Tasks; using Geen.Core.Domains.Replies.Queries; -namespace Geen.Core.Domains.Replies.Repositories +namespace Geen.Core.Domains.Replies.Repositories; + +public interface IReplyRepository { - public interface IReplyRepository - { - Task GetById(string id); + Task GetById(string id); + + Task> GetList(GetReplyListQuery query); + Task> GetLatestList(GetReplyLatestQuery query); + Task> GetUnapprovedList(GetReplyUnapprovedListQuery query); - Task> GetList(GetReplyListQuery query); - Task> GetLatestList(GetReplyLatestQuery query); - Task> GetUnapprovedList(GetReplyUnapprovedListQuery query); + Task Approve(string id); + Task Disapprove(string id); - Task Approve(string id); - Task Disapprove(string id); + Task UpdateText(string id, string text); - Task UpdateText(string id, string text); + Task Save(ReplyModel model); - Task Save(ReplyModel model); + Task Delete(string id); - Task Delete(string id); - - Task> GetAll(int count); + Task> GetAll(int count); - Task UpdateUser(string id, string userName); - } -} + Task UpdateUser(string id, string userName); +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Search/Queries/SearchQuery.cs b/src/Backend/Geen.Core/Domains/Search/Queries/SearchQuery.cs index 3364dab..2a5bed5 100644 --- a/src/Backend/Geen.Core/Domains/Search/Queries/SearchQuery.cs +++ b/src/Backend/Geen.Core/Domains/Search/Queries/SearchQuery.cs @@ -4,27 +4,25 @@ using Geen.Core.Domains.Players.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Search.Queries +namespace Geen.Core.Domains.Search.Queries; + +public record SearchQuery : IQuery>> +{ + public string Query { get; set; } + public int Count { get; set; } +} + +public class SearchQueryHandler : IQueryHandler>> { - public class SearchQuery : IQuery>> + private readonly IPlayerRepository _playerRepository; + + public SearchQueryHandler(IPlayerRepository playerRepository) { - public string Query { get; set; } - public int Count { get; set; } + _playerRepository = playerRepository; } - public class SearchQueryHandler : IQueryHandler>> + public Task> Execute(SearchQuery query) { - private readonly IPlayerRepository _playerRepository; - - public SearchQueryHandler(IPlayerRepository playerRepository) - { - _playerRepository = playerRepository; - } - - public Task> Execute(SearchQuery query) - { - return _playerRepository.Search(query.Query, query.Count); - } + return _playerRepository.Search(query.Query, query.Count); } -} - \ No newline at end of file +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Users/UserModel.cs b/src/Backend/Geen.Core/Domains/Users/UserModel.cs index d9168aa..292a36e 100644 --- a/src/Backend/Geen.Core/Domains/Users/UserModel.cs +++ b/src/Backend/Geen.Core/Domains/Users/UserModel.cs @@ -1,13 +1,12 @@ -namespace Geen.Core.Domains.Users +namespace Geen.Core.Domains.Users; + +public record UserModel { - public class UserModel - { - public string Id { get; set; } + public string Id { get; set; } + + public string Name { get; set; } - public string Name { get; set; } + public string ProfileImage { get; set; } - public string ProfileImage { get; set; } - - public bool? IsAnonymous { get; set; } - } -} + public bool? IsAnonymous { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Votes/Commands/CreateVoteCommand.cs b/src/Backend/Geen.Core/Domains/Votes/Commands/CreateVoteCommand.cs index 6cf6a52..0e01957 100644 --- a/src/Backend/Geen.Core/Domains/Votes/Commands/CreateVoteCommand.cs +++ b/src/Backend/Geen.Core/Domains/Votes/Commands/CreateVoteCommand.cs @@ -3,36 +3,35 @@ using Geen.Core.Domains.Votes.Repositories; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Votes.Commands +namespace Geen.Core.Domains.Votes.Commands; + +public record CreateVoteCommand : ICommand +{ + public int? LeftPlayerId { get; set; } + public int? RightPlayerId { get; set; } + + public int? WinnerId { get; set; } +} + +public class CreateVoteCommandDispatcher : ICommandDispatcher { - public class CreateVoteCommand : ICommand + private readonly IVoteRepository _voteRepository; + + public CreateVoteCommandDispatcher(IVoteRepository voteRepository) { - public int? LeftPlayerId { get; set; } - public int? RightPlayerId { get; set; } - - public int? WinnerId { get; set; } + _voteRepository = voteRepository; } - public class CreateVoteCommandDispatcher : ICommandDispatcher + public Task Execute(CreateVoteCommand command) { - private readonly IVoteRepository _voteRepository; - - public CreateVoteCommandDispatcher(IVoteRepository voteRepository) + var model = new VoteModel { - _voteRepository = voteRepository; - } + LeftPlayerId = command.LeftPlayerId, + RightPlayerId = command.RightPlayerId, + WinnerId = command.WinnerId, + Date = DateTime.UtcNow + }; - public Task Execute(CreateVoteCommand command) - { - var model = new VoteModel - { - LeftPlayerId = command.LeftPlayerId, - RightPlayerId = command.RightPlayerId, - WinnerId = command.WinnerId, - Date = DateTime.UtcNow - }; - - return _voteRepository.Create(model); - } + return _voteRepository.Create(model); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Votes/Queries/GetVoteDataQuery.cs b/src/Backend/Geen.Core/Domains/Votes/Queries/GetVoteDataQuery.cs index 3d6d4a8..bd75a77 100644 --- a/src/Backend/Geen.Core/Domains/Votes/Queries/GetVoteDataQuery.cs +++ b/src/Backend/Geen.Core/Domains/Votes/Queries/GetVoteDataQuery.cs @@ -3,32 +3,31 @@ using Geen.Core.Domains.Players.Utils; using Geen.Core.Interfaces.Common; -namespace Geen.Core.Domains.Votes.Queries +namespace Geen.Core.Domains.Votes.Queries; + +public record GetVoteDataQuery : IQuery> +{ +} + +public class GetVoteDataQueryHandler : IQueryHandler> { - public class GetVoteDataQuery : IQuery> + private readonly IPlayerRepository _playerRepository; + + public GetVoteDataQueryHandler(IPlayerRepository playerRepository) { + _playerRepository = playerRepository; } - public class GetVoteDataQueryHandler : IQueryHandler> + public async Task Execute(GetVoteDataQuery query) { - private readonly IPlayerRepository _playerRepository; + var position = Randomizer.RandomLocal.Next(0, 5); - public GetVoteDataQueryHandler(IPlayerRepository playerRepository) - { - _playerRepository = playerRepository; - } + var votesPlayers = await _playerRepository.GetForVotes(position); - public async Task Execute(GetVoteDataQuery query) + return new VoteFullModel { - var position = Randomizer.RandomLocal.Next(0, 5); - - var votesPlayers = await _playerRepository.GetForVotes(position); - - return new VoteFullModel - { - Left = votesPlayers.Left, - Right = votesPlayers.Right - }; - } + Left = votesPlayers.Left, + Right = votesPlayers.Right + }; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Votes/Repositories/IVoteRepository.cs b/src/Backend/Geen.Core/Domains/Votes/Repositories/IVoteRepository.cs index c076b21..2e05e0e 100644 --- a/src/Backend/Geen.Core/Domains/Votes/Repositories/IVoteRepository.cs +++ b/src/Backend/Geen.Core/Domains/Votes/Repositories/IVoteRepository.cs @@ -1,9 +1,8 @@ using System.Threading.Tasks; -namespace Geen.Core.Domains.Votes.Repositories +namespace Geen.Core.Domains.Votes.Repositories; + +public interface IVoteRepository { - public interface IVoteRepository - { - Task Create(VoteModel model); - } -} + Task Create(VoteModel model); +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Domains/Votes/VoteModel.cs b/src/Backend/Geen.Core/Domains/Votes/VoteModel.cs index 9690764..b417695 100644 --- a/src/Backend/Geen.Core/Domains/Votes/VoteModel.cs +++ b/src/Backend/Geen.Core/Domains/Votes/VoteModel.cs @@ -1,23 +1,22 @@ using System; using Geen.Core.Domains.Players; -namespace Geen.Core.Domains.Votes +namespace Geen.Core.Domains.Votes; + +public class VoteModel { - public class VoteModel - { - public string Id { get; set; } + public string Id { get; set; } + + public int? LeftPlayerId { get; set; } + public int? RightPlayerId { get; set; } - public int? LeftPlayerId { get; set; } - public int? RightPlayerId { get; set; } - - public int? WinnerId { get; set; } + public int? WinnerId { get; set; } - public DateTime Date {get;set;} - } - - public class VoteFullModel - { - public PlayerModel Left { get; set; } - public PlayerModel Right{ get; set; } - } + public DateTime Date { get; set; } +} + +public class VoteFullModel +{ + public PlayerModel Left { get; set; } + public PlayerModel Right { get; set; } } \ No newline at end of file diff --git a/src/Backend/Geen.Core/Geen.Core.csproj b/src/Backend/Geen.Core/Geen.Core.csproj index 6fd6428..8c06efa 100644 --- a/src/Backend/Geen.Core/Geen.Core.csproj +++ b/src/Backend/Geen.Core/Geen.Core.csproj @@ -1,8 +1,8 @@  - - net7.0 - - - - + + net7.0 + + + + \ No newline at end of file diff --git a/src/Backend/Geen.Core/Interfaces/Common/ICommand.cs b/src/Backend/Geen.Core/Interfaces/Common/ICommand.cs index ea6d366..c10b8ea 100644 --- a/src/Backend/Geen.Core/Interfaces/Common/ICommand.cs +++ b/src/Backend/Geen.Core/Interfaces/Common/ICommand.cs @@ -1,17 +1,16 @@ -namespace Geen.Core.Interfaces.Common -{ - public interface ICommand - { - } +namespace Geen.Core.Interfaces.Common; - public interface ICommandDispatcher - { - TResult Execute(ICommand command); - } +public interface ICommand +{ +} - public interface ICommandDispatcher - where TCommand : ICommand - { - TResult Execute(TCommand query); - } +public interface ICommandDispatcher +{ + TResult Execute(ICommand command); } + +public interface ICommandDispatcher + where TCommand : ICommand +{ + TResult Execute(TCommand query); +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Interfaces/Common/IQuery.cs b/src/Backend/Geen.Core/Interfaces/Common/IQuery.cs index b3f524e..33f6550 100644 --- a/src/Backend/Geen.Core/Interfaces/Common/IQuery.cs +++ b/src/Backend/Geen.Core/Interfaces/Common/IQuery.cs @@ -1,17 +1,16 @@ -namespace Geen.Core.Interfaces.Common -{ - public interface IQuery - { - } +namespace Geen.Core.Interfaces.Common; - public interface IQueryDispatcher - { - TResult Execute(IQuery query); - } +public interface IQuery +{ +} - public interface IQueryHandler - where TQuery : IQuery - { - TResult Execute(TQuery query); - } +public interface IQueryDispatcher +{ + TResult Execute(IQuery query); } + +public interface IQueryHandler + where TQuery : IQuery +{ + TResult Execute(TQuery query); +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Models/Content/ContentContext.cs b/src/Backend/Geen.Core/Models/Content/ContentContext.cs index 88a4f65..a561262 100644 --- a/src/Backend/Geen.Core/Models/Content/ContentContext.cs +++ b/src/Backend/Geen.Core/Models/Content/ContentContext.cs @@ -1,11 +1,10 @@ using Geen.Core.Domains.Clubs; using Geen.Core.Domains.Players; -namespace Geen.Core.Models.Content +namespace Geen.Core.Models.Content; + +public class ContentContext { - public class ContentContext - { - public ClubModel Club { get; set; } - public PlayerModel Player { get; set; } - } -} + public ClubModel Club { get; set; } + public PlayerModel Player { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Models/Content/Extensions/ContentExtensions.cs b/src/Backend/Geen.Core/Models/Content/Extensions/ContentExtensions.cs index 66af7c6..b29ca59 100644 --- a/src/Backend/Geen.Core/Models/Content/Extensions/ContentExtensions.cs +++ b/src/Backend/Geen.Core/Models/Content/Extensions/ContentExtensions.cs @@ -1,16 +1,15 @@ using Geen.Core.Domains.Mentions; -namespace Geen.Core.Models.Content.Extensions +namespace Geen.Core.Models.Content.Extensions; + +public static class ContentExtensions { - public static class ContentExtensions + public static ContentContext ToContentContext(this MentionModel obj) { - public static ContentContext ToContentContext(this MentionModel obj) + return new ContentContext { - return new ContentContext - { - Club = obj.Club, - Player = obj.Player - }; - } + Club = obj.Club, + Player = obj.Player + }; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Models/Likes/LikeModel.cs b/src/Backend/Geen.Core/Models/Likes/LikeModel.cs index 6603d6e..6c85041 100644 --- a/src/Backend/Geen.Core/Models/Likes/LikeModel.cs +++ b/src/Backend/Geen.Core/Models/Likes/LikeModel.cs @@ -1,14 +1,13 @@ -namespace Geen.Core.Models.Likes -{ - public class LikeModel - { - public int Likes { get; set; } - public int Dislikes { get; set; } - } +namespace Geen.Core.Models.Likes; - public class LikeStatus - { - public bool Likes { get; set; } - public bool Dislikes { get; set; } - } +public class LikeModel +{ + public int Likes { get; set; } + public int Dislikes { get; set; } } + +public class LikeStatus +{ + public bool Likes { get; set; } + public bool Dislikes { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Models/Mentions/EntityInfo.cs b/src/Backend/Geen.Core/Models/Mentions/EntityInfo.cs index 7dee0c4..e1354ca 100644 --- a/src/Backend/Geen.Core/Models/Mentions/EntityInfo.cs +++ b/src/Backend/Geen.Core/Models/Mentions/EntityInfo.cs @@ -1,11 +1,10 @@ -namespace Geen.Core.Models.Mentions +namespace Geen.Core.Models.Mentions; + +public class EntityInfo { - public class EntityInfo - { - public int Id { get; set; } + public int Id { get; set; } - public string Url { get; set; } + public string Url { get; set; } - public static EntityInfo Empty => new EntityInfo(); - } -} + public static EntityInfo Empty => new(); +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Models/Mentions/MentionCreateModel.cs b/src/Backend/Geen.Core/Models/Mentions/MentionCreateModel.cs index a909a47..8a20aec 100644 --- a/src/Backend/Geen.Core/Models/Mentions/MentionCreateModel.cs +++ b/src/Backend/Geen.Core/Models/Mentions/MentionCreateModel.cs @@ -1,10 +1,9 @@ -namespace Geen.Core.Models.Mentions +namespace Geen.Core.Models.Mentions; + +public class MentionCreateModel { - public class MentionCreateModel - { - public string Text { get; set; } + public string Text { get; set; } - public int? PlayerId { get; set; } - public int? ClubId { get; set; } - } -} + public int? PlayerId { get; set; } + public int? ClubId { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Models/Replies/ReplyCreateModel.cs b/src/Backend/Geen.Core/Models/Replies/ReplyCreateModel.cs index 82af30e..588a93e 100644 --- a/src/Backend/Geen.Core/Models/Replies/ReplyCreateModel.cs +++ b/src/Backend/Geen.Core/Models/Replies/ReplyCreateModel.cs @@ -1,13 +1,12 @@ using Geen.Core.Domains.Users; -namespace Geen.Core.Models.Replies +namespace Geen.Core.Models.Replies; + +public class ReplyCreateModel { - public class ReplyCreateModel - { - public long MentionId { get; set; } + public long MentionId { get; set; } - public UserModel User { get; set; } + public UserModel User { get; set; } - public string Text { get; set; } - } -} + public string Text { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Registration.cs b/src/Backend/Geen.Core/Registration.cs index 360b363..f50d2be 100644 --- a/src/Backend/Geen.Core/Registration.cs +++ b/src/Backend/Geen.Core/Registration.cs @@ -5,44 +5,43 @@ using Geen.Core.Services.Text; using Microsoft.Extensions.DependencyInjection; -namespace Geen.Core +namespace Geen.Core; + +public static class Registration { - public static class Registration + public static void RegisterCoreServices(this IServiceCollection services) { - public static void RegisterCoreServices(this IServiceCollection services) - { - services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); - var assemblyTypes = Assembly.GetExecutingAssembly().GetTypes(); + var assemblyTypes = Assembly.GetExecutingAssembly().GetTypes(); - services.RegisterCommandsAndQueries(assemblyTypes); - } + services.RegisterCommandsAndQueries(assemblyTypes); + } - private static void RegisterCommandsAndQueries(this IServiceCollection services, IReadOnlyCollection types) - { - var queries = types.Where(x => x.FullName.EndsWith("QueryHandler")); + private static void RegisterCommandsAndQueries(this IServiceCollection services, IReadOnlyCollection types) + { + var queries = types.Where(x => x.FullName.EndsWith("QueryHandler")); - foreach (var handler in queries) - { - var handlerInterface = handler.GetInterfaces().FirstOrDefault(); + foreach (var handler in queries) + { + var handlerInterface = handler.GetInterfaces().FirstOrDefault(); - if (handlerInterface == null) - continue; + if (handlerInterface == null) + continue; - services.AddTransient(handlerInterface, handler); - } + services.AddTransient(handlerInterface, handler); + } - var commands = types.Where(x => x.FullName.EndsWith("CommandDispatcher")); - foreach (var dispatcher in commands) - { - var dispatcherInterface = dispatcher.GetInterfaces().FirstOrDefault(); + var commands = types.Where(x => x.FullName.EndsWith("CommandDispatcher")); + foreach (var dispatcher in commands) + { + var dispatcherInterface = dispatcher.GetInterfaces().FirstOrDefault(); - if (dispatcherInterface == null) - continue; + if (dispatcherInterface == null) + continue; - services.AddTransient(dispatcherInterface, dispatcher); - } + services.AddTransient(dispatcherInterface, dispatcher); } } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Services/Interfaces/IClubCacheRepository.cs b/src/Backend/Geen.Core/Services/Interfaces/IClubCacheRepository.cs index dd06810..3f26e21 100644 --- a/src/Backend/Geen.Core/Services/Interfaces/IClubCacheRepository.cs +++ b/src/Backend/Geen.Core/Services/Interfaces/IClubCacheRepository.cs @@ -1,10 +1,9 @@ using Geen.Core.Models.Content; using Geen.Core.Models.Mentions; -namespace Geen.Core.Services.Interfaces +namespace Geen.Core.Services.Interfaces; + +public interface IClubCacheRepository { - public interface IClubCacheRepository - { - EntityInfo GetClubUrl(string word, ContentContext context); - } -} + EntityInfo GetClubUrl(string word, ContentContext context); +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Services/Interfaces/IPlayerCacheRepository.cs b/src/Backend/Geen.Core/Services/Interfaces/IPlayerCacheRepository.cs index 0dee974..752e7cf 100644 --- a/src/Backend/Geen.Core/Services/Interfaces/IPlayerCacheRepository.cs +++ b/src/Backend/Geen.Core/Services/Interfaces/IPlayerCacheRepository.cs @@ -1,10 +1,9 @@ using Geen.Core.Models.Content; using Geen.Core.Models.Mentions; -namespace Geen.Core.Services.Interfaces +namespace Geen.Core.Services.Interfaces; + +public interface IPlayerCacheRepository { - public interface IPlayerCacheRepository - { - EntityInfo GetPlayerUrl(string word, ContentContext context); - } -} + EntityInfo GetPlayerUrl(string word, ContentContext context); +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Services/Text/ContentService.cs b/src/Backend/Geen.Core/Services/Text/ContentService.cs index bc78fee..52d9093 100644 --- a/src/Backend/Geen.Core/Services/Text/ContentService.cs +++ b/src/Backend/Geen.Core/Services/Text/ContentService.cs @@ -8,154 +8,148 @@ using Geen.Core.Services.Interfaces; using Geen.Core.Services.Text.Extensions; -namespace Geen.Core.Services.Text +namespace Geen.Core.Services.Text; + +public interface IContentService +{ + ContentProcessingResult Process(string text, ContentContext context); + string GenerateBasicTitle(MentionModel mention); +} + +public class ContentService : IContentService { - public interface IContentService + private readonly IClubCacheRepository _clubCacheRepository; + private readonly IPlayerCacheRepository _playerCacheRepository; + + public ContentService(IPlayerCacheRepository playerCacheRepository, + IClubCacheRepository clubCacheRepository) { - ContentProcessingResult Process(string text, ContentContext context); - string GenerateBasicTitle(MentionModel mention); + _playerCacheRepository = playerCacheRepository; + _clubCacheRepository = clubCacheRepository; } - - public class ContentService : IContentService + + public ContentProcessingResult Process(string text, ContentContext context) { - private readonly IPlayerCacheRepository _playerCacheRepository; - private readonly IClubCacheRepository _clubCacheRepository; + var cleanedText = text.Trim().AsText(); - public ContentService(IPlayerCacheRepository playerCacheRepository, - IClubCacheRepository clubCacheRepository) - { - _playerCacheRepository = playerCacheRepository; - _clubCacheRepository = clubCacheRepository; - } + var builder = new StringBuilder(cleanedText); - public ContentProcessingResult Process(string text, ContentContext context) - { - var cleanedText = text.Trim().AsText(); + var words = cleanedText + .Split(new[] { ' ', ',', '.', '(', ')', '\n', '-', '/', '\\', '<', '>' }, + StringSplitOptions.RemoveEmptyEntries) + .Where(x => x.Length > 3); - var builder = new StringBuilder(cleanedText); + var result = new ContentProcessingResult(); - var words = cleanedText - .Split(new[] { ' ', ',', '.', '(', ')', '\n', '-', '/', '\\', '<', '>' }, StringSplitOptions.RemoveEmptyEntries) - .Where(x => x.Length > 3); + var replacedWords = new HashSet(); - var result = new ContentProcessingResult(); + foreach (var word in words) + { + if (replacedWords.Contains(word)) + continue; - var replacedWords = new HashSet(); - - foreach (var word in words) - { - if(replacedWords.Contains(word)) - continue; - - var loweredWord = word.ToLower(); - - var playerInfo = _playerCacheRepository.GetPlayerUrl(loweredWord, context); - if (!string.IsNullOrWhiteSpace(playerInfo.Url)) - { - builder.Replace(word, $"{word}"); - result.PlayerIds.Add(playerInfo.Id); - - replacedWords.Add(word); - } - - var clubInfo = _clubCacheRepository.GetClubUrl(loweredWord, context); - if (!string.IsNullOrWhiteSpace(clubInfo.Url)) - { - builder.Replace(word, $"{word}"); - result.ClubIds.Add(clubInfo.Id); - - replacedWords.Add(word); - } - } + var loweredWord = word.ToLower(); - result.Text = builder.ToString(); + var playerInfo = _playerCacheRepository.GetPlayerUrl(loweredWord, context); + if (!string.IsNullOrWhiteSpace(playerInfo.Url)) + { + builder.Replace(word, $"{word}"); + result.PlayerIds.Add(playerInfo.Id); - return result; - } + replacedWords.Add(word); + } - public string GenerateBasicTitle(MentionModel mention) - { - if (mention.Player != null) + var clubInfo = _clubCacheRepository.GetClubUrl(loweredWord, context); + if (!string.IsNullOrWhiteSpace(clubInfo.Url)) { - return GenerateTitleForPlayer(mention); - } - - if (mention.Club != null) - { - return GenerateTitleForClub(mention); - } + builder.Replace(word, $"{word}"); + result.ClubIds.Add(clubInfo.Id); - return string.Empty; + replacedWords.Add(word); + } } - private string GenerateTitleForPlayer(MentionModel playerMention) - { - return ExtractPhraze(playerMention.Text); - } + result.Text = builder.ToString(); - private string GenerateTitleForClub(MentionModel clubMention) - { - return ExtractPhraze(clubMention.Text); - } + return result; + } - private string ExtractPhraze(string text) - { - var cleanText = StripTextFromTags(text); + public string GenerateBasicTitle(MentionModel mention) + { + if (mention.Player != null) return GenerateTitleForPlayer(mention); - var wordSplittedText = cleanText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + if (mention.Club != null) return GenerateTitleForClub(mention); - if(wordSplittedText.Length > 9) - return ClearTailFromNonAplha(string.Join(" ", wordSplittedText.Take(9))); + return string.Empty; + } - if (char.IsLower(cleanText.First())) - return MakeFirstLetterUppercase(cleanText); + private string GenerateTitleForPlayer(MentionModel playerMention) + { + return ExtractPhraze(playerMention.Text); + } - return ClearTailFromNonAplha(cleanText); - } + private string GenerateTitleForClub(MentionModel clubMention) + { + return ExtractPhraze(clubMention.Text); + } - private static string MakeFirstLetterUppercase(string text) - { - return text.First().ToString().ToUpper() + text.Substring(1); - } + private string ExtractPhraze(string text) + { + var cleanText = StripTextFromTags(text); - private static string ClearTailFromNonAplha(string text) - { - var lastAlphaIndex = text.Length - 1; + var wordSplittedText = cleanText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); - while (lastAlphaIndex >= 1 && !Char.IsLetterOrDigit(text[lastAlphaIndex])) - lastAlphaIndex--; + if (wordSplittedText.Length > 9) + return ClearTailFromNonAplha(string.Join(" ", wordSplittedText.Take(9))); - return text.Substring(0, lastAlphaIndex + 1); - } + if (char.IsLower(cleanText.First())) + return MakeFirstLetterUppercase(cleanText); - private string StripTextFromTags(string text) - { - if (string.IsNullOrWhiteSpace(text)) - return string.Empty; + return ClearTailFromNonAplha(cleanText); + } - string s = Regex.Replace(text, @"<(.|\n)*?>", string.Empty); + private static string MakeFirstLetterUppercase(string text) + { + return text.First().ToString().ToUpper() + text.Substring(1); + } - s = s.Replace(" ", " "); + private static string ClearTailFromNonAplha(string text) + { + var lastAlphaIndex = text.Length - 1; - s = Regex.Replace(s, @"\s+", " "); - s = Regex.Replace(s, @"\r\n", " "); - s = Regex.Replace(s, @"\n+", " "); + while (lastAlphaIndex >= 1 && !char.IsLetterOrDigit(text[lastAlphaIndex])) + lastAlphaIndex--; - return s; - } + return text.Substring(0, lastAlphaIndex + 1); } - public class ContentProcessingResult + private string StripTextFromTags(string text) { - public ContentProcessingResult() - { - PlayerIds = new SortedSet(); - ClubIds = new SortedSet(); - } + if (string.IsNullOrWhiteSpace(text)) + return string.Empty; + + var s = Regex.Replace(text, @"<(.|\n)*?>", string.Empty); + + s = s.Replace(" ", " "); - public string Text { get; set; } + s = Regex.Replace(s, @"\s+", " "); + s = Regex.Replace(s, @"\r\n", " "); + s = Regex.Replace(s, @"\n+", " "); - public SortedSet PlayerIds { get; set; } - public SortedSet ClubIds { get; set; } + return s; } } + +public class ContentProcessingResult +{ + public ContentProcessingResult() + { + PlayerIds = new SortedSet(); + ClubIds = new SortedSet(); + } + + public string Text { get; set; } + + public SortedSet PlayerIds { get; set; } + public SortedSet ClubIds { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Services/Text/Extensions/TextExtensions.cs b/src/Backend/Geen.Core/Services/Text/Extensions/TextExtensions.cs index 4966aaa..2d72d68 100644 --- a/src/Backend/Geen.Core/Services/Text/Extensions/TextExtensions.cs +++ b/src/Backend/Geen.Core/Services/Text/Extensions/TextExtensions.cs @@ -1,25 +1,24 @@ using System.Text; using System.Text.RegularExpressions; -namespace Geen.Core.Services.Text.Extensions +namespace Geen.Core.Services.Text.Extensions; + +public static class TextExtensions { - public static class TextExtensions + private static readonly Regex HtmlCleanRegexp = new("<.*?>", RegexOptions.Compiled); + + public static string AsText(this string input) { - private static readonly Regex HtmlCleanRegexp = new Regex("<.*?>", RegexOptions.Compiled); - - public static string AsText(this string input) - { - if (string.IsNullOrWhiteSpace(input)) - return string.Empty; + if (string.IsNullOrWhiteSpace(input)) + return string.Empty; - var builder = new StringBuilder(input); + var builder = new StringBuilder(input); - builder.Replace(" ,", ", "); - builder.Replace(" .", ". "); + builder.Replace(" ,", ", "); + builder.Replace(" .", ". "); - builder.Replace(" ", " "); + builder.Replace(" ", " "); - return HtmlCleanRegexp.Replace(builder.ToString(), string.Empty).Replace("\n", "
"); - } + return HtmlCleanRegexp.Replace(builder.ToString(), string.Empty).Replace("\n", "
"); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Services/Text/TextService.cs b/src/Backend/Geen.Core/Services/Text/TextService.cs index c92e963..5062b79 100644 --- a/src/Backend/Geen.Core/Services/Text/TextService.cs +++ b/src/Backend/Geen.Core/Services/Text/TextService.cs @@ -1,43 +1,42 @@ using System.Collections.Generic; using System.Linq; -namespace Geen.Core.Services.Text +namespace Geen.Core.Services.Text; + +public interface ITextService +{ + bool CanApproveMention(string text); +} + +public class TextService : ITextService { - public interface ITextService + private readonly List _domains; + + public TextService() { - bool CanApproveMention(string text); + _domains = new List + { + ".ru", + ".com", + ".net", + ".online" + }; } - - public class TextService : ITextService - { - private readonly List _domains; - public TextService() - { - _domains = new List - { - ".ru", - ".com", - ".net", - ".online" - }; - } - - public bool CanApproveMention(string text) - { - if (text.Contains("http")) - return false; + public bool CanApproveMention(string text) + { + if (text.Contains("http")) + return false; - if (text.Contains("//")) - return false; + if (text.Contains("//")) + return false; - if (text.Length < 100) - return false; + if (text.Length < 100) + return false; - if (_domains.Any(text.Contains)) - return false; + if (_domains.Any(text.Contains)) + return false; - return true; - } + return true; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Core/Services/Voting/VotingService.cs b/src/Backend/Geen.Core/Services/Voting/VotingService.cs index 9a56fd1..2a2de64 100644 --- a/src/Backend/Geen.Core/Services/Voting/VotingService.cs +++ b/src/Backend/Geen.Core/Services/Voting/VotingService.cs @@ -50,3 +50,4 @@ // } // } //} + diff --git a/src/Backend/Geen.Core/Utils/PagingExtensions.cs b/src/Backend/Geen.Core/Utils/PagingExtensions.cs index e2fe0fa..a8b5073 100644 --- a/src/Backend/Geen.Core/Utils/PagingExtensions.cs +++ b/src/Backend/Geen.Core/Utils/PagingExtensions.cs @@ -1,14 +1,13 @@ using System; -namespace Geen.Core.Utils +namespace Geen.Core.Utils; + +public static class PagingExtensions { - public static class PagingExtensions - { - private const int PageSize = 30; + private const int PageSize = 30; - public static int GetTotalPages(long items) - { - return (int)Math.Ceiling((double)items / PageSize); - } + public static int GetTotalPages(long items) + { + return (int)Math.Ceiling((double)items / PageSize); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Caches/ClubCacheRepository.cs b/src/Backend/Geen.Data/Caches/ClubCacheRepository.cs index aa6cd09..db5bdd9 100644 --- a/src/Backend/Geen.Data/Caches/ClubCacheRepository.cs +++ b/src/Backend/Geen.Data/Caches/ClubCacheRepository.cs @@ -9,35 +9,34 @@ using Geen.Core.Models.Mentions; using Geen.Core.Services.Interfaces; -namespace Geen.Data.Caches +namespace Geen.Data.Caches; + +public class ClubCacheRepository : IClubCacheRepository { - public class ClubCacheRepository : IClubCacheRepository + private readonly Lazy>> _cache; + + public ClubCacheRepository(IQueryDispatcher queryDispatcher) { - private readonly Lazy>> _cache; - - public ClubCacheRepository(IQueryDispatcher queryDispatcher) - { - _cache = new Lazy>>(async () - => await queryDispatcher.Execute(new ClubsForCacheQuery())); - } + _cache = new Lazy>>(async () + => await queryDispatcher.Execute(new ClubsForCacheQuery())); + } - public EntityInfo GetClubUrl(string word, ContentContext context) - { - var clubKeys = _cache.Value.Result.Keys.Where(word.StartsWith).ToList(); + public EntityInfo GetClubUrl(string word, ContentContext context) + { + var clubKeys = _cache.Value.Result.Keys.Where(word.StartsWith).ToList(); - if (clubKeys.Count != 1) - return EntityInfo.Empty; + if (clubKeys.Count != 1) + return EntityInfo.Empty; - var club = _cache.Value.Result[clubKeys.FirstOrDefault()]; + var club = _cache.Value.Result[clubKeys.FirstOrDefault()]; - if (club.Id == context.Club?.Id) - return EntityInfo.Empty; + if (club.Id == context.Club?.Id) + return EntityInfo.Empty; - return new EntityInfo - { - Id = club.Id, - Url = club.UrlName - }; - } + return new EntityInfo + { + Id = club.Id, + Url = club.UrlName + }; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Caches/PlayerCacheRepository.cs b/src/Backend/Geen.Data/Caches/PlayerCacheRepository.cs index 6d1eef4..f61f8de 100644 --- a/src/Backend/Geen.Data/Caches/PlayerCacheRepository.cs +++ b/src/Backend/Geen.Data/Caches/PlayerCacheRepository.cs @@ -9,62 +9,61 @@ using Geen.Core.Models.Mentions; using Geen.Core.Services.Interfaces; -namespace Geen.Data.Caches +namespace Geen.Data.Caches; + +public class PlayerCacheRepository : IPlayerCacheRepository { - public class PlayerCacheRepository : IPlayerCacheRepository + private readonly Lazy>> _cache; + + public PlayerCacheRepository(IQueryDispatcher queryDispatcher) { - private readonly Lazy>> _cache; + _cache = new Lazy>>( + () => queryDispatcher.Execute(new PlayerForCacheQuery())); + } - public PlayerCacheRepository(IQueryDispatcher queryDispatcher) - { - _cache = new Lazy>>( - () => queryDispatcher.Execute(new PlayerForCacheQuery())); - } + public EntityInfo GetPlayerUrl(string word, ContentContext context) + { + var players = _cache.Value.Result + .Where(player => word.StartsWith(player.LastName)) + .ToList(); + + if (players.Count == 0) + return EntityInfo.Empty; - public EntityInfo GetPlayerUrl(string word, ContentContext context) + if (players.Count == 1) { - var players = _cache.Value.Result - .Where(player => word.StartsWith(player.LastName)) - .ToList(); + var player = players.SingleOrDefault(); - if (players.Count == 0) + if (player.Id == context.Player?.Id || player.Id == 20) return EntityInfo.Empty; - if (players.Count == 1) + var currentPlayer = players.SingleOrDefault(); + + return new EntityInfo { - var player = players.SingleOrDefault(); + Id = currentPlayer.Id, + Url = currentPlayer.UrlName + }; + } - if(player.Id == context.Player?.Id || player.Id == 20) - return EntityInfo.Empty; + var clubPlayers = players + .Where(x => x.Club?.Id == context.Club?.Id) + .ToList(); - var currentPlayer = players.SingleOrDefault(); + if (clubPlayers.Count == 1) + { + var clubPlayer = clubPlayers.SingleOrDefault(); - return new EntityInfo - { - Id = currentPlayer.Id, - Url = currentPlayer.UrlName - }; - } - - var clubPlayers = players - .Where(x => x.Club?.Id == context.Club?.Id) - .ToList(); + if (clubPlayer.Id == context.Player?.Id || clubPlayer.Id == 20) + return EntityInfo.Empty; - if (clubPlayers.Count == 1) + return new EntityInfo { - var clubPlayer = clubPlayers.SingleOrDefault(); - - if (clubPlayer.Id == context.Player?.Id || clubPlayer.Id == 20) - return EntityInfo.Empty; - - return new EntityInfo - { - Id = clubPlayer.Id, - Url = clubPlayer.UrlName - }; - } - - return EntityInfo.Empty; + Id = clubPlayer.Id, + Url = clubPlayer.UrlName + }; } + + return EntityInfo.Empty; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Entities/Attributes/MongoEntityAttribute.cs b/src/Backend/Geen.Data/Entities/Attributes/MongoEntityAttribute.cs index 20621a8..31a97d6 100644 --- a/src/Backend/Geen.Data/Entities/Attributes/MongoEntityAttribute.cs +++ b/src/Backend/Geen.Data/Entities/Attributes/MongoEntityAttribute.cs @@ -1,17 +1,16 @@ using System; -namespace Geen.Data.Entities.Attributes +namespace Geen.Data.Entities.Attributes; + +[AttributeUsage(AttributeTargets.Class)] +public class MongoEntityAttribute : Attribute { - [AttributeUsage(AttributeTargets.Class)] - public class MongoEntityAttribute : Attribute + public MongoEntityAttribute(string collectionName, string schemaName = null) { - public string CollectionName { get; set; } - public string SchemaName { get; set; } - - public MongoEntityAttribute(string collectionName, string schemaName = null) - { - CollectionName = collectionName; - SchemaName = schemaName; - } + CollectionName = collectionName; + SchemaName = schemaName; } -} + + public string CollectionName { get; set; } + public string SchemaName { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Entities/ClubEntity.cs b/src/Backend/Geen.Data/Entities/ClubEntity.cs index ba58c1c..e07414a 100644 --- a/src/Backend/Geen.Data/Entities/ClubEntity.cs +++ b/src/Backend/Geen.Data/Entities/ClubEntity.cs @@ -1,22 +1,21 @@ using Geen.Data.Entities.Attributes; using Geen.Data.Entities.Namespaces; -namespace Geen.Data.Entities +namespace Geen.Data.Entities; + +[MongoEntity("Clubs", MongoNamespaces.Global)] +public class ClubEntity { - [MongoEntity("Clubs", MongoNamespaces.Global)] - public class ClubEntity - { - public int Id { get; set; } + public int Id { get; set; } - public string Name { get; set; } - public string UrlName { get; set; } + public string Name { get; set; } + public string UrlName { get; set; } - public string OfficialProfile { get; set; } + public string OfficialProfile { get; set; } - public int LeagueId { get; set; } + public int LeagueId { get; set; } - public bool IsNational { get; set; } + public bool IsNational { get; set; } - public long Votes { get; set; } - } -} + public long Votes { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Entities/CountryEntity.cs b/src/Backend/Geen.Data/Entities/CountryEntity.cs index 14ead48..028b671 100644 --- a/src/Backend/Geen.Data/Entities/CountryEntity.cs +++ b/src/Backend/Geen.Data/Entities/CountryEntity.cs @@ -1,14 +1,13 @@ using Geen.Data.Entities.Attributes; using Geen.Data.Entities.Namespaces; -namespace Geen.Data.Entities +namespace Geen.Data.Entities; + +[MongoEntity("Countries", MongoNamespaces.Global)] +public class CountryEntity { - [MongoEntity("Countries", MongoNamespaces.Global)] - public class CountryEntity - { - public int Id { get; set; } + public int Id { get; set; } - public string Name { get; set; } - public string UrlName { get; set; } - } -} + public string Name { get; set; } + public string UrlName { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Entities/IdentityEntity.cs b/src/Backend/Geen.Data/Entities/IdentityEntity.cs index 6e0226f..649c5b0 100644 --- a/src/Backend/Geen.Data/Entities/IdentityEntity.cs +++ b/src/Backend/Geen.Data/Entities/IdentityEntity.cs @@ -2,13 +2,12 @@ using Geen.Data.Entities.Namespaces; using MongoDB.Bson.Serialization.Attributes; -namespace Geen.Data.Entities +namespace Geen.Data.Entities; + +[MongoEntity("Identities", MongoNamespaces.Global)] +public class IdentityEntity { - [MongoEntity("Identities", MongoNamespaces.Global)] - public class IdentityEntity - { - [BsonId] - public string Name { get; set; } - public long Value { get; set; } - } + [BsonId] public string Name { get; set; } + + public long Value { get; set; } } \ No newline at end of file diff --git a/src/Backend/Geen.Data/Entities/LeagueEntity.cs b/src/Backend/Geen.Data/Entities/LeagueEntity.cs index b3cb15e..bb8ef96 100644 --- a/src/Backend/Geen.Data/Entities/LeagueEntity.cs +++ b/src/Backend/Geen.Data/Entities/LeagueEntity.cs @@ -1,16 +1,15 @@ using Geen.Data.Entities.Attributes; using Geen.Data.Entities.Namespaces; -namespace Geen.Data.Entities +namespace Geen.Data.Entities; + +[MongoEntity("Leagues", MongoNamespaces.Global)] +public class LeagueEntity { - [MongoEntity("Leagues", MongoNamespaces.Global)] - public class LeagueEntity - { - public int Id { get; set; } + public int Id { get; set; } - public string Name { get; set; } - public string UrlName { get; set; } + public string Name { get; set; } + public string UrlName { get; set; } - public int CountryId { get; set; } - } -} + public int CountryId { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Entities/MentionEntity.cs b/src/Backend/Geen.Data/Entities/MentionEntity.cs index d6a0511..de92a61 100644 --- a/src/Backend/Geen.Data/Entities/MentionEntity.cs +++ b/src/Backend/Geen.Data/Entities/MentionEntity.cs @@ -5,84 +5,82 @@ using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; -namespace Geen.Data.Entities +namespace Geen.Data.Entities; + +[MongoEntity("Mentions", MongoNamespaces.Global)] +public class MentionEntity { - [MongoEntity("Mentions", MongoNamespaces.Global)] - public class MentionEntity + public MentionEntity() { - public MentionEntity() - { - Related = new MentionRelatedEntity(); - } + Related = new MentionRelatedEntity(); + } - [BsonId] - public long Id { get; set; } + [BsonId] public long Id { get; set; } - public string Title { get; set; } + public string Title { get; set; } - public string Text { get; set; } + public string Text { get; set; } - public DateTime Date { get; set; } + public DateTime Date { get; set; } - public UserEntity User { get; set; } + public UserEntity User { get; set; } - public PlayerEntity Player { get; set; } + public PlayerEntity Player { get; set; } - public ClubEntity Club { get; set; } + public ClubEntity Club { get; set; } - public int Likes { get; set; } + public int Likes { get; set; } - public int Dislikes { get; set; } + public int Dislikes { get; set; } - public double[] Location { get; set; } + public double[] Location { get; set; } - public int RepliesCount { get; set; } + public int RepliesCount { get; set; } - public string SourceUrl { get; set; } + public string SourceUrl { get; set; } - public bool IsApproved { get; set; } + public bool IsApproved { get; set; } - public MentionRelatedEntity Related { get; set; } + public MentionRelatedEntity Related { get; set; } - public DateTime? TitleChangeDate { get; set; } + public DateTime? TitleChangeDate { get; set; } - public bool ContainsUrlName(string urlName) - { - return Player?.UrlName == urlName || Club?.UrlName == urlName; - } + public bool ContainsUrlName(string urlName) + { + return Player?.UrlName == urlName || Club?.UrlName == urlName; + } - public class MentionRelatedEntity + public class MentionRelatedEntity + { + public MentionRelatedEntity() { - public MentionRelatedEntity() - { - Players = new List(); - Clubs = new List(); - } - - public List Players { get; set; } - public List Clubs { get; set; } + Players = new List(); + Clubs = new List(); } + + public List Players { get; set; } + public List Clubs { get; set; } } +} - #region Unwinded +#region Unwinded - public class MentionUnwinded +public class MentionUnwinded +{ + public MentionUnwinded() { - public MentionUnwinded() - { - Related = new MentionRelatedUnwinded(); - } + Related = new MentionRelatedUnwinded(); + } - [BsonRepresentation(BsonType.ObjectId)] - public string Id { get; set; } - - public MentionRelatedUnwinded Related { get; set; } + [BsonRepresentation(BsonType.ObjectId)] + public string Id { get; set; } - public class MentionRelatedUnwinded - { - public int Players { get; set; } - } - } + public MentionRelatedUnwinded Related { get; set; } - #endregion + public class MentionRelatedUnwinded + { + public int Players { get; set; } + } } + +#endregion \ No newline at end of file diff --git a/src/Backend/Geen.Data/Entities/Namespaces/MongoNamespaces.cs b/src/Backend/Geen.Data/Entities/Namespaces/MongoNamespaces.cs index d92021f..4e6199a 100644 --- a/src/Backend/Geen.Data/Entities/Namespaces/MongoNamespaces.cs +++ b/src/Backend/Geen.Data/Entities/Namespaces/MongoNamespaces.cs @@ -1,7 +1,6 @@ -namespace Geen.Data.Entities.Namespaces +namespace Geen.Data.Entities.Namespaces; + +public class MongoNamespaces { - public class MongoNamespaces - { - public const string Global = "Geen"; - } -} + public const string Global = "Geen"; +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Entities/PlayerEntity.cs b/src/Backend/Geen.Data/Entities/PlayerEntity.cs index 70ee69c..878a5ec 100644 --- a/src/Backend/Geen.Data/Entities/PlayerEntity.cs +++ b/src/Backend/Geen.Data/Entities/PlayerEntity.cs @@ -2,26 +2,25 @@ using Geen.Data.Entities.Attributes; using Geen.Data.Entities.Namespaces; -namespace Geen.Data.Entities +namespace Geen.Data.Entities; + +[MongoEntity("Players", MongoNamespaces.Global)] +public class PlayerEntity { - [MongoEntity("Players", MongoNamespaces.Global)] - public class PlayerEntity - { - public int Id { get; set; } + public int Id { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } - public string UrlName { get; set; } + public string UrlName { get; set; } - public DateTime BirthDate { get; set; } + public DateTime BirthDate { get; set; } - public int Position { get; set; } + public int Position { get; set; } - public ClubEntity Club { get; set; } + public ClubEntity Club { get; set; } - public long Votes { get; set; } + public long Votes { get; set; } - public long MentionsCount { get; set; } - } -} + public long MentionsCount { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Entities/ReplyEntity.cs b/src/Backend/Geen.Data/Entities/ReplyEntity.cs index a6d2158..54aabfd 100644 --- a/src/Backend/Geen.Data/Entities/ReplyEntity.cs +++ b/src/Backend/Geen.Data/Entities/ReplyEntity.cs @@ -4,22 +4,21 @@ using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; -namespace Geen.Data.Entities +namespace Geen.Data.Entities; + +[MongoEntity("Replies", MongoNamespaces.Global)] +public class ReplyEntity { - [MongoEntity("Replies", MongoNamespaces.Global)] - public class ReplyEntity - { - [BsonRepresentation(BsonType.ObjectId)] - public string Id { get; set; } + [BsonRepresentation(BsonType.ObjectId)] + public string Id { get; set; } - public long MentionId { get; set; } + public long MentionId { get; set; } - public string Text { get; set; } + public string Text { get; set; } - public DateTime Date { get; set; } + public DateTime Date { get; set; } - public UserEntity User { get; set; } + public UserEntity User { get; set; } - public bool IsApproved { get; set; } - } -} + public bool IsApproved { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Entities/UserEntity.cs b/src/Backend/Geen.Data/Entities/UserEntity.cs index 2bc034b..9620d21 100644 --- a/src/Backend/Geen.Data/Entities/UserEntity.cs +++ b/src/Backend/Geen.Data/Entities/UserEntity.cs @@ -1,16 +1,14 @@ using MongoDB.Bson.Serialization.Attributes; -namespace Geen.Data.Entities +namespace Geen.Data.Entities; + +public class UserEntity { - public class UserEntity - { - public string Id { get; set; } + public string Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } - public string ProfileImage { get; set; } + public string ProfileImage { get; set; } - [BsonElement("IsAnon")] - public bool? IsAnonymous { get; set; } - } -} + [BsonElement("IsAnon")] public bool? IsAnonymous { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Entities/VoteEntity.cs b/src/Backend/Geen.Data/Entities/VoteEntity.cs index c4894d6..5f73911 100644 --- a/src/Backend/Geen.Data/Entities/VoteEntity.cs +++ b/src/Backend/Geen.Data/Entities/VoteEntity.cs @@ -4,19 +4,18 @@ using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; -namespace Geen.Data.Entities +namespace Geen.Data.Entities; + +[MongoEntity("Votes", MongoNamespaces.Global)] +public class VoteEntity { - [MongoEntity("Votes", MongoNamespaces.Global)] - public class VoteEntity - { - [BsonRepresentation(BsonType.ObjectId)] - public string Id { get; set; } + [BsonRepresentation(BsonType.ObjectId)] + public string Id { get; set; } + + public int? LeftPlayerId { get; set; } + public int? RightPlayerId { get; set; } - public int? LeftPlayerId { get; set; } - public int? RightPlayerId { get; set; } - - public int? WinnerId { get; set; } + public int? WinnerId { get; set; } - public DateTime Date {get;set;} - } -} + public DateTime Date { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Extensions/MapperExtensions.cs b/src/Backend/Geen.Data/Extensions/MapperExtensions.cs index 8450134..85673e5 100644 --- a/src/Backend/Geen.Data/Extensions/MapperExtensions.cs +++ b/src/Backend/Geen.Data/Extensions/MapperExtensions.cs @@ -1,12 +1,11 @@ using Mapster; -namespace Geen.Data.Extensions +namespace Geen.Data.Extensions; + +public static class MapperExtensions { - public static class MapperExtensions + public static T Map(this object obj) { - public static T Map(this object obj) - { - return obj.Adapt(); - } + return obj.Adapt(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Geen.Data.csproj b/src/Backend/Geen.Data/Geen.Data.csproj index 47e99e9..ba9304c 100644 --- a/src/Backend/Geen.Data/Geen.Data.csproj +++ b/src/Backend/Geen.Data/Geen.Data.csproj @@ -1,16 +1,16 @@  - - net7.0 - - - - - - - - - - - - + + net7.0 + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Backend/Geen.Data/Registration.cs b/src/Backend/Geen.Data/Registration.cs index 6337c29..b5f2426 100644 --- a/src/Backend/Geen.Data/Registration.cs +++ b/src/Backend/Geen.Data/Registration.cs @@ -12,51 +12,50 @@ using Microsoft.Extensions.Logging; using MongoDB.Bson.Serialization.Conventions; -namespace Geen.Data +namespace Geen.Data; + +public static class Registration { - public static class Registration + public static void RegisterDataServices(this IServiceCollection services, GeenSettings settings) { - public static void RegisterDataServices(this IServiceCollection services, GeenSettings settings) - { - RegisterMongoSettings(); + RegisterMongoSettings(); - services.AddSingleton(provider => new MongoContext( - settings.Database.MongoUrl, provider.GetService>())); + services.AddSingleton(provider => new MongoContext( + settings.Database.MongoUrl, provider.GetService>())); - services.AddSingleton(provider => new RedisStore(settings.Database.RedisUrl)); + services.AddSingleton(provider => new RedisStore(settings.Database.RedisUrl)); - services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); - var assemblyTypes = Assembly.GetExecutingAssembly().GetTypes(); + var assemblyTypes = Assembly.GetExecutingAssembly().GetTypes(); - services.RegisterRepositories(assemblyTypes); - } + services.RegisterRepositories(assemblyTypes); + } - private static void RegisterRepositories(this IServiceCollection services, IReadOnlyCollection types) - { - var repositories = types.Where(x => !x.IsInterface && x.FullName.EndsWith("Repository")); + private static void RegisterRepositories(this IServiceCollection services, IReadOnlyCollection types) + { + var repositories = types.Where(x => !x.IsInterface && x.FullName.EndsWith("Repository")); - foreach (var repository in repositories) - { - var handlerInterface = repository.GetInterfaces().FirstOrDefault(); + foreach (var repository in repositories) + { + var handlerInterface = repository.GetInterfaces().FirstOrDefault(); - if (handlerInterface == null) - continue; + if (handlerInterface == null) + continue; - services.AddTransient(handlerInterface, repository); - } + services.AddTransient(handlerInterface, repository); } - - private static void RegisterMongoSettings() + } + + private static void RegisterMongoSettings() + { + //Mongodb Ignore extra elements + ConventionRegistry.Register("ApplicationConventions", new ConventionPack { - //Mongodb Ignore extra elements - ConventionRegistry.Register("ApplicationConventions", new ConventionPack - { - new IgnoreExtraElementsConvention(true) - }, t => true); - } + new IgnoreExtraElementsConvention(true) + }, t => true); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Repositories/ClubRepository.cs b/src/Backend/Geen.Data/Repositories/ClubRepository.cs index b913285..fe2336c 100644 --- a/src/Backend/Geen.Data/Repositories/ClubRepository.cs +++ b/src/Backend/Geen.Data/Repositories/ClubRepository.cs @@ -8,111 +8,110 @@ using Geen.Data.Storages.Mongo; using MongoDB.Driver; -namespace Geen.Data.Repositories +namespace Geen.Data.Repositories; + +public class ClubRepository : IClubRepository { - public class ClubRepository : IClubRepository + private readonly MongoContext _context; + + public ClubRepository(MongoContext context) + { + _context = context; + } + + public async Task GetById(int id) { - private readonly MongoContext _context; - - public ClubRepository(MongoContext context) - { - _context = context; - } - - public async Task GetById(int id) - { - var result = await _context.For() - .Find(x => x.Id == id) - .FirstOrDefaultAsync(); - - return result.Map(); - } - - public async Task GetByUrlName(string urlName) - { - var result = await _context.For() - .Find(x => x.UrlName == urlName) - .FirstOrDefaultAsync(); - - return result.Map(); - } - - public async Task> GetAll() - { - var result = await _context.For() - .Find(x => true) - .ToListAsync(); - - return result.Map>(); - } - - public async Task> GetAllUrls() - { - var projection = Builders - .Projection - .Include(x => x.UrlName) - .Include(x => x.IsNational); - - var result = await _context.For() - .Find(x => true) - .Project(projection) - .ToListAsync(); - - return result.Map>(); - } - - public async Task GetNextId() - { - var projection = Builders - .Projection - .Expression(x => (int?)x.Id); - - var lastId = await _context.For() - .Find(x => true) - .SortByDescending(x => x.Id) - .Project(projection) - .FirstOrDefaultAsync(); - - if (!lastId.HasValue) - return 1; - - return lastId.Value + 1; - } - - public Task> GetBirthdays(string urlName) - { - var projection = Builders - .Projection - .Expression(x => x.BirthDate); - - return _context.For() - .Find(x => x.Club.UrlName == urlName && x.Position != 4) //no coach - .Project(projection) - .ToListAsync(); - } - - public Task Save(ClubModel model) - { - var entity = model.Map(); - - return _context.For() - .ReplaceOneAsync(x => x.Id == model.Id, entity, - new ReplaceOptions { IsUpsert = true }); - } - - public async Task> GetCached() - { - var projection = Builders.Projection - .Include(x => x.Id) - .Include(x => x.Name) - .Include(x => x.UrlName); - - var result = await _context.For() - .Find(x => true) - .Project(projection) - .ToListAsync(); - - return result.Map>(); - } + var result = await _context.For() + .Find(x => x.Id == id) + .FirstOrDefaultAsync(); + + return result.Map(); + } + + public async Task GetByUrlName(string urlName) + { + var result = await _context.For() + .Find(x => x.UrlName == urlName) + .FirstOrDefaultAsync(); + + return result.Map(); + } + + public async Task> GetAll() + { + var result = await _context.For() + .Find(x => true) + .ToListAsync(); + + return result.Map>(); + } + + public async Task> GetAllUrls() + { + var projection = Builders + .Projection + .Include(x => x.UrlName) + .Include(x => x.IsNational); + + var result = await _context.For() + .Find(x => true) + .Project(projection) + .ToListAsync(); + + return result.Map>(); + } + + public async Task GetNextId() + { + var projection = Builders + .Projection + .Expression(x => (int?)x.Id); + + var lastId = await _context.For() + .Find(x => true) + .SortByDescending(x => x.Id) + .Project(projection) + .FirstOrDefaultAsync(); + + if (!lastId.HasValue) + return 1; + + return lastId.Value + 1; + } + + public Task> GetBirthdays(string urlName) + { + var projection = Builders + .Projection + .Expression(x => x.BirthDate); + + return _context.For() + .Find(x => x.Club.UrlName == urlName && x.Position != 4) //no coach + .Project(projection) + .ToListAsync(); + } + + public Task Save(ClubModel model) + { + var entity = model.Map(); + + return _context.For() + .ReplaceOneAsync(x => x.Id == model.Id, entity, + new ReplaceOptions { IsUpsert = true }); + } + + public async Task> GetCached() + { + var projection = Builders.Projection + .Include(x => x.Id) + .Include(x => x.Name) + .Include(x => x.UrlName); + + var result = await _context.For() + .Find(x => true) + .Project(projection) + .ToListAsync(); + + return result.Map>(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Repositories/CountryRepository.cs b/src/Backend/Geen.Data/Repositories/CountryRepository.cs index 59f47a4..4ff0f60 100644 --- a/src/Backend/Geen.Data/Repositories/CountryRepository.cs +++ b/src/Backend/Geen.Data/Repositories/CountryRepository.cs @@ -7,67 +7,66 @@ using Geen.Data.Storages.Mongo; using MongoDB.Driver; -namespace Geen.Data.Repositories +namespace Geen.Data.Repositories; + +public class CountryRepository : ICountryRepository { - public class CountryRepository : ICountryRepository - { - private readonly MongoContext _context; + private readonly MongoContext _context; - public CountryRepository(MongoContext context) - { - _context = context; - } + public CountryRepository(MongoContext context) + { + _context = context; + } - public async Task GetById(int id) - { - var result = await _context.For() - .Find(x => x.Id == id) - .FirstOrDefaultAsync(); + public async Task GetById(int id) + { + var result = await _context.For() + .Find(x => x.Id == id) + .FirstOrDefaultAsync(); - return result.Map(); - } + return result.Map(); + } - public async Task GetByUrlName(string urlName) - { - var result = await _context.For() - .Find(x => x.UrlName == urlName) - .FirstOrDefaultAsync(); + public async Task GetByUrlName(string urlName) + { + var result = await _context.For() + .Find(x => x.UrlName == urlName) + .FirstOrDefaultAsync(); - return result.Map(); - } + return result.Map(); + } - public async Task> GetAll() - { - var result = await _context.For() - .Find(x => true) - .ToListAsync(); + public async Task> GetAll() + { + var result = await _context.For() + .Find(x => true) + .ToListAsync(); - return result.Map>(); - } + return result.Map>(); + } - public async Task GetNextId() - { - var projection = Builders.Projection.Expression(x => (int?)x.Id); + public async Task GetNextId() + { + var projection = Builders.Projection.Expression(x => (int?)x.Id); - var lastId = await _context.For() - .Find(x => true) - .SortByDescending(x => x.Id) - .Project(projection) - .FirstOrDefaultAsync(); + var lastId = await _context.For() + .Find(x => true) + .SortByDescending(x => x.Id) + .Project(projection) + .FirstOrDefaultAsync(); - if (!lastId.HasValue) - return 1; + if (!lastId.HasValue) + return 1; - return lastId.Value + 1; - } + return lastId.Value + 1; + } - public Task Save(CountryModel model) - { - var entity = model.Map(); + public Task Save(CountryModel model) + { + var entity = model.Map(); - return _context.For() - .ReplaceOneAsync(x => x.Id == model.Id, entity, - new ReplaceOptions { IsUpsert = true }); - } + return _context.For() + .ReplaceOneAsync(x => x.Id == model.Id, entity, + new ReplaceOptions { IsUpsert = true }); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Repositories/LeagueRepository.cs b/src/Backend/Geen.Data/Repositories/LeagueRepository.cs index e4674b7..a07735d 100644 --- a/src/Backend/Geen.Data/Repositories/LeagueRepository.cs +++ b/src/Backend/Geen.Data/Repositories/LeagueRepository.cs @@ -5,70 +5,68 @@ using Geen.Data.Entities; using Geen.Data.Extensions; using Geen.Data.Storages.Mongo; -using Mapster; using MongoDB.Driver; -namespace Geen.Data.Repositories +namespace Geen.Data.Repositories; + +public class LeagueRepository : ILeagueRepository { - public class LeagueRepository : ILeagueRepository - { - private readonly MongoContext _context; + private readonly MongoContext _context; - public LeagueRepository(MongoContext context) - { - _context = context; - } + public LeagueRepository(MongoContext context) + { + _context = context; + } - public async Task GetById(int id) - { - var result = await _context.For() - .Find(x => x.Id == id) - .FirstOrDefaultAsync(); + public async Task GetById(int id) + { + var result = await _context.For() + .Find(x => x.Id == id) + .FirstOrDefaultAsync(); - return result.Map(); - } + return result.Map(); + } - public async Task GetByUrlName(string urlName) - { - var result = await _context.For() - .Find(x => x.UrlName == urlName) - .FirstOrDefaultAsync(); + public async Task GetByUrlName(string urlName) + { + var result = await _context.For() + .Find(x => x.UrlName == urlName) + .FirstOrDefaultAsync(); - return result.Map(); - } + return result.Map(); + } - public async Task> GetAll() - { - var result = await _context.For() - .Find(x => true) - .ToListAsync(); + public async Task> GetAll() + { + var result = await _context.For() + .Find(x => true) + .ToListAsync(); - return result.Map>(); - } + return result.Map>(); + } - public async Task GetNextId() - { - var projection = Builders.Projection.Expression(x => (int?)x.Id); + public async Task GetNextId() + { + var projection = Builders.Projection.Expression(x => (int?)x.Id); - var lastId = await _context.For() - .Find(x => true) - .SortByDescending(x => x.Id) - .Project(projection) - .FirstOrDefaultAsync(); + var lastId = await _context.For() + .Find(x => true) + .SortByDescending(x => x.Id) + .Project(projection) + .FirstOrDefaultAsync(); - if (!lastId.HasValue) - return 1; + if (!lastId.HasValue) + return 1; - return lastId.Value + 1; - } + return lastId.Value + 1; + } - public Task Save(LeagueModel model) - { - var entity = model.Map(); + public Task Save(LeagueModel model) + { + var entity = model.Map(); - return _context.For() - .ReplaceOneAsync(x => x.Id == model.Id, entity, - new ReplaceOptions { IsUpsert = true }); - } + return _context.For() + .ReplaceOneAsync(x => x.Id == model.Id, entity, + new ReplaceOptions { IsUpsert = true }); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Repositories/Likes/MentionLikeRepository.cs b/src/Backend/Geen.Data/Repositories/Likes/MentionLikeRepository.cs index 0823f28..9b25d14 100644 --- a/src/Backend/Geen.Data/Repositories/Likes/MentionLikeRepository.cs +++ b/src/Backend/Geen.Data/Repositories/Likes/MentionLikeRepository.cs @@ -3,59 +3,58 @@ using Geen.Core.Models.Likes; using Geen.Data.Storages.Redis; -namespace Geen.Data.Repositories.Likes +namespace Geen.Data.Repositories.Likes; + +public class MentionLikeRepository : IMentionLikeRepository { - public class MentionLikeRepository : IMentionLikeRepository + private readonly RedisStore _redisStore; + + public MentionLikeRepository(RedisStore redisStore) { - private readonly RedisStore _redisStore; + _redisStore = redisStore; + } - public MentionLikeRepository(RedisStore redisStore) - { - _redisStore = redisStore; - } + public async Task GetLikeStatus(long id, string userId) + { + var likesStatus = _redisStore.Current.SetContainsAsync(GetLikeKey(id), userId); + var dislikesStatus = _redisStore.Current.SetContainsAsync(GetDislikeKey(id), userId); - private string GetLikeKey(long id) - { - return $"MENTION_{id}_LIKES"; - } + await Task.WhenAll(likesStatus, dislikesStatus); - private string GetDislikeKey(long id) + return new LikeStatus { - return $"MENTION_{id}_DISLIKES"; - } + Likes = likesStatus.Result, + Dislikes = dislikesStatus.Result + }; + } - public async Task GetLikeStatus(long id, string userId) - { - var likesStatus = _redisStore.Current.SetContainsAsync(GetLikeKey(id), userId); - var dislikesStatus = _redisStore.Current.SetContainsAsync(GetDislikeKey(id), userId); - - await Task.WhenAll(likesStatus, dislikesStatus); - - return new LikeStatus - { - Likes = likesStatus.Result, - Dislikes = dislikesStatus.Result - }; - } - - public Task LikeAddUser(long id, string userId) - { - return _redisStore.Current.SetAddAsync(GetLikeKey(id), userId); - } + public Task LikeAddUser(long id, string userId) + { + return _redisStore.Current.SetAddAsync(GetLikeKey(id), userId); + } - public Task LikeRemoveUser(long id, string userId) - { - return _redisStore.Current.SetRemoveAsync(GetLikeKey(id), userId); - } + public Task LikeRemoveUser(long id, string userId) + { + return _redisStore.Current.SetRemoveAsync(GetLikeKey(id), userId); + } - public Task DislikeAddUser(long id, string userId) - { - return _redisStore.Current.SetAddAsync(GetDislikeKey(id), userId); - } + public Task DislikeAddUser(long id, string userId) + { + return _redisStore.Current.SetAddAsync(GetDislikeKey(id), userId); + } - public Task DislikeRemoveUser(long id, string userId) - { - return _redisStore.Current.SetRemoveAsync(GetDislikeKey(id), userId); - } + public Task DislikeRemoveUser(long id, string userId) + { + return _redisStore.Current.SetRemoveAsync(GetDislikeKey(id), userId); + } + + private string GetLikeKey(long id) + { + return $"MENTION_{id}_LIKES"; + } + + private string GetDislikeKey(long id) + { + return $"MENTION_{id}_DISLIKES"; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Repositories/Likes/ReplyLikeRepository.cs b/src/Backend/Geen.Data/Repositories/Likes/ReplyLikeRepository.cs index 5b569fb..84991f3 100644 --- a/src/Backend/Geen.Data/Repositories/Likes/ReplyLikeRepository.cs +++ b/src/Backend/Geen.Data/Repositories/Likes/ReplyLikeRepository.cs @@ -3,59 +3,58 @@ using Geen.Core.Models.Likes; using Geen.Data.Storages.Redis; -namespace Geen.Data.Repositories.Likes +namespace Geen.Data.Repositories.Likes; + +public class ReplyLikeRepository : IReplyLikeRepository { - public class ReplyLikeRepository : IReplyLikeRepository + private readonly RedisStore _redisStore; + + public ReplyLikeRepository(RedisStore redisStore) { - private readonly RedisStore _redisStore; + _redisStore = redisStore; + } - public ReplyLikeRepository(RedisStore redisStore) - { - _redisStore = redisStore; - } + public async Task GetLikeStatus(string id, string userId) + { + var likesStatus = _redisStore.Current.SetContainsAsync(GetLikeKey(id), userId); + var dislikesStatus = _redisStore.Current.SetContainsAsync(GetDislikeKey(id), userId); - private string GetLikeKey(string id) - { - return $"REPLY_{id}_LIKES"; - } + await Task.WhenAll(likesStatus, dislikesStatus); - private string GetDislikeKey(string id) + return new LikeStatus { - return $"REPLY_{id}_DISLIKES"; - } + Likes = likesStatus.Result, + Dislikes = dislikesStatus.Result + }; + } - public async Task GetLikeStatus(string id, string userId) - { - var likesStatus = _redisStore.Current.SetContainsAsync(GetLikeKey(id), userId); - var dislikesStatus = _redisStore.Current.SetContainsAsync(GetDislikeKey(id), userId); - - await Task.WhenAll(likesStatus, dislikesStatus); - - return new LikeStatus - { - Likes = likesStatus.Result, - Dislikes = dislikesStatus.Result - }; - } - - public Task LikeAddUser(string id, string userId) - { - return _redisStore.Current.SetAddAsync(GetLikeKey(id), userId); - } + public Task LikeAddUser(string id, string userId) + { + return _redisStore.Current.SetAddAsync(GetLikeKey(id), userId); + } - public Task LikeRemoveUser(string id, string userId) - { - return _redisStore.Current.SetRemoveAsync(GetLikeKey(id), userId); - } + public Task LikeRemoveUser(string id, string userId) + { + return _redisStore.Current.SetRemoveAsync(GetLikeKey(id), userId); + } - public Task DislikeAddUser(string id, string userId) - { - return _redisStore.Current.SetAddAsync(GetDislikeKey(id), userId); - } + public Task DislikeAddUser(string id, string userId) + { + return _redisStore.Current.SetAddAsync(GetDislikeKey(id), userId); + } - public Task DislikeRemoveUser(string id, string userId) - { - return _redisStore.Current.SetRemoveAsync(GetDislikeKey(id), userId); - } + public Task DislikeRemoveUser(string id, string userId) + { + return _redisStore.Current.SetRemoveAsync(GetDislikeKey(id), userId); + } + + private string GetLikeKey(string id) + { + return $"REPLY_{id}_LIKES"; + } + + private string GetDislikeKey(string id) + { + return $"REPLY_{id}_DISLIKES"; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Repositories/MentionRepository.cs b/src/Backend/Geen.Data/Repositories/MentionRepository.cs index 0be6f40..622a48f 100644 --- a/src/Backend/Geen.Data/Repositories/MentionRepository.cs +++ b/src/Backend/Geen.Data/Repositories/MentionRepository.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Threading.Tasks; using Geen.Core.Domains.Mentions; using Geen.Core.Domains.Mentions.Commands; @@ -14,424 +13,414 @@ using Geen.Data.Services; using Geen.Data.Storages.Mongo; using Geen.Data.Utils; -using Mapster; using MongoDB.Driver; -namespace Geen.Data.Repositories -{ - public class MentionRepository : IMentionRepository - { - private readonly MongoContext _context; - private readonly IdentityService _identityService; - - public MentionRepository(MongoContext context, IdentityService identityService) - { - _context = context; - _identityService = identityService; - } - - public async Task GetById(long identity) - { - var result = await _context.For() - .Find(x => x.Id == identity) - .FirstOrDefaultAsync(); - - return result.Map(); - } +namespace Geen.Data.Repositories; - public async Task> GetMentionIdentities() - { - var projection = Builders.Projection - .Include(x => x.Id) - .Include(x => x.RepliesCount) - .Include(x => x.Player.UrlName) - .Include(x => x.Club.UrlName); - - var result = await _context.For() - .Find(x => x.IsApproved) - .Project(projection) - .ToListAsync(); +public class MentionRepository : IMentionRepository +{ + private readonly MongoContext _context; + private readonly IdentityService _identityService; - return result.Map>(); - } + public MentionRepository(MongoContext context, IdentityService identityService) + { + _context = context; + _identityService = identityService; + } - public async Task> GetMentionTitleList(long? id, int page) - { - var filter = Builders.Filter.Where(x => x.IsApproved); + public async Task GetById(long identity) + { + var result = await _context.For() + .Find(x => x.Id == identity) + .FirstOrDefaultAsync(); - if (id.HasValue) - filter &= Builders.Filter.Where(x => x.Id == id); + return result.Map(); + } - var project = Builders.Projection - .Include(x => x.Id) - .Include(x => x.Text) - .Include(x => x.Title); + public async Task> GetMentionIdentities() + { + var projection = Builders.Projection + .Include(x => x.Id) + .Include(x => x.RepliesCount) + .Include(x => x.Player.UrlName) + .Include(x => x.Club.UrlName); + + var result = await _context.For() + .Find(x => x.IsApproved) + .Project(projection) + .ToListAsync(); + + return result.Map>(); + } - var result = await _context.For() - .Find(filter) - .SortByDescending(x => x.Date) - .Project(project) - .ToPagedAsync(page); + public async Task> GetMentionTitleList(long? id, int page) + { + var filter = Builders.Filter.Where(x => x.IsApproved); - return result.Map>(); - } + if (id.HasValue) + filter &= Builders.Filter.Where(x => x.Id == id); - public async Task> GetList(GetMentionListQuery query) - { - var builder = Builders.Filter; + var project = Builders.Projection + .Include(x => x.Id) + .Include(x => x.Text) + .Include(x => x.Title); - var filter = FilterDefinition.Empty; + var result = await _context.For() + .Find(filter) + .SortByDescending(x => x.Date) + .Project(project) + .ToPagedAsync(page); - if (query.IsApproved.HasValue) - filter = filter & builder.Eq(x => x.IsApproved, query.IsApproved.Value); + return result.Map>(); + } - if (query.PlayerId.HasValue) - filter = filter & builder.Where(x => x.Player.Id == query.PlayerId.Value); + public async Task> GetList(GetMentionListQuery query) + { + var builder = Builders.Filter; - if (!string.IsNullOrWhiteSpace(query.ClubUrlName)) - filter = filter & builder.Where(x => x.Club.UrlName == query.ClubUrlName); + var filter = FilterDefinition.Empty; - if (!string.IsNullOrWhiteSpace(query.PlayerClubUrlName)) - filter = filter & builder.Where(x => x.Player.Club.UrlName == query.PlayerClubUrlName); + if (query.IsApproved.HasValue) + filter = filter & builder.Eq(x => x.IsApproved, query.IsApproved.Value); - if (!string.IsNullOrWhiteSpace(query.UserId)) - filter = filter & builder.Where(x => x.User.Id == query.UserId); + if (query.PlayerId.HasValue) + filter = filter & builder.Where(x => x.Player.Id == query.PlayerId.Value); - if (query.ForPlayer.HasValue) - filter = filter & builder.Exists(x => x.Player.Id, query.ForPlayer.Value); + if (!string.IsNullOrWhiteSpace(query.ClubUrlName)) + filter = filter & builder.Where(x => x.Club.UrlName == query.ClubUrlName); - if (query.ForClub.HasValue) - { - filter = filter & builder.Exists(x => x.Club.Id, query.ForClub.Value) - & builder.Not(builder.Eq(x => x.Club.IsNational, true)); - } + if (!string.IsNullOrWhiteSpace(query.PlayerClubUrlName)) + filter = filter & builder.Where(x => x.Player.Club.UrlName == query.PlayerClubUrlName); - if (query.Latitude.HasValue && query.Longitude.HasValue) - { - filter = filter & - builder.Near(x => x.Location, query.Latitude.Value, query.Longitude.Value); - } + if (!string.IsNullOrWhiteSpace(query.UserId)) + filter = filter & builder.Where(x => x.User.Id == query.UserId); - var result = await _context.For() - .Find(filter) - .SortByDescending(x => x.Date) - .ToPagedAsync(query.Page); + if (query.ForPlayer.HasValue) + filter = filter & builder.Exists(x => x.Player.Id, query.ForPlayer.Value); - return result.Map>(); - } - - public async Task GetNextId() - { - var projection = Builders.Projection.Expression(x => (int?)x.Id); + if (query.ForClub.HasValue) + filter = filter & builder.Exists(x => x.Club.Id, query.ForClub.Value) + & builder.Not(builder.Eq(x => x.Club.IsNational, true)); - var lastId = await _context.For() - .Find(x => true) - .SortByDescending(x => x.Id) - .Project(projection) - .FirstOrDefaultAsync(); + if (query.Latitude.HasValue && query.Longitude.HasValue) + filter = filter & + builder.Near(x => x.Location, query.Latitude.Value, query.Longitude.Value); - if (!lastId.HasValue) - return 1; + var result = await _context.For() + .Find(filter) + .SortByDescending(x => x.Date) + .ToPagedAsync(query.Page); - return lastId.Value + 1; - } + return result.Map>(); + } - public Task> GetBirthdays(string urlName) - { - var projection = Builders - .Projection - .Expression(x => x.BirthDate); - return _context.For() - .Find(x => x.Club.UrlName == urlName && x.Position != 4) //no coach - .Project(projection) - .ToListAsync(); - } + public Task GetLikeStatus(long id) + { + var projection = Builders.Projection + .Include(x => x.Likes) + .Include(x => x.Dislikes); + + return _context.For() + .Find(x => x.Id == id) + .Project(projection) + .FirstOrDefaultAsync(); + } + public async Task Approve(long id) + { + var update = Builders.Update.Set(x => x.IsApproved, true); - public Task GetLikeStatus(long id) - { - var projection = Builders.Projection - .Include(x => x.Likes) - .Include(x => x.Dislikes); - - return _context.For() - .Find(x => x.Id == id) - .Project(projection) - .FirstOrDefaultAsync(); - } + var result = await _context.For() + .FindOneAndUpdateAsync(x => x.Id == id, update); - public async Task Approve(long id) - { - var update = Builders.Update.Set(x => x.IsApproved, true); + if (result.Player != null) + await _context.For() + .UpdateOneAsync(x => x.Id == result.Player.Id, + Builders.Update.Inc(x => x.MentionsCount, 1)); + } - var result = await _context.For() - .FindOneAndUpdateAsync(x => x.Id == id, update); + public async Task Disapprove(long id) + { + var update = Builders.Update.Set(x => x.IsApproved, false); - if (result.Player != null) - { - await _context.For() - .UpdateOneAsync(x => x.Id == result.Player.Id, - Builders.Update.Inc(x => x.MentionsCount, 1)); - } - } + var result = await _context.For() + .FindOneAndUpdateAsync(x => x.Id == id, update); - public async Task Disapprove(long id) - { - var update = Builders.Update.Set(x => x.IsApproved, false); + if (result.Player != null) + await _context.For() + .UpdateOneAsync(x => x.Id == result.Player.Id, + Builders.Update.Inc(x => x.MentionsCount, -1)); + } - var result = await _context.For() - .FindOneAndUpdateAsync(x => x.Id == id, update); + public Task Like(long id, IncrementStatus status) + { + var updates = new List>(); - if (result.Player != null) - { - await _context.For() - .UpdateOneAsync(x => x.Id == result.Player.Id, - Builders.Update.Inc(x => x.MentionsCount, -1)); - } - } + if (status.Likes != 0) + updates.Add(Builders.Update.Inc(x => x.Likes, status.Likes)); - public Task Like(long id, IncrementStatus status) - { - var updates = new List>(); - - if (status.Likes != 0) - updates.Add(Builders.Update.Inc(x => x.Likes, status.Likes)); - - if (status.Dislikes != 0) - updates.Add(Builders.Update.Inc(x => x.Dislikes, status.Dislikes)); - - if (updates.Count == 0) - throw new InvalidOperationException("Empty update list"); - - var updateDefinition = Builders.Update.Combine(updates); - - return _context.For().UpdateOneAsync( - mention => mention.Id == id, - updateDefinition - ); - } + if (status.Dislikes != 0) + updates.Add(Builders.Update.Inc(x => x.Dislikes, status.Dislikes)); - public Task Dislike(long id, IncrementStatus status) - { - var updates = new List>(); + if (updates.Count == 0) + throw new InvalidOperationException("Empty update list"); - if (status.Likes != 0) - updates.Add(Builders.Update.Inc(x => x.Likes, status.Likes)); + var updateDefinition = Builders.Update.Combine(updates); - if (status.Dislikes != 0) - updates.Add(Builders.Update.Inc(x => x.Dislikes, status.Dislikes)); + return _context.For().UpdateOneAsync( + mention => mention.Id == id, + updateDefinition + ); + } - if(updates.Count == 0) - throw new InvalidOperationException("Empty update list"); + public Task Dislike(long id, IncrementStatus status) + { + var updates = new List>(); - return _context.For().UpdateOneAsync( - mention => mention.Id == id, - Builders.Update.Combine(updates) - ); - } + if (status.Likes != 0) + updates.Add(Builders.Update.Inc(x => x.Likes, status.Likes)); - public Task UpdateTitle(long id, string title) - { - var update = Builders.Update - .Set(x => x.Title, title) - .Set(x => x.TitleChangeDate, DateTime.UtcNow); + if (status.Dislikes != 0) + updates.Add(Builders.Update.Inc(x => x.Dislikes, status.Dislikes)); - return _context.For() - .UpdateOneAsync(x => x.Id == id, update); - } + if (updates.Count == 0) + throw new InvalidOperationException("Empty update list"); - public Task UpdateText(long id, string text) - { - var update = Builders.Update - .Set(x => x.Text, text) - .Set(x => x.TitleChangeDate, DateTime.UtcNow); + return _context.For().UpdateOneAsync( + mention => mention.Id == id, + Builders.Update.Combine(updates) + ); + } - return _context.For() - .UpdateOneAsync(x => x.Id == id, update); - } + public Task UpdateTitle(long id, string title) + { + var update = Builders.Update + .Set(x => x.Title, title) + .Set(x => x.TitleChangeDate, DateTime.UtcNow); - public Task UpdateUser(long id, string userName) - { - var update = Builders.Update - .Set(x => x.User.IsAnonymous, false) - .Set(x => x.User.Name, userName); + return _context.For() + .UpdateOneAsync(x => x.Id == id, update); + } - return _context.For() - .UpdateOneAsync(x => x.Id == id, update); - } + public Task UpdateText(long id, string text) + { + var update = Builders.Update + .Set(x => x.Text, text) + .Set(x => x.TitleChangeDate, DateTime.UtcNow); - public Task SetDefaultAvatar(long id) - { - var update = Builders.Update - .Set(x => x.User.ProfileImage, null); + return _context.For() + .UpdateOneAsync(x => x.Id == id, update); + } - return _context.For() - .UpdateOneAsync(x => x.Id == id, update); - } + public Task UpdateUser(long id, string userName) + { + var update = Builders.Update + .Set(x => x.User.IsAnonymous, false) + .Set(x => x.User.Name, userName); - public async Task Save(MentionModel model) - { - if (model.Id == 0) - model.Id = await _identityService.Next(); + return _context.For() + .UpdateOneAsync(x => x.Id == id, update); + } - var entity = model.Map(); + public Task SetDefaultAvatar(long id) + { + var update = Builders.Update + .Set(x => x.User.ProfileImage, null); - await _context.For() - .ReplaceOneAsync(x => x.Id == entity.Id, entity, - new ReplaceOptions { IsUpsert = true }); - } + return _context.For() + .UpdateOneAsync(x => x.Id == id, update); + } - public Task Delete(long id) - { - return _context.For() - .DeleteOneAsync(x => x.Id == id); - } + public async Task Save(MentionModel model) + { + if (model.Id == 0) + model.Id = await _identityService.Next(); - public Task IncrementRepliesCount(long id) - { - var update = Builders.Update - .Inc(x => x.RepliesCount, 1); + var entity = model.Map(); - return _context.For() - .UpdateOneAsync(x => x.Id == id, update); - } + await _context.For() + .ReplaceOneAsync(x => x.Id == entity.Id, entity, + new ReplaceOptions { IsUpsert = true }); + } - public Task DecrementRepliesCount(long id) - { - var update = Builders.Update - .Inc(x => x.RepliesCount, -1); + public Task Delete(long id) + { + return _context.For() + .DeleteOneAsync(x => x.Id == id); + } - return _context.For() - .UpdateOneAsync(x => x.Id == id, update); - } + public Task IncrementRepliesCount(long id) + { + var update = Builders.Update + .Inc(x => x.RepliesCount, 1); - #region Fresh + return _context.For() + .UpdateOneAsync(x => x.Id == id, update); + } - public async Task> GetFreshMentions(DateTime? dateStart) - { - if (!dateStart.HasValue) - dateStart = DateTime.UtcNow.Date; - - var mentionProjection = Builders.Projection - .Include(x => x.Id) - .Include(x => x.Player.UrlName) - .Include(x => x.RepliesCount) - .Include(x => x.Club.UrlName); - - var result = await _context.For() - .Find(x => x.Date >= dateStart || x.TitleChangeDate >= dateStart) - .Project(mentionProjection) - .ToListAsync(); + public Task DecrementRepliesCount(long id) + { + var update = Builders.Update + .Inc(x => x.RepliesCount, -1); - return result.Map>(); - } + return _context.For() + .UpdateOneAsync(x => x.Id == id, update); + } - public async Task> GetFreshTitledMentions(DateTime? dateStart) - { - if (!dateStart.HasValue) - dateStart = DateTime.UtcNow.Date; - - var mentionProjection = Builders.Projection - .Include(x => x.Id) - .Include(x => x.Player.UrlName) - .Include(x => x.RepliesCount) - .Include(x => x.Club.UrlName); - - var result = await _context.For() - .Find(x => x.IsApproved && x.TitleChangeDate >= dateStart) - .Project(mentionProjection) - .ToListAsync(); + public async Task GetNextId() + { + var projection = Builders.Projection.Expression(x => (int?)x.Id); - return result.Map>(); - } + var lastId = await _context.For() + .Find(x => true) + .SortByDescending(x => x.Id) + .Project(projection) + .FirstOrDefaultAsync(); - public async Task> GetFreshRepliedMentionIds(DateTime? dateStart) - { - if (!dateStart.HasValue) - dateStart = DateTime.UtcNow.Date; + if (!lastId.HasValue) + return 1; - var repliesMentionIds = await _context.For() - .Find(x => x.IsApproved && x.Date >= dateStart) - .Project(x => x.MentionId) - .ToListAsync(); + return lastId.Value + 1; + } - var mentionProjection = Builders.Projection - .Include(x => x.Id) - .Include(x => x.Player.UrlName) - .Include(x => x.RepliesCount) - .Include(x => x.Club.UrlName); + public Task> GetBirthdays(string urlName) + { + var projection = Builders + .Projection + .Expression(x => x.BirthDate); + + return _context.For() + .Find(x => x.Club.UrlName == urlName && x.Position != 4) //no coach + .Project(projection) + .ToListAsync(); + } - var result = await _context.For() - .Find(x => repliesMentionIds.Contains(x.Id)) - .Project(mentionProjection) - .ToListAsync(); + #region Fresh - return result.Map>(); - } + public async Task> GetFreshMentions(DateTime? dateStart) + { + if (!dateStart.HasValue) + dateStart = DateTime.UtcNow.Date; - public long GetClubItemsCount(string clubUrlName) - { - return _context.For() - .CountDocuments(x => x.Club.UrlName == clubUrlName); - } + var mentionProjection = Builders.Projection + .Include(x => x.Id) + .Include(x => x.Player.UrlName) + .Include(x => x.RepliesCount) + .Include(x => x.Club.UrlName); - public long GetPlayerItemsCount(string playerUrlName) - { - return _context.For() - .CountDocuments(x => x.Player.UrlName == playerUrlName); - } + var result = await _context.For() + .Find(x => x.Date >= dateStart || x.TitleChangeDate >= dateStart) + .Project(mentionProjection) + .ToListAsync(); - public Task RandomLikes(MentionRandomLikerCommand command) - { - return Task.WhenAll( - ForMentions() - ); + return result.Map>(); + } - async Task ForMentions() - { - var minDate = DateTime.UtcNow.Date.AddDays(-command.DaysInteval); + public async Task> GetFreshTitledMentions(DateTime? dateStart) + { + if (!dateStart.HasValue) + dateStart = DateTime.UtcNow.Date; - var mentions = await _context.For() - .Aggregate() - .Match(x => x.Date >= minDate) - .AppendStage("{ $sample: { size: " + command.Count + "} }") - .Project(x => new { x.Id }) - .ToListAsync(); + var mentionProjection = Builders.Projection + .Include(x => x.Id) + .Include(x => x.Player.UrlName) + .Include(x => x.RepliesCount) + .Include(x => x.Club.UrlName); - var tasks = new List(); + var result = await _context.For() + .Find(x => x.IsApproved && x.TitleChangeDate >= dateStart) + .Project(mentionProjection) + .ToListAsync(); - var randomizer = Randomizer.RandomLocal; - - foreach (var mention in mentions) - { - var likesInc = randomizer.Next(0, command.MaxLikes); - var dislikesInc = randomizer.Next(0, command.MaxDislikes); + return result.Map>(); + } - var update = Builders.Update - .Inc(x => x.Likes, likesInc) - .Inc(x => x.Dislikes, dislikesInc); + public async Task> GetFreshRepliedMentionIds(DateTime? dateStart) + { + if (!dateStart.HasValue) + dateStart = DateTime.UtcNow.Date; + + var repliesMentionIds = await _context.For() + .Find(x => x.IsApproved && x.Date >= dateStart) + .Project(x => x.MentionId) + .ToListAsync(); + + var mentionProjection = Builders.Projection + .Include(x => x.Id) + .Include(x => x.Player.UrlName) + .Include(x => x.RepliesCount) + .Include(x => x.Club.UrlName); + + var result = await _context.For() + .Find(x => repliesMentionIds.Contains(x.Id)) + .Project(mentionProjection) + .ToListAsync(); + + return result.Map>(); + } - var updateTask = _context.For().UpdateOneAsync(x => x.Id == mention.Id, update); + public long GetClubItemsCount(string clubUrlName) + { + return _context.For() + .CountDocuments(x => x.Club.UrlName == clubUrlName); + } - tasks.Add(updateTask); - } + public long GetPlayerItemsCount(string playerUrlName) + { + return _context.For() + .CountDocuments(x => x.Player.UrlName == playerUrlName); + } - await Task.WhenAll(tasks); - } - } + public Task RandomLikes(MentionRandomLikerCommand command) + { + return Task.WhenAll( + ForMentions() + ); - public async Task> GetAll(int count) + async Task ForMentions() { + var minDate = DateTime.UtcNow.Date.AddDays(-command.DaysInteval); + var mentions = await _context.For() .Aggregate() - .AppendStage("{ $sample: { size: " + count + "} }") + .Match(x => x.Date >= minDate) + .AppendStage("{ $sample: { size: " + command.Count + "} }") .Project(x => new { x.Id }) .ToListAsync(); - return mentions.Map>(); + var tasks = new List(); + + var randomizer = Randomizer.RandomLocal; + + foreach (var mention in mentions) + { + var likesInc = randomizer.Next(0, command.MaxLikes); + var dislikesInc = randomizer.Next(0, command.MaxDislikes); + + var update = Builders.Update + .Inc(x => x.Likes, likesInc) + .Inc(x => x.Dislikes, dislikesInc); + + var updateTask = _context.For().UpdateOneAsync(x => x.Id == mention.Id, update); + + tasks.Add(updateTask); + } + + await Task.WhenAll(tasks); } + } + + public async Task> GetAll(int count) + { + var mentions = await _context.For() + .Aggregate() + .AppendStage("{ $sample: { size: " + count + "} }") + .Project(x => new { x.Id }) + .ToListAsync(); - #endregion + return mentions.Map>(); } -} + + #endregion +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Repositories/PlayerRepository.cs b/src/Backend/Geen.Data/Repositories/PlayerRepository.cs index d3e242b..d741db2 100644 --- a/src/Backend/Geen.Data/Repositories/PlayerRepository.cs +++ b/src/Backend/Geen.Data/Repositories/PlayerRepository.cs @@ -5,332 +5,325 @@ using System.Threading.Tasks; using Geen.Core.Domains.Players; using Geen.Core.Domains.Players.Repositories; -using Geen.Core.Domains.Players.Utils; using Geen.Data.Entities; using Geen.Data.Extensions; using Geen.Data.Storages.Mongo; using Geen.Data.Utils; -using Mapster; using MongoDB.Bson; using MongoDB.Driver; -namespace Geen.Data.Repositories +namespace Geen.Data.Repositories; + +public class PlayerRepository : IPlayerRepository { - public class PlayerRepository : IPlayerRepository + private readonly MongoContext _context; + + public PlayerRepository(MongoContext context) { - private readonly MongoContext _context; + _context = context; + } - public PlayerRepository(MongoContext context) - { - _context = context; - } + public async Task GetById(int id) + { + var result = await _context.For() + .Find(x => x.Id == id) + .FirstOrDefaultAsync(); - public async Task GetById(int id) - { - var result = await _context.For() - .Find(x => x.Id == id) - .FirstOrDefaultAsync(); + return result.Map(); + } - return result.Map(); - } + public async Task GetByUrlName(string urlName) + { + var result = await _context.For() + .Find(x => x.UrlName == urlName) + .FirstOrDefaultAsync(); - public async Task GetByUrlName(string urlName) - { - var result = await _context.For() - .Find(x => x.UrlName == urlName) - .FirstOrDefaultAsync(); + return result.Map(); + } - return result.Map(); - } + public async Task GetClubCoach(string clubUrlName) + { + const int coachPosition = 4; - public async Task GetClubCoach(string clubUrlName) - { - const int coachPosition = 4; - - var result = await _context.For() - .Find(x => x.Club.UrlName == clubUrlName && x.Position == coachPosition) - .FirstOrDefaultAsync(); + var result = await _context.For() + .Find(x => x.Club.UrlName == clubUrlName && x.Position == coachPosition) + .FirstOrDefaultAsync(); - return result.Map(); - } + return result.Map(); + } - public async Task> GetList(string query, string clubUrlName, int page) - { - var filter = FilterDefinition.Empty; + public async Task> GetList(string query, string clubUrlName, int page) + { + var filter = FilterDefinition.Empty; - if (!string.IsNullOrWhiteSpace(clubUrlName)) - { - filter = filter & Builders.Filter.Eq(x => x.Club.UrlName, clubUrlName); - } + if (!string.IsNullOrWhiteSpace(clubUrlName)) + filter = filter & Builders.Filter.Eq(x => x.Club.UrlName, clubUrlName); - if (!string.IsNullOrWhiteSpace(query)) - { - filter = filter & Builders.Filter.Regex(x => x.LastName, - new BsonRegularExpression(Regex.Escape(query), "i")); - } + if (!string.IsNullOrWhiteSpace(query)) + filter = filter & Builders.Filter.Regex(x => x.LastName, + new BsonRegularExpression(Regex.Escape(query), "i")); - var result = await _context.For() - .Find(filter) - .SortByDescending(x => x.Id) - .ToPagedAsync(page); + var result = await _context.For() + .Find(filter) + .SortByDescending(x => x.Id) + .ToPagedAsync(page); - return result.Map>(); - } + return result.Map>(); + } - public Task> GetUrls() - { - var projection = Builders - .Projection - .Expression(x => x.UrlName); - - return _context.For() - .Find(x => true) - .Project(projection) - .ToListAsync(); - } + public Task> GetUrls() + { + var projection = Builders + .Projection + .Expression(x => x.UrlName); + + return _context.For() + .Find(x => true) + .Project(projection) + .ToListAsync(); + } - public async Task> GetByClubUrlName(string clubUrlName) - { - var result = await _context.For() - .Find(x => x.Club.UrlName == clubUrlName) - .ToListAsync(); + public async Task> GetByClubUrlName(string clubUrlName) + { + var result = await _context.For() + .Find(x => x.Club.UrlName == clubUrlName) + .ToListAsync(); - return result.Map>(); - } + return result.Map>(); + } - public Task> GetIdsByClubAndPosition(string clubUrlName, int position) - { - var projection = Builders - .Projection - .Expression(x => x.Id); - - return _context.For() - .Find(x => x.Club.UrlName == clubUrlName && x.Position == position) - .Project(projection) - .ToListAsync(); - } + public Task> GetIdsByClubAndPosition(string clubUrlName, int position) + { + var projection = Builders + .Projection + .Expression(x => x.Id); + + return _context.For() + .Find(x => x.Club.UrlName == clubUrlName && x.Position == position) + .Project(projection) + .ToListAsync(); + } - public async Task> GetByIds(List ids) - { - var result = await _context.For() - .Find(x => ids.Contains(x.Id)) - .ToListAsync(); + public async Task> GetByIds(List ids) + { + var result = await _context.For() + .Find(x => ids.Contains(x.Id)) + .ToListAsync(); - return result.Map>(); - } + return result.Map>(); + } - public Task> GetTopPlayers(string clubUrlName) - { - if (!string.IsNullOrWhiteSpace(clubUrlName)) - return GetTopClubPlayerModels(clubUrlName); + public Task> GetTopPlayers(string clubUrlName) + { + if (!string.IsNullOrWhiteSpace(clubUrlName)) + return GetTopClubPlayerModels(clubUrlName); - return GetTopGlobalPlayerModels(); - } + return GetTopGlobalPlayerModels(); + } - public async Task> GetRelatedPlayers(string urlName) - { - var filter = Builders.Filter - .Where(x => x.Player.UrlName == urlName); + public async Task> GetRelatedPlayers(string urlName) + { + var filter = Builders.Filter + .Where(x => x.Player.UrlName == urlName); - var projection = Builders.Projection.Include(x => x.Related.Players); + var projection = Builders.Projection.Include(x => x.Related.Players); - var topRelatedPlayerModels = await _context.For() - .Aggregate(new AggregateOptions { AllowDiskUse = true }) - .Match(filter) - .Project(projection) - .Unwind(x => x.Related.Players) - .SortByCount(x => x.Related) - .Limit(3) - .ToListAsync(); + var topRelatedPlayerModels = await _context.For() + .Aggregate(new AggregateOptions { AllowDiskUse = true }) + .Match(filter) + .Project(projection) + .Unwind(x => x.Related.Players) + .SortByCount(x => x.Related) + .Limit(3) + .ToListAsync(); - var topRelatedPlayerModelsIds = topRelatedPlayerModels - .Select(x => x.Id.Players) - .ToList(); + var topRelatedPlayerModelsIds = topRelatedPlayerModels + .Select(x => x.Id.Players) + .ToList(); - var result = await _context.For() - .Find(x => topRelatedPlayerModelsIds.Contains(x.Id)) - .ToListAsync(); + var result = await _context.For() + .Find(x => topRelatedPlayerModelsIds.Contains(x.Id)) + .ToListAsync(); - return result.Map>(); - } + return result.Map>(); + } - private async Task> GetTopClubPlayerModels(string clubUrlName) - { - var filter = Builders.Filter.Where(x => x.Club.UrlName == clubUrlName); + public async Task GetRandom() + { + var result = await _context.For() + .Aggregate() + .Match(x => x.Club.UrlName != null) + .AppendStage("{ $sample: { size: 1 } }") + .FirstOrDefaultAsync(); - var result = await _context.For() - .Find(filter) - .SortByDescending(x => x.MentionsCount) - .Limit(12) - .ToListAsync(); + return result.Map(); + } - return result.Map>(); - } + public async Task<(PlayerModel Left, PlayerModel Right)> GetForVotes(int position) + { + var leftPlayer = await _context.For() + .Aggregate() + .Match(x => x.Position == position) + .AppendStage("{ $sample: { size: 1 } }") + .FirstOrDefaultAsync(); + + var rightPlayer = await _context.For() + .Aggregate() + .Match(x => x.Id != leftPlayer.Id && x.Position == position) + .AppendStage("{ $sample: { size: 1 } }") + .FirstOrDefaultAsync(); + + return (leftPlayer.Map(), rightPlayer.Map()); + } - private async Task> GetTopGlobalPlayerModels() - { - var dateTime = DateTime.UtcNow.AddYears(-3); + public async Task> GetAll() + { + var result = await _context.For() + .Find(x => true) + .ToListAsync(); - var filter = Builders.Filter - .Where(x => x.Player.UrlName != null && x.Date > dateTime); + return result.Map>(); + } - var topPlayerModels = await _context.For() - .Aggregate(new AggregateOptions { AllowDiskUse = true }) - .Match(filter) - .SortByCount(x => x.Player.Id) - .Limit(12) - .ToListAsync(); + public async Task GetNextId() + { + var projection = Builders.Projection.Expression(x => (int?)x.Id); - var playerLookup = topPlayerModels.ToLookup(x => x.Id, y => y.Count); + var lastId = await _context.For() + .Find(x => true) + .SortByDescending(x => x.Id) + .Project(projection) + .FirstOrDefaultAsync(); - var playerIds = topPlayerModels.Select(x => x.Id); + if (!lastId.HasValue) + return 1; - var result = await _context.For() - .Find(x => playerIds.Contains(x.Id)) - .ToListAsync(); + return lastId.Value + 1; + } - var preResult = result - .OrderByDescending(x => playerLookup[x.Id].FirstOrDefault()) - .ToList(); + public Task IncrementMentionsCount(int id) + { + var update = Builders.Update + .Inc(x => x.MentionsCount, 1); - return preResult.Map>(); - } + return _context.For() + .UpdateOneAsync(x => x.Id == id, update); + } - public async Task GetRandom() - { - var result = await _context.For() - .Aggregate() - .Match(x => x.Club.UrlName != null) - .AppendStage("{ $sample: { size: 1 } }") - .FirstOrDefaultAsync(); + public Task Save(PlayerModel model) + { + var entity = model.Map(); - return result.Map(); - } + return _context.For() + .ReplaceOneAsync(x => x.Id == model.Id, entity, + new ReplaceOptions { IsUpsert = true }); + } + + public async Task> Search(string query, int count) + { + var filter = Builders.Filter + .Regex(x => x.LastName, new BsonRegularExpression(Regex.Escape(query), "i")); + + var result = await _context.For() + .Find(filter) + .Limit(count) + .ToListAsync(); + + return result.Map>(); + } + + public async Task> GetCached() + { + var projection = Builders.Projection + .Include(x => x.Id) + .Include(x => x.LastName) + .Include(x => x.UrlName) + .Include(x => x.Club.Id); + + var playerModels = await _context.For() + .Find(x => true) + .Project(projection) + .ToListAsync(); + + var result = new List(); + + var actualPlayers = playerModels.Where(x => x.LastName != null && x.LastName.Length > 3) + .OrderByDescending(x => x.LastName.Length); - public async Task<(PlayerModel Left, PlayerModel Right)> GetForVotes(int position) + foreach (var playerModel in actualPlayers) { - var leftPlayer = await _context.For() - .Aggregate() - .Match(x => x.Position == position) - .AppendStage("{ $sample: { size: 1 } }") - .FirstOrDefaultAsync(); - - var rightPlayer = await _context.For() - .Aggregate() - .Match(x => x.Id != leftPlayer.Id && x.Position == position) - .AppendStage("{ $sample: { size: 1 } }") - .FirstOrDefaultAsync(); - - return (leftPlayer.Map(), rightPlayer.Map()); + playerModel.LastName = playerModel.LastName?.ToLower(); + result.Add(playerModel); } - public async Task> GetAll() - { - var result = await _context.For() - .Find(x => true) - .ToListAsync(); + return result.Map>(); + } - return result.Map>(); - } + private async Task> GetTopClubPlayerModels(string clubUrlName) + { + var filter = Builders.Filter.Where(x => x.Club.UrlName == clubUrlName); - public async Task> GetAllUrls() - { - var projection = Builders - .Projection - .Include(x => x.UrlName); + var result = await _context.For() + .Find(filter) + .SortByDescending(x => x.MentionsCount) + .Limit(12) + .ToListAsync(); - var result = await _context.For() - .Find(x => true) - .Project(projection) - .ToListAsync(); + return result.Map>(); + } - return result.Map>(); - } + private async Task> GetTopGlobalPlayerModels() + { + var dateTime = DateTime.UtcNow.AddYears(-3); - public async Task GetNextId() - { - var projection = Builders.Projection.Expression(x => (int?)x.Id); + var filter = Builders.Filter + .Where(x => x.Player.UrlName != null && x.Date > dateTime); - var lastId = await _context.For() - .Find(x => true) - .SortByDescending(x => x.Id) - .Project(projection) - .FirstOrDefaultAsync(); + var topPlayerModels = await _context.For() + .Aggregate(new AggregateOptions { AllowDiskUse = true }) + .Match(filter) + .SortByCount(x => x.Player.Id) + .Limit(12) + .ToListAsync(); - if (!lastId.HasValue) - return 1; + var playerLookup = topPlayerModels.ToLookup(x => x.Id, y => y.Count); - return lastId.Value + 1; - } + var playerIds = topPlayerModels.Select(x => x.Id); - public Task IncrementMentionsCount(int id) - { - var update = Builders.Update - .Inc(x => x.MentionsCount, 1); + var result = await _context.For() + .Find(x => playerIds.Contains(x.Id)) + .ToListAsync(); - return _context.For() - .UpdateOneAsync(x => x.Id == id, update); - } + var preResult = result + .OrderByDescending(x => playerLookup[x.Id].FirstOrDefault()) + .ToList(); - public Task> GetBirthdays(string urlName) - { - var projection = Builders - .Projection - .Expression(x => x.BirthDate); - - return _context.For() - .Find(x => x.Club.UrlName == urlName && x.Position != 4) //no coach - .Project(projection) - .ToListAsync(); - } + return preResult.Map>(); + } - public Task Save(PlayerModel model) - { - var entity = model.Map(); + public async Task> GetAllUrls() + { + var projection = Builders + .Projection + .Include(x => x.UrlName); - return _context.For() - .ReplaceOneAsync(x => x.Id == model.Id, entity, - new ReplaceOptions { IsUpsert = true }); - } + var result = await _context.For() + .Find(x => true) + .Project(projection) + .ToListAsync(); - public async Task> Search(string query, int count) - { - var filter = Builders.Filter - .Regex(x => x.LastName, new BsonRegularExpression(Regex.Escape(query), "i")); - - var result = await _context.For() - .Find(filter) - .Limit(count) - .ToListAsync(); - - return result.Map>(); - } + return result.Map>(); + } - public async Task> GetCached() - { - var projection = Builders.Projection - .Include(x => x.Id) - .Include(x => x.LastName) - .Include(x => x.UrlName) - .Include(x => x.Club.Id); - - var playerModels = await _context.For() - .Find(x => true) - .Project(projection) - .ToListAsync(); - - var result = new List(); - - var actualPlayers = playerModels.Where(x => x.LastName != null && x.LastName.Length > 3) - .OrderByDescending(x => x.LastName.Length); - - foreach (var playerModel in actualPlayers) - { - playerModel.LastName = playerModel.LastName?.ToLower(); - result.Add(playerModel); - } - - return result.Map>(); - } + public Task> GetBirthdays(string urlName) + { + var projection = Builders + .Projection + .Expression(x => x.BirthDate); + + return _context.For() + .Find(x => x.Club.UrlName == urlName && x.Position != 4) //no coach + .Project(projection) + .ToListAsync(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Repositories/ReplyRepository.cs b/src/Backend/Geen.Data/Repositories/ReplyRepository.cs index 6d3ad72..4fc8c42 100644 --- a/src/Backend/Geen.Data/Repositories/ReplyRepository.cs +++ b/src/Backend/Geen.Data/Repositories/ReplyRepository.cs @@ -1,171 +1,160 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Threading.Tasks; -using Geen.Core.Domains.Mentions.Models; using Geen.Core.Domains.Replies; using Geen.Core.Domains.Replies.Queries; using Geen.Core.Domains.Replies.Repositories; -using Geen.Core.Models.Likes; using Geen.Data.Entities; using Geen.Data.Extensions; using Geen.Data.Storages.Mongo; using Geen.Data.Utils; -using Mapster; using MongoDB.Driver; using MongoDB.Driver.Linq; -namespace Geen.Data.Repositories +namespace Geen.Data.Repositories; + +public class ReplyRepository : IReplyRepository { - public class ReplyRepository : IReplyRepository + private readonly MongoContext _context; + + public ReplyRepository(MongoContext context) + { + _context = context; + } + + public async Task GetById(string id) + { + var result = await _context.For() + .Find(x => x.Id == id) + .FirstOrDefaultAsync(); + + return result.Map(); + } + + public async Task> GetList(GetReplyListQuery query) + { + var filter = Builders.Filter + .Where(x => x.MentionId == query.MentionId && x.IsApproved); + + var result = await _context.For() + .Find(filter) + .SortBy(x => x.Date) + .ToPagedAsync(query.Page); + + return result.Map>(); + } + + public async Task> GetLatestList(GetReplyLatestQuery query) + { + var mentionsQuery = _context.For().AsQueryable(); + var replyQuery = _context.For().AsQueryable(); + + var resultQuery = from reply in replyQuery + join mention in mentionsQuery on reply.MentionId equals mention.Id + where mention.Club.Id == query.ClubId + || mention.Player.Id == query.PlayerId + select reply; + + var result = await resultQuery.Take(query.Count).ToListAsync(); + + return result.Map>(); + } + + public async Task> GetUnapprovedList(GetReplyUnapprovedListQuery query) + { + var builder = Builders.Filter; + + var filter = builder.Empty; + + if (query.IsApproved.HasValue) filter &= builder.Where(x => x.IsApproved == query.IsApproved.Value); + + if (query.MentionId.HasValue) filter &= builder.Where(x => x.MentionId == query.MentionId); + + var result = await _context.For() + .Find(filter) + .SortByDescending(x => x.Date) + .ToPagedAsync(query.Page); + + return result.Map>(); + } + + public async Task Approve(string id) + { + var update = Builders.Update + .Set(x => x.IsApproved, true); + + var result = await _context.For() + .FindOneAndUpdateAsync(x => x.Id == id, update); + + await IncRepliesCount(result.MentionId, 1); + } + + public async Task Disapprove(string id) + { + var update = Builders.Update + .Set(x => x.IsApproved, false); + + var result = await _context.For() + .FindOneAndUpdateAsync(x => x.Id == id, update); + + await IncRepliesCount(result.MentionId, -1); + } + + public async Task UpdateText(string id, string text) + { + var update = Builders.Update + .Set(x => x.Text, text); + + var result = await _context.For() + .FindOneAndUpdateAsync(x => x.Id == id, update); + + var updateMention = Builders.Update + .Set(x => x.TitleChangeDate, DateTime.UtcNow); + + await _context.For() + .UpdateOneAsync(x => x.Id == result.MentionId, updateMention); + } + + public Task Save(ReplyModel model) + { + var entity = model.Map(); + + return _context.For().InsertOneAsync(entity); + } + + public Task Delete(string id) + { + return _context.For() + .DeleteOneAsync(x => x.Id == id); + } + + public async Task> GetAll(int count) { - private readonly MongoContext _context; - - public ReplyRepository(MongoContext context) - { - _context = context; - } - - public async Task GetById(string id) - { - var result = await _context.For() - .Find(x => x.Id == id) - .FirstOrDefaultAsync(); - - return result.Map(); - } - - public async Task> GetList(GetReplyListQuery query) - { - var filter = Builders.Filter - .Where(x => x.MentionId == query.MentionId && x.IsApproved); - - var result = await _context.For() - .Find(filter) - .SortBy(x => x.Date) - .ToPagedAsync(query.Page); - - return result.Map>(); - } - - public async Task> GetLatestList(GetReplyLatestQuery query) - { - var mentionsQuery = _context.For().AsQueryable(); - var replyQuery = _context.For().AsQueryable(); - - var resultQuery = from reply in replyQuery - join mention in mentionsQuery on reply.MentionId equals mention.Id - where mention.Club.Id == query.ClubId - || mention.Player.Id == query.PlayerId - select reply; - - var result = await resultQuery.Take(query.Count).ToListAsync(); - - return result.Map>(); - } - - public async Task> GetUnapprovedList(GetReplyUnapprovedListQuery query) - { - var builder = Builders.Filter; - - var filter = builder.Empty; - - if (query.IsApproved.HasValue) - { - filter &= builder.Where(x => x.IsApproved == query.IsApproved.Value); - } - - if (query.MentionId.HasValue) - { - filter &= builder.Where(x => x.MentionId == query.MentionId); - } - - var result = await _context.For() - .Find(filter) - .SortByDescending(x => x.Date) - .ToPagedAsync(query.Page); - - return result.Map>(); - } - - public async Task Approve(string id) - { - var update = Builders.Update - .Set(x => x.IsApproved, true); - - var result = await _context.For() - .FindOneAndUpdateAsync(x => x.Id == id, update); - - await IncRepliesCount(result.MentionId, 1); - } - - public async Task Disapprove(string id) - { - var update = Builders.Update - .Set(x => x.IsApproved, false); - - var result = await _context.For() - .FindOneAndUpdateAsync(x => x.Id == id, update); - - await IncRepliesCount(result.MentionId, -1); - } - - public async Task UpdateText(string id, string text) - { - var update = Builders.Update - .Set(x => x.Text, text); - - var result = await _context.For() - .FindOneAndUpdateAsync(x => x.Id == id, update); - - var updateMention = Builders.Update - .Set(x => x.TitleChangeDate, DateTime.UtcNow); - - await _context.For() - .UpdateOneAsync(x => x.Id == result.MentionId, updateMention); - } - - private Task IncRepliesCount(long mentionId, int value) - { - var mentionUpdate = Builders.Update - .Inc(x => x.RepliesCount, value); - - return _context.For() - .UpdateOneAsync(x => x.Id == mentionId, mentionUpdate); - } - - public Task Save(ReplyModel model) - { - var entity = model.Map(); - - return _context.For().InsertOneAsync(entity); - } - - public Task Delete(string id) - { - return _context.For() - .DeleteOneAsync(x => x.Id == id); - } - - public async Task> GetAll(int count) - { - var replies = await _context.For() - .Aggregate() - .AppendStage("{ $sample: { size: " + count + "} }") - .Project(x => new { x.Id }) - .ToListAsync(); - - return replies.Map>(); - } - - public Task UpdateUser(string id, string userName) - { - var update = Builders.Update - .Set(x => x.User.IsAnonymous, false) - .Set(x => x.User.Name, userName); - - return _context.For() - .UpdateOneAsync(x => x.Id == id, update); - } + var replies = await _context.For() + .Aggregate() + .AppendStage("{ $sample: { size: " + count + "} }") + .Project(x => new { x.Id }) + .ToListAsync(); + + return replies.Map>(); + } + + public Task UpdateUser(string id, string userName) + { + var update = Builders.Update + .Set(x => x.User.IsAnonymous, false) + .Set(x => x.User.Name, userName); + + return _context.For() + .UpdateOneAsync(x => x.Id == id, update); + } + + private Task IncRepliesCount(long mentionId, int value) + { + var mentionUpdate = Builders.Update + .Inc(x => x.RepliesCount, value); + + return _context.For() + .UpdateOneAsync(x => x.Id == mentionId, mentionUpdate); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Repositories/VoteRepository.cs b/src/Backend/Geen.Data/Repositories/VoteRepository.cs index 10bd4e4..06be21c 100644 --- a/src/Backend/Geen.Data/Repositories/VoteRepository.cs +++ b/src/Backend/Geen.Data/Repositories/VoteRepository.cs @@ -5,22 +5,21 @@ using Geen.Data.Extensions; using Geen.Data.Storages.Mongo; -namespace Geen.Data.Repositories +namespace Geen.Data.Repositories; + +public class VoteRepository : IVoteRepository { - public class VoteRepository : IVoteRepository + private readonly MongoContext _context; + + public VoteRepository(MongoContext context) { - private readonly MongoContext _context; + _context = context; + } - public VoteRepository(MongoContext context) - { - _context = context; - } - - public Task Create(VoteModel model) - { - var entity = model.Map(); + public Task Create(VoteModel model) + { + var entity = model.Map(); - return _context.For().InsertOneAsync(entity); - } + return _context.For().InsertOneAsync(entity); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Services/Voting/VotingService.cs b/src/Backend/Geen.Data/Services/Voting/VotingService.cs index bee01ac..5b7223f 100644 --- a/src/Backend/Geen.Data/Services/Voting/VotingService.cs +++ b/src/Backend/Geen.Data/Services/Voting/VotingService.cs @@ -19,7 +19,7 @@ // public class VotingService : IService // { // private readonly GeenContext _context; - + // public VotingService(GeenContext context, PlayerService playerService) // { @@ -29,10 +29,9 @@ // public async Task GetClubVoteModel(int clubId) // { - + // } - // public async Task GetGlobalVoteModel() // { @@ -42,3 +41,4 @@ // } // } // } + diff --git a/src/Backend/Geen.Data/Settings/GeenSettings.cs b/src/Backend/Geen.Data/Settings/GeenSettings.cs index aca6b0b..bf44e08 100644 --- a/src/Backend/Geen.Data/Settings/GeenSettings.cs +++ b/src/Backend/Geen.Data/Settings/GeenSettings.cs @@ -1,37 +1,36 @@ -namespace Geen.Data.Settings +namespace Geen.Data.Settings; + +public class GeenSettings { - public class GeenSettings - { - public virtual DatabaseSettingsSettings Database { get; set; } - public virtual AuthenticationSettings Authentication { get; set; } - public virtual PrerenderSettings Prerender { get; set; } - public virtual TracingSettings Tracing { get; set; } - } + public virtual DatabaseSettingsSettings Database { get; set; } + public virtual AuthenticationSettings Authentication { get; set; } + public virtual PrerenderSettings Prerender { get; set; } + public virtual TracingSettings Tracing { get; set; } +} - public class DatabaseSettingsSettings - { - public string MongoUrl { get; set; } - public string RedisUrl { get; set; } - } +public class DatabaseSettingsSettings +{ + public string MongoUrl { get; set; } + public string RedisUrl { get; set; } +} - public class AuthenticationSettings - { - public string Login { get; set; } - public string Password { get; set; } - } +public class AuthenticationSettings +{ + public string Login { get; set; } + public string Password { get; set; } +} - public class PrerenderSettings - { - public string StaticPath { get; set; } - } - - public class TracingSettings +public class PrerenderSettings +{ + public string StaticPath { get; set; } +} + +public class TracingSettings +{ + public JaegerSettings Jaeger { get; set; } + + public class JaegerSettings { - public JaegerSettings Jaeger { get; set; } - - public class JaegerSettings - { - public string Endpoint { get; set; } - } + public string Endpoint { get; set; } } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Storages/Mongo/Extensions/MongoExtensions.cs b/src/Backend/Geen.Data/Storages/Mongo/Extensions/MongoExtensions.cs index ed04288..2cbf4e9 100644 --- a/src/Backend/Geen.Data/Storages/Mongo/Extensions/MongoExtensions.cs +++ b/src/Backend/Geen.Data/Storages/Mongo/Extensions/MongoExtensions.cs @@ -1,7 +1,5 @@ -namespace Geen.Data.Storages.Mongo.Extensions +namespace Geen.Data.Storages.Mongo.Extensions; + +public class MongoExtensions { - public class MongoExtensions - { - - } } \ No newline at end of file diff --git a/src/Backend/Geen.Data/Storages/Mongo/MongoContext.cs b/src/Backend/Geen.Data/Storages/Mongo/MongoContext.cs index 4dca531..dfe6abc 100644 --- a/src/Backend/Geen.Data/Storages/Mongo/MongoContext.cs +++ b/src/Backend/Geen.Data/Storages/Mongo/MongoContext.cs @@ -9,97 +9,97 @@ using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Events; -namespace Geen.Data.Storages.Mongo +namespace Geen.Data.Storages.Mongo; + +public class MongoContext : IDisposable { - public class MongoContext : IDisposable + private readonly ConcurrentDictionary _collectionNameCache = new(); + private readonly Lazy _mongoClient; + + private readonly MongoUrl _mongoUrl; + + public MongoContext(string mongoUrl, ILogger logger) { - private readonly ConcurrentDictionary _collectionNameCache = new(); + var settings = MongoClientSettings.FromUrl(new MongoUrl(mongoUrl)); - private readonly MongoUrl _mongoUrl; - private readonly Lazy _mongoClient; + settings.ClusterConfigurator = + cb => GetClusterBulder(cb, logger); - public MongoContext(string mongoUrl, ILogger logger) - { - var settings = MongoClientSettings.FromUrl(new MongoUrl(mongoUrl)); + settings.WaitQueueTimeout = TimeSpan.FromSeconds(30); - settings.ClusterConfigurator = - cb => GetClusterBulder(cb, logger); + _mongoUrl = new MongoUrl(mongoUrl); + _mongoClient = new Lazy(() => new MongoClient(settings)); + } - settings.WaitQueueTimeout = TimeSpan.FromSeconds(30); + public IMongoClient Client => _mongoClient.Value; - _mongoUrl = new MongoUrl(mongoUrl); - _mongoClient = new Lazy(() => new MongoClient(settings)); - } + public void Dispose() + { + } - public IMongoCollection For() - { - return GetCollection(); - } + public IMongoCollection For() + { + return GetCollection(); + } - public IMongoClient Client => _mongoClient.Value; + #region Internal - #region Internal + private string GetCollectionName(Type entityType) + { + var collectionAttr = + (MongoEntityAttribute)entityType.GetTypeInfo().GetCustomAttribute(typeof(MongoEntityAttribute)); - private string GetCollectionName(Type entityType) - { - var collectionAttr = (MongoEntityAttribute)entityType.GetTypeInfo().GetCustomAttribute(typeof(MongoEntityAttribute)); + if (collectionAttr == null) + throw new InvalidOperationException( + $"Entity with type '{entityType.GetTypeInfo().FullName}' is not MongoDB entity"); - if (collectionAttr == null) - throw new InvalidOperationException($"Entity with type '{entityType.GetTypeInfo().FullName}' is not MongoDB entity"); + if (string.IsNullOrWhiteSpace(collectionAttr.SchemaName)) + return collectionAttr.CollectionName; - if (string.IsNullOrWhiteSpace(collectionAttr.SchemaName)) - return collectionAttr.CollectionName; + return $"{collectionAttr.SchemaName}.{collectionAttr.CollectionName}"; + } - return $"{collectionAttr.SchemaName}.{collectionAttr.CollectionName}"; - } + private IMongoCollection GetCollection() + { + var database = _mongoClient.Value.GetDatabase(_mongoUrl.DatabaseName); - private IMongoCollection GetCollection() - { - var database = _mongoClient.Value.GetDatabase(_mongoUrl.DatabaseName); + return database.GetCollection(_collectionNameCache.GetOrAdd(typeof(TEntity), GetCollectionName)); + } - return database.GetCollection(_collectionNameCache.GetOrAdd(typeof(TEntity), GetCollectionName)); - } + #endregion - #endregion + #region Logging - #region Logging + private static readonly JsonWriterSettings JsonWriterSettings = new() + { + Indent = true + }; - private static readonly JsonWriterSettings JsonWriterSettings = new() - { - Indent = true - }; + private readonly HashSet _ignoringCommands = new() + { + "isMaster", + "buildInfo", + "getLastError" + }; - private readonly HashSet _ignoringCommands = new() + private void GetClusterBulder(ClusterBuilder builder, ILogger logger) + { + builder.Subscribe(e => { - "isMaster", - "buildInfo", - "getLastError" - }; + if (_ignoringCommands.Contains(e.CommandName)) + return; + }); - private void GetClusterBulder(ClusterBuilder builder, ILogger logger) - { - builder.Subscribe(e => - { - if (_ignoringCommands.Contains(e.CommandName)) - return; - }); - - builder.Subscribe(e => - { - if (_ignoringCommands.Contains(e.CommandName)) - return; - - if (e.Duration.TotalMilliseconds > 100) - { - logger.LogWarning("LONG REQUEST: {CommandName}, {Duration} ms ", e.CommandName, e.Duration.TotalMilliseconds); - } - }); - } - - #endregion - - public void Dispose() + builder.Subscribe(e => { - } + if (_ignoringCommands.Contains(e.CommandName)) + return; + + if (e.Duration.TotalMilliseconds > 100) + logger.LogWarning("LONG REQUEST: {CommandName}, {Duration} ms ", e.CommandName, + e.Duration.TotalMilliseconds); + }); } -} + + #endregion +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Storages/Redis/RedisStore.cs b/src/Backend/Geen.Data/Storages/Redis/RedisStore.cs index 06550d4..ad60dcb 100644 --- a/src/Backend/Geen.Data/Storages/Redis/RedisStore.cs +++ b/src/Backend/Geen.Data/Storages/Redis/RedisStore.cs @@ -1,18 +1,17 @@ using System; using StackExchange.Redis; -namespace Geen.Data.Storages.Redis -{ - public class RedisStore - { - private readonly Lazy _lazyConnection; +namespace Geen.Data.Storages.Redis; - public RedisStore(string redisUrl) - { - _lazyConnection = new Lazy( - () => ConnectionMultiplexer.Connect(redisUrl)); - } +public class RedisStore +{ + private readonly Lazy _lazyConnection; - public IDatabase Current => _lazyConnection.Value.GetDatabase(); + public RedisStore(string redisUrl) + { + _lazyConnection = new Lazy( + () => ConnectionMultiplexer.Connect(redisUrl)); } -} + + public IDatabase Current => _lazyConnection.Value.GetDatabase(); +} \ No newline at end of file diff --git a/src/Backend/Geen.Data/Utils/PagingExtensions.cs b/src/Backend/Geen.Data/Utils/PagingExtensions.cs index c0e78a5..3ed4485 100644 --- a/src/Backend/Geen.Data/Utils/PagingExtensions.cs +++ b/src/Backend/Geen.Data/Utils/PagingExtensions.cs @@ -2,20 +2,19 @@ using System.Threading.Tasks; using MongoDB.Driver; -namespace Geen.Data.Utils +namespace Geen.Data.Utils; + +public static class PagingExtensions { - public static class PagingExtensions - { - private const int PageSize = 30; + private const int PageSize = 30; - public static async Task> ToPagedAsync(this IFindFluent items, int page) - { - if (page < 1) - page = 1; + public static async Task> ToPagedAsync(this IFindFluent items, int page) + { + if (page < 1) + page = 1; - var skip = (page - 1) * PageSize; + var skip = (page - 1) * PageSize; - return await items.Skip(skip).Limit(PageSize).ToListAsync(); - } + return await items.Skip(skip).Limit(PageSize).ToListAsync(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Jobs/Application/Jobs/SportsSyncService.cs b/src/Backend/Geen.Jobs/Application/Jobs/SportsSyncService.cs index acccd46..7c4e30b 100644 --- a/src/Backend/Geen.Jobs/Application/Jobs/SportsSyncService.cs +++ b/src/Backend/Geen.Jobs/Application/Jobs/SportsSyncService.cs @@ -6,7 +6,7 @@ public class SportsSyncService : IHostedService { public Task StartAsync(CancellationToken cancellationToken) { - return Task.CompletedTask; + return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) diff --git a/src/Backend/Geen.Jobs/Geen.Jobs.csproj b/src/Backend/Geen.Jobs/Geen.Jobs.csproj index 8b9c9d4..0496066 100644 --- a/src/Backend/Geen.Jobs/Geen.Jobs.csproj +++ b/src/Backend/Geen.Jobs/Geen.Jobs.csproj @@ -8,12 +8,12 @@ - - + + - + diff --git a/src/Backend/Geen.Jobs/Program.cs b/src/Backend/Geen.Jobs/Program.cs index 141b08f..0b2c7b8 100644 --- a/src/Backend/Geen.Jobs/Program.cs +++ b/src/Backend/Geen.Jobs/Program.cs @@ -4,10 +4,7 @@ using Microsoft.Extensions.Logging; await Host.CreateDefaultBuilder(args) - .ConfigureServices(services => - { - services.AddHostedService(); - }) + .ConfigureServices(services => { services.AddHostedService(); }) .ConfigureLogging(builder => { builder.ClearProviders() diff --git a/src/Backend/Geen.Web/Application/Attributes/FromJsonUriAttribute.cs b/src/Backend/Geen.Web/Application/Attributes/FromJsonUriAttribute.cs index da97982..0411ba2 100644 --- a/src/Backend/Geen.Web/Application/Attributes/FromJsonUriAttribute.cs +++ b/src/Backend/Geen.Web/Application/Attributes/FromJsonUriAttribute.cs @@ -2,21 +2,20 @@ using Geen.Web.Application.Formatter.Bindings; using Microsoft.AspNetCore.Mvc.ModelBinding; -namespace Geen.Web.Application.Attributes +namespace Geen.Web.Application.Attributes; + +[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Class)] +public class FromJsonUriAttribute : Attribute, IModelNameProvider, IBinderTypeProviderMetadata { - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Class)] - public class FromJsonUriAttribute : Attribute, IModelNameProvider, IBinderTypeProviderMetadata + public FromJsonUriAttribute() { - public FromJsonUriAttribute() - { - BinderType = typeof (JsonModelBinder); - BindingSource = BindingSource.Custom; - } + BinderType = typeof(JsonModelBinder); + BindingSource = BindingSource.Custom; + } - public Type BinderType { get; set; } + public Type BinderType { get; set; } - public BindingSource BindingSource { get; set; } + public BindingSource BindingSource { get; set; } - public string Name { get; set; } - } -} + public string Name { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Authentication/Extensions/LoginModelExtensions.cs b/src/Backend/Geen.Web/Application/Authentication/Extensions/LoginModelExtensions.cs index f3002d4..1787dcf 100644 --- a/src/Backend/Geen.Web/Application/Authentication/Extensions/LoginModelExtensions.cs +++ b/src/Backend/Geen.Web/Application/Authentication/Extensions/LoginModelExtensions.cs @@ -2,14 +2,14 @@ using Geen.Data.Settings; using Geen.Web.Application.Authentication.Model; -namespace Geen.Web.Application.Authentication.Extensions +namespace Geen.Web.Application.Authentication.Extensions; + +public static class LoginModelExtensions { - public static class LoginModelExtensions + public static bool IsSuccessAdminLogin(this LoginModel model, GeenSettings settings) { - public static bool IsSuccessAdminLogin(this LoginModel model, GeenSettings settings) - { - return string.Compare(settings.Authentication.Login, model.Login, StringComparison.OrdinalIgnoreCase) == 0 - && string.Compare(settings.Authentication.Password, model.Password, StringComparison.OrdinalIgnoreCase) == 0; - } + return string.Compare(settings.Authentication.Login, model.Login, StringComparison.OrdinalIgnoreCase) == 0 + && string.Compare(settings.Authentication.Password, model.Password, + StringComparison.OrdinalIgnoreCase) == 0; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Authentication/Filters/AuthenticationFilter.cs b/src/Backend/Geen.Web/Application/Authentication/Filters/AuthenticationFilter.cs index 9c2050b..014e410 100644 --- a/src/Backend/Geen.Web/Application/Authentication/Filters/AuthenticationFilter.cs +++ b/src/Backend/Geen.Web/Application/Authentication/Filters/AuthenticationFilter.cs @@ -8,38 +8,37 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -namespace Geen.Web.Application.Authentication.Filters +namespace Geen.Web.Application.Authentication.Filters; + +public class AuthenticationFilter : Attribute, IAsyncActionFilter { - public class AuthenticationFilter : Attribute, IAsyncActionFilter + public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { - public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) - { - var token = context.HttpContext.Request.Cookies[CookieConstants.AdministratorCookieName]; + var token = context.HttpContext.Request.Cookies[CookieConstants.AdministratorCookieName]; - if (string.IsNullOrWhiteSpace(token)) - { - context.Result = null; - context.HttpContext.Response.StatusCode = 401; - return; - } - - var geenSettings = context.HttpContext.RequestServices.GetService>(); - var authenticationService = context.HttpContext.RequestServices.GetService(); + if (string.IsNullOrWhiteSpace(token)) + { + context.Result = null; + context.HttpContext.Response.StatusCode = 401; + return; + } - var currentToken = authenticationService.CreateToken(new LoginModel - { - Login = geenSettings.Value.Authentication.Login, - Password = geenSettings.Value.Authentication.Password - }); + var geenSettings = context.HttpContext.RequestServices.GetService>(); + var authenticationService = context.HttpContext.RequestServices.GetService(); - if (string.Compare(token, currentToken, StringComparison.Ordinal) != 0) - { - context.Result = null; - context.HttpContext.Response.StatusCode = 401; - return; - } + var currentToken = authenticationService.CreateToken(new LoginModel + { + Login = geenSettings.Value.Authentication.Login, + Password = geenSettings.Value.Authentication.Password + }); - await next(); + if (string.Compare(token, currentToken, StringComparison.Ordinal) != 0) + { + context.Result = null; + context.HttpContext.Response.StatusCode = 401; + return; } + + await next(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Authentication/Model/LoginModel.cs b/src/Backend/Geen.Web/Application/Authentication/Model/LoginModel.cs index 2d2caac..562f50c 100644 --- a/src/Backend/Geen.Web/Application/Authentication/Model/LoginModel.cs +++ b/src/Backend/Geen.Web/Application/Authentication/Model/LoginModel.cs @@ -1,8 +1,7 @@ -namespace Geen.Web.Application.Authentication.Model +namespace Geen.Web.Application.Authentication.Model; + +public class LoginModel { - public class LoginModel - { - public string Login { get; set; } - public string Password { get; set; } - } -} + public string Login { get; set; } + public string Password { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Authentication/Services/AuthenticationService.cs b/src/Backend/Geen.Web/Application/Authentication/Services/AuthenticationService.cs index d990ae4..836bc35 100644 --- a/src/Backend/Geen.Web/Application/Authentication/Services/AuthenticationService.cs +++ b/src/Backend/Geen.Web/Application/Authentication/Services/AuthenticationService.cs @@ -2,14 +2,13 @@ using System.Text; using Geen.Web.Application.Authentication.Model; -namespace Geen.Web.Application.Authentication.Services +namespace Geen.Web.Application.Authentication.Services; + +public class AuthenticationService { - public class AuthenticationService + public string CreateToken(LoginModel model) { - public string CreateToken(LoginModel model) - { - var data = (model.Login + model.Password).Trim().ToLower(); - return Convert.ToBase64String(Encoding.ASCII.GetBytes(data)); - } + var data = (model.Login + model.Password).Trim().ToLower(); + return Convert.ToBase64String(Encoding.ASCII.GetBytes(data)); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Authentication/Services/UserService.cs b/src/Backend/Geen.Web/Application/Authentication/Services/UserService.cs index 68f0940..006d779 100644 --- a/src/Backend/Geen.Web/Application/Authentication/Services/UserService.cs +++ b/src/Backend/Geen.Web/Application/Authentication/Services/UserService.cs @@ -4,60 +4,59 @@ using Microsoft.AspNetCore.Http; using MongoDB.Bson; -namespace Geen.Web.Application.Authentication.Services +namespace Geen.Web.Application.Authentication.Services; + +public class UserService { - public class UserService + private readonly IHttpContextAccessor _contextAccessor; + + public UserService(IHttpContextAccessor contextAccessor) { - private readonly IHttpContextAccessor _contextAccessor; + _contextAccessor = contextAccessor; + } - public UserService(IHttpContextAccessor contextAccessor) + public UserModel GetCurrentUser() + { + var model = new UserModel { - _contextAccessor = contextAccessor; + Id = _contextAccessor.HttpContext.Request.Cookies.TryGetValue( + CookieConstants.AuthCookieName, out var anonymousId) + ? anonymousId + : UpdateUser() + }; + + var userName = _contextAccessor.HttpContext.Request.Cookies.TryGetValue( + CookieConstants.UserNameCookieName, out var cookieUserName) + ? cookieUserName + : null; + + if (string.IsNullOrWhiteSpace(userName)) + { + model.IsAnonymous = true; + model.Name = null; } - - public UserModel GetCurrentUser() + else { - var model = new UserModel - { - Id = _contextAccessor.HttpContext.Request.Cookies.TryGetValue( - CookieConstants.AuthCookieName, out var anonymousId) - ? anonymousId - : UpdateUser() - }; - - string userName = _contextAccessor.HttpContext.Request.Cookies.TryGetValue( - CookieConstants.UserNameCookieName, out var cookieUserName) - ? cookieUserName - : null; - - if (string.IsNullOrWhiteSpace(userName)) - { - model.IsAnonymous = true; - model.Name = null; - } - else - { - model.IsAnonymous = false; - model.Name = userName; - } - - return model; + model.IsAnonymous = false; + model.Name = userName; } - private string UpdateUser() - { - var anonymousId = ObjectId.GenerateNewId().ToString(); + return model; + } - var cookiesContainer = _contextAccessor.HttpContext.Response.Cookies; + private string UpdateUser() + { + var anonymousId = ObjectId.GenerateNewId().ToString(); - cookiesContainer.Append(CookieConstants.AuthCookieName, anonymousId, - new CookieOptions - { - Expires = DateTime.UtcNow.AddYears(5), - Secure = true - }); + var cookiesContainer = _contextAccessor.HttpContext.Response.Cookies; - return anonymousId; - } + cookiesContainer.Append(CookieConstants.AuthCookieName, anonymousId, + new CookieOptions + { + Expires = DateTime.UtcNow.AddYears(5), + Secure = true + }); + + return anonymousId; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Constants/CookieConstants.cs b/src/Backend/Geen.Web/Application/Constants/CookieConstants.cs index c46e8c2..d2bda6c 100644 --- a/src/Backend/Geen.Web/Application/Constants/CookieConstants.cs +++ b/src/Backend/Geen.Web/Application/Constants/CookieConstants.cs @@ -1,9 +1,8 @@ -namespace Geen.Web.Application.Constants +namespace Geen.Web.Application.Constants; + +public static class CookieConstants { - public static class CookieConstants - { - public const string AuthCookieName = "geen_auth"; - public const string UserNameCookieName = "geen_user"; - public const string AdministratorCookieName = "geen_admin_auth"; - } -} + public const string AuthCookieName = "geen_auth"; + public const string UserNameCookieName = "geen_user"; + public const string AdministratorCookieName = "geen_admin_auth"; +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Dispatchers/CommandDispatcher.cs b/src/Backend/Geen.Web/Application/Dispatchers/CommandDispatcher.cs index 0a356ae..07446b5 100644 --- a/src/Backend/Geen.Web/Application/Dispatchers/CommandDispatcher.cs +++ b/src/Backend/Geen.Web/Application/Dispatchers/CommandDispatcher.cs @@ -5,37 +5,35 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -namespace Geen.Web.Application.Dispatchers +namespace Geen.Web.Application.Dispatchers; + +public sealed class CommandDispatcher : ICommandDispatcher { - public sealed class CommandDispatcher : ICommandDispatcher + private static readonly ConcurrentDictionary TypesCache = new(); + private readonly ILogger _logger; + private readonly IServiceProvider _serviceProvider; + + public CommandDispatcher(IServiceProvider serviceProvider) + { + _logger = serviceProvider.GetService>(); + + _serviceProvider = serviceProvider; + } + + public TResult Execute(ICommand command) { - private readonly ILogger _logger; - private readonly IServiceProvider _serviceProvider; - - private static readonly ConcurrentDictionary TypesCache = new(); - - public CommandDispatcher(IServiceProvider serviceProvider) - { - _logger = serviceProvider.GetService>(); - - _serviceProvider = serviceProvider; - } - - public TResult Execute(ICommand command) - { - var commandType = command.GetType(); - - var commandHandlerType = TypesCache.GetOrAdd( - commandType, - type => typeof(ICommandDispatcher<,>).MakeGenericType(type, typeof(TResult)) - ); - - dynamic commandHandler = _serviceProvider.GetService(commandHandlerType); - - if(_logger.IsEnabled(LogLevel.Information)) - _logger.LogInformation("Command: {Type}, {Body}", commandType.Name, command.ToJson()); - - return commandHandler.Execute((dynamic)command); - } + var commandType = command.GetType(); + + var commandHandlerType = TypesCache.GetOrAdd( + commandType, + type => typeof(ICommandDispatcher<,>).MakeGenericType(type, typeof(TResult)) + ); + + dynamic commandHandler = _serviceProvider.GetService(commandHandlerType); + + if (_logger.IsEnabled(LogLevel.Information)) + _logger.LogInformation("Command: {Type}, {Body}", commandType.Name, command.ToJson()); + + return commandHandler.Execute((dynamic)command); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Dispatchers/QueryDispatcher.cs b/src/Backend/Geen.Web/Application/Dispatchers/QueryDispatcher.cs index 32bfa1d..0a0de20 100644 --- a/src/Backend/Geen.Web/Application/Dispatchers/QueryDispatcher.cs +++ b/src/Backend/Geen.Web/Application/Dispatchers/QueryDispatcher.cs @@ -5,38 +5,36 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -namespace Geen.Web.Application.Dispatchers +namespace Geen.Web.Application.Dispatchers; + +public sealed class QueryDispatcher : IQueryDispatcher { - public sealed class QueryDispatcher : IQueryDispatcher - { - private readonly ILogger _logger; + private static readonly ConcurrentDictionary TypesCache = new(); + private readonly ILogger _logger; + + private readonly IServiceProvider _serviceProvider; - private readonly IServiceProvider _serviceProvider; + public QueryDispatcher(IServiceProvider serviceProvider) + { + _logger = serviceProvider.GetService>(); - private static readonly ConcurrentDictionary TypesCache = new(); + _serviceProvider = serviceProvider; + } - public QueryDispatcher(IServiceProvider serviceProvider) - { - _logger = serviceProvider.GetService>(); - - _serviceProvider = serviceProvider; - } + public TResult Execute(IQuery query) + { + var queryType = query.GetType(); - public TResult Execute(IQuery query) - { - var queryType = query.GetType(); - - var queryHandlerType = TypesCache.GetOrAdd( - queryType, - type => typeof(IQueryHandler<,>).MakeGenericType(type, typeof(TResult)) - ); + var queryHandlerType = TypesCache.GetOrAdd( + queryType, + type => typeof(IQueryHandler<,>).MakeGenericType(type, typeof(TResult)) + ); - dynamic queryHandler = _serviceProvider.GetService(queryHandlerType); + dynamic queryHandler = _serviceProvider.GetService(queryHandlerType); - if (_logger.IsEnabled(LogLevel.Debug)) - _logger.LogDebug("Query: {Type}, {Body}", queryType.Name, query.ToJson()); + if (_logger.IsEnabled(LogLevel.Debug)) + _logger.LogDebug("Query: {Type}, {Body}", queryType.Name, query.ToJson()); - return queryHandler.Execute((dynamic)query); - } + return queryHandler.Execute((dynamic)query); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Filters/Exceptions/ExceptionFilter.cs b/src/Backend/Geen.Web/Application/Filters/Exceptions/ExceptionFilter.cs index 8bb07c4..7937d93 100644 --- a/src/Backend/Geen.Web/Application/Filters/Exceptions/ExceptionFilter.cs +++ b/src/Backend/Geen.Web/Application/Filters/Exceptions/ExceptionFilter.cs @@ -2,24 +2,23 @@ using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; -namespace Geen.Web.Application.Filters.Exceptions +namespace Geen.Web.Application.Filters.Exceptions; + +public class ExceptionFilter : IAsyncExceptionFilter { - public class ExceptionFilter : IAsyncExceptionFilter + private readonly ILogger _logger; + + public ExceptionFilter(ILogger logger) { - private readonly ILogger _logger; + _logger = logger; + } - public ExceptionFilter(ILogger logger) - { - _logger = logger; - } + public Task OnExceptionAsync(ExceptionContext context) + { + _logger.LogError("Error: " + context.Exception); - public Task OnExceptionAsync(ExceptionContext context) - { - _logger.LogError("Error: " + context.Exception); - - context.HttpContext.Response.StatusCode = 500; + context.HttpContext.Response.StatusCode = 500; - return Task.CompletedTask; - } + return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Filters/Throttling/ThrottlingFilter.cs b/src/Backend/Geen.Web/Application/Filters/Throttling/ThrottlingFilter.cs index f25cf51..a90ef1f 100644 --- a/src/Backend/Geen.Web/Application/Filters/Throttling/ThrottlingFilter.cs +++ b/src/Backend/Geen.Web/Application/Filters/Throttling/ThrottlingFilter.cs @@ -5,54 +5,52 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; -namespace Geen.Web.Application.Filters.Throttling +namespace Geen.Web.Application.Filters.Throttling; + +public class ThrottleFilter : Attribute, IAsyncActionFilter { - public class ThrottleFilter : Attribute, IAsyncActionFilter - { - private readonly TimeSpan _minTimeSpan; + private static ConcurrentDictionary _clientActionActivity; + private readonly TimeSpan _minTimeSpan; - private static ConcurrentDictionary _clientActionActivity; + public ThrottleFilter(int hours, int minutes, int seconds, int milliseconds) + { + _minTimeSpan = new TimeSpan(0, hours, minutes, seconds, milliseconds); + _clientActionActivity = new ConcurrentDictionary(); + } - public ThrottleFilter(int hours, int minutes, int seconds, int milliseconds) - { - _minTimeSpan = new TimeSpan(0, hours, minutes, seconds, milliseconds); - _clientActionActivity = new ConcurrentDictionary(); - } + public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + if (context.HttpContext.Request.Method == "OPTIONS") + return; - public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) - { - if (context.HttpContext.Request.Method == "OPTIONS") - return; + var clientIp = GetIP(context); - var clientIp = GetIP(context); + if (string.IsNullOrWhiteSpace(clientIp)) + return; - if (string.IsNullOrWhiteSpace(clientIp)) - return; + var action = $"{clientIp}_{context.RouteData.Values["Controller"]}/{context.RouteData.Values["Action"]}"; - string action = $"{clientIp}_{context.RouteData.Values["Controller"]}/{context.RouteData.Values["Action"]}"; + var currentDate = DateTime.UtcNow; - var currentDate = DateTime.UtcNow; + var lastActivityDate = _clientActionActivity.GetOrAdd(action, initial => currentDate); - var lastActivityDate = _clientActionActivity.GetOrAdd(action, initial => currentDate); + if (currentDate != lastActivityDate) + { + _clientActionActivity.AddOrUpdate(action, str => currentDate, (str, dt) => currentDate); - if (currentDate != lastActivityDate) + if (currentDate - lastActivityDate <= _minTimeSpan) { - _clientActionActivity.AddOrUpdate(action, str => currentDate, (str, dt) => currentDate); - - if (currentDate - lastActivityDate <= _minTimeSpan) - { - context.Result = new StatusCodeResult(429); - return; - } + context.Result = new StatusCodeResult(429); + return; } - - await next(); } - private string GetIP(ActionExecutingContext context) - { - var connectionFeature = context.HttpContext.Features.Get(); - return connectionFeature?.RemoteIpAddress.ToString(); - } + await next(); + } + + private string GetIP(ActionExecutingContext context) + { + var connectionFeature = context.HttpContext.Features.Get(); + return connectionFeature?.RemoteIpAddress.ToString(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Formatter/Bindings/FromJsonUriAttribute.cs b/src/Backend/Geen.Web/Application/Formatter/Bindings/FromJsonUriAttribute.cs index 7bfa4f4..ef11b8c 100644 --- a/src/Backend/Geen.Web/Application/Formatter/Bindings/FromJsonUriAttribute.cs +++ b/src/Backend/Geen.Web/Application/Formatter/Bindings/FromJsonUriAttribute.cs @@ -1,21 +1,20 @@ using System; using Microsoft.AspNetCore.Mvc.ModelBinding; -namespace Geen.Web.Application.Formatter.Bindings +namespace Geen.Web.Application.Formatter.Bindings; + +[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Class)] +public class FromJsonUriAttribute : Attribute, IModelNameProvider, IBinderTypeProviderMetadata { - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Class)] - public class FromJsonUriAttribute : Attribute, IModelNameProvider, IBinderTypeProviderMetadata + public FromJsonUriAttribute() { - public FromJsonUriAttribute() - { - BinderType = typeof (JsonModelBinder); - BindingSource = BindingSource.Custom; - } + BinderType = typeof(JsonModelBinder); + BindingSource = BindingSource.Custom; + } - public Type BinderType { get; set; } + public Type BinderType { get; set; } - public BindingSource BindingSource { get; set; } + public BindingSource BindingSource { get; set; } - public string Name { get; set; } - } -} + public string Name { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Formatter/Bindings/JsonModelBinder.cs b/src/Backend/Geen.Web/Application/Formatter/Bindings/JsonModelBinder.cs index 882d455..73d4d94 100644 --- a/src/Backend/Geen.Web/Application/Formatter/Bindings/JsonModelBinder.cs +++ b/src/Backend/Geen.Web/Application/Formatter/Bindings/JsonModelBinder.cs @@ -2,22 +2,21 @@ using Geen.Web.Application.Services.Json; using Microsoft.AspNetCore.Mvc.ModelBinding; -namespace Geen.Web.Application.Formatter.Bindings +namespace Geen.Web.Application.Formatter.Bindings; + +public class JsonModelBinder : IModelBinder { - public class JsonModelBinder : IModelBinder + public Task BindModelAsync(ModelBindingContext bindingContext) { - public Task BindModelAsync(ModelBindingContext bindingContext) - { - var modelStringValue = bindingContext.HttpContext.Request.Query[bindingContext.ModelName]; + var modelStringValue = bindingContext.HttpContext.Request.Query[bindingContext.ModelName]; - if(string.IsNullOrWhiteSpace(modelStringValue)) - return Task.CompletedTask; + if (string.IsNullOrWhiteSpace(modelStringValue)) + return Task.CompletedTask; - var result = ((string) modelStringValue).FromJson(bindingContext.ModelType); + var result = ((string)modelStringValue).FromJson(bindingContext.ModelType); - bindingContext.Result = ModelBindingResult.Success(result); + bindingContext.Result = ModelBindingResult.Success(result); - return Task.CompletedTask; - } + return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Models/BodyText.cs b/src/Backend/Geen.Web/Application/Models/BodyText.cs index 95bdc12..e55ca1d 100644 --- a/src/Backend/Geen.Web/Application/Models/BodyText.cs +++ b/src/Backend/Geen.Web/Application/Models/BodyText.cs @@ -1,7 +1,6 @@ -namespace Geen.Web.Application.Models +namespace Geen.Web.Application.Models; + +public class BodyText { - public class BodyText - { - public string Text { get; set; } - } -} + public string Text { get; set; } +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Models/MentionCreateDto.cs b/src/Backend/Geen.Web/Application/Models/MentionCreateDto.cs index 2ffd5cb..b25894c 100644 --- a/src/Backend/Geen.Web/Application/Models/MentionCreateDto.cs +++ b/src/Backend/Geen.Web/Application/Models/MentionCreateDto.cs @@ -1,22 +1,21 @@ using Geen.Core.Models.Mentions; -namespace Geen.Web.Application.Models +namespace Geen.Web.Application.Models; + +public class MentionCreateDto { - public class MentionCreateDto - { - public string Text { get; set; } + public string Text { get; set; } - public int? ClubId { get; set; } - public int? PlayerId { get; set; } + public int? ClubId { get; set; } + public int? PlayerId { get; set; } - public MentionCreateModel ToModel() + public MentionCreateModel ToModel() + { + return new MentionCreateModel { - return new MentionCreateModel - { - Text = Text, - ClubId = ClubId, - PlayerId = PlayerId - }; - } + Text = Text, + ClubId = ClubId, + PlayerId = PlayerId + }; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Models/ReplyCreateDto.cs b/src/Backend/Geen.Web/Application/Models/ReplyCreateDto.cs index 000111d..20c0856 100644 --- a/src/Backend/Geen.Web/Application/Models/ReplyCreateDto.cs +++ b/src/Backend/Geen.Web/Application/Models/ReplyCreateDto.cs @@ -1,19 +1,18 @@ using Geen.Core.Models.Replies; -namespace Geen.Web.Application.Models +namespace Geen.Web.Application.Models; + +public class ReplyCreateDto { - public class ReplyCreateDto - { - public long MentionId { get; set; } - public string Text { get; set; } + public long MentionId { get; set; } + public string Text { get; set; } - public ReplyCreateModel ToModel() + public ReplyCreateModel ToModel() + { + return new ReplyCreateModel { - return new ReplyCreateModel - { - MentionId = MentionId, - Text = Text - }; - } + MentionId = MentionId, + Text = Text + }; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Registration.cs b/src/Backend/Geen.Web/Application/Registration.cs index badb415..526cfb8 100644 --- a/src/Backend/Geen.Web/Application/Registration.cs +++ b/src/Backend/Geen.Web/Application/Registration.cs @@ -16,111 +16,108 @@ using Microsoft.Extensions.DependencyInjection; using MongoDB.Bson; -namespace Geen.Web.Application +namespace Geen.Web.Application; + +public static class ServiceRegistration { - public static class ServiceRegistration + private static readonly List ApiPaths = new() { - public static GeenSettings RegisterInternalServices(this IServiceCollection services, IConfiguration configuration) - { - var settings = services.RegisterSettings(configuration); + new PathString("/api"), + new PathString("/metrics"), + new PathString("/gc"), + new PathString("/signin"), + new PathString("/signout") + }; + + private static readonly List GonePaths = new() + { + new PathString("/mention"), + new PathString("/page"), + new PathString("/club/list") + }; - services.RegisterDataServices(settings); - services.RegisterCoreServices(); - - services.AddSingleton(); - services.AddSingleton(); - - services.AddSingleton(); - services.AddTransient(); - services.AddTransient(); + public static GeenSettings RegisterInternalServices(this IServiceCollection services, IConfiguration configuration) + { + var settings = services.RegisterSettings(configuration); - services.AddSingleton(); + services.RegisterDataServices(settings); + services.RegisterCoreServices(); - return settings; - } + services.AddSingleton(); + services.AddSingleton(); - private static GeenSettings RegisterSettings(this IServiceCollection services, IConfiguration configuration) - { - services.AddOptions(); + services.AddSingleton(); + services.AddTransient(); + services.AddTransient(); - var settingsSection = configuration.GetSection("Settings"); + services.AddSingleton(); - services.Configure(settingsSection); + return settings; + } - return settingsSection.Get(); - } + private static GeenSettings RegisterSettings(this IServiceCollection services, IConfiguration configuration) + { + services.AddOptions(); - public static void UserAnonymous(this IApplicationBuilder app) - { - app.Use(async (context, func) => - { - if (!context.Request.Cookies.ContainsKey(CookieConstants.AuthCookieName)) - { - var geenId = ObjectId.GenerateNewId().ToString(); + var settingsSection = configuration.GetSection("Settings"); - context.Response.Cookies.Append(CookieConstants.AuthCookieName, geenId, - new CookieOptions { Expires = DateTime.UtcNow.AddYears(100) }); - } + services.Configure(settingsSection); - await func(); - }); - } + return settingsSection.Get(); + } - private static readonly List ApiPaths = new() - { - new PathString("/api"), - new PathString("/metrics"), - new PathString("/gc"), - new PathString("/signin"), - new PathString("/signout") - }; - - private static readonly List GonePaths = new() + public static void UserAnonymous(this IApplicationBuilder app) + { + app.Use(async (context, func) => { - new PathString("/mention"), - new PathString("/page"), - new PathString("/club/list") - }; + if (!context.Request.Cookies.ContainsKey(CookieConstants.AuthCookieName)) + { + var geenId = ObjectId.GenerateNewId().ToString(); + + context.Response.Cookies.Append(CookieConstants.AuthCookieName, geenId, + new CookieOptions { Expires = DateTime.UtcNow.AddYears(100) }); + } + + await func(); + }); + } - public static void UseFallbackRedirects(this IApplicationBuilder app) + public static void UseFallbackRedirects(this IApplicationBuilder app) + { + app.Use(async (context, next) => { - app.Use(async (context, next) => + if (GonePaths.Any(path => context.Request.Path.StartsWithSegments(path))) { - if (GonePaths.Any(path => context.Request.Path.StartsWithSegments(path))) + context.Response.StatusCode = 410; //gone + return; + } + + if (ApiPaths.All(path => !context.Request.Path.StartsWithSegments(path))) + if (context.Request.Path.ToString().EndsWith("page/1")) { - context.Response.StatusCode = 410; //gone + context.Response.Redirect(context.Request.Path.ToString().Replace("/page/1", ""), true); return; } - if (ApiPaths.All(path => !context.Request.Path.StartsWithSegments(path))) - { - if (context.Request.Path.ToString().EndsWith("page/1")) - { - context.Response.Redirect(context.Request.Path.ToString().Replace("/page/1", ""), true); - return; - } - } - - await next(); - }); - } + await next(); + }); + } - public static void UseSitemap(this IApplicationBuilder app) + public static void UseSitemap(this IApplicationBuilder app) + { + app.Use(async (context, next) => { - app.Use(async (context, next) => + if (string.CompareOrdinal(context.Request.Path, "/sitemap.xml") == 0) { - if (string.CompareOrdinal(context.Request.Path, "/sitemap.xml") == 0) - { - var sitemapProvider = context.RequestServices.GetService(); + var sitemapProvider = context.RequestServices.GetService(); - await context.Response.WriteAsync( - await sitemapProvider.Generate(), Encoding.UTF8); + await context.Response.WriteAsync( + await sitemapProvider.Generate(), Encoding.UTF8); - return; - } + return; + } - await next(); - }); - } + await next(); + }); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Services/Json/JsonService.cs b/src/Backend/Geen.Web/Application/Services/Json/JsonService.cs index 9659d39..e69e635 100644 --- a/src/Backend/Geen.Web/Application/Services/Json/JsonService.cs +++ b/src/Backend/Geen.Web/Application/Services/Json/JsonService.cs @@ -2,31 +2,30 @@ using System.Runtime.CompilerServices; using System.Text.Json; -namespace Geen.Web.Application.Services.Json +namespace Geen.Web.Application.Services.Json; + +public static class JsonService { - public static class JsonService + private static readonly JsonSerializerOptions JsonSerializerOptions = new() { - private static readonly JsonSerializerOptions JsonSerializerOptions = new() - { - PropertyNamingPolicy = JsonNamingPolicy.CamelCase - }; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static string ToJson(this object obj) - { - return JsonSerializer.Serialize(obj, JsonSerializerOptions); - } + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static T FromJson(this string data) - { - return JsonSerializer.Deserialize(data, JsonSerializerOptions); - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string ToJson(this object obj) + { + return JsonSerializer.Serialize(obj, JsonSerializerOptions); + } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static object FromJson(this string data, Type type) - { - return JsonSerializer.Deserialize(data, type, JsonSerializerOptions); - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T FromJson(this string data) + { + return JsonSerializer.Deserialize(data, JsonSerializerOptions); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object FromJson(this string data, Type type) + { + return JsonSerializer.Deserialize(data, type, JsonSerializerOptions); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Application/Sitemap/SitemapProvider.cs b/src/Backend/Geen.Web/Application/Sitemap/SitemapProvider.cs index ecb797a..c1bae7b 100644 --- a/src/Backend/Geen.Web/Application/Sitemap/SitemapProvider.cs +++ b/src/Backend/Geen.Web/Application/Sitemap/SitemapProvider.cs @@ -7,95 +7,88 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; -namespace Geen.Web.Application.Sitemap +namespace Geen.Web.Application.Sitemap; + +public class SitemapProvider { - public class SitemapProvider + private readonly IHttpContextAccessor _httpContextAccessor; + private readonly ILogger _logger; + + private readonly IQueryDispatcher _queryDispatcher; + + public SitemapProvider(ILogger logger, IQueryDispatcher queryDispatcher, + IHttpContextAccessor httpContextAccessor) { - private readonly ILogger _logger; - private readonly IHttpContextAccessor _httpContextAccessor; - - private readonly IQueryDispatcher _queryDispatcher; + _logger = logger; + _queryDispatcher = queryDispatcher; + _httpContextAccessor = httpContextAccessor; + } - public SitemapProvider(ILogger logger, IQueryDispatcher queryDispatcher, - IHttpContextAccessor httpContextAccessor) - { - _logger = logger; - _queryDispatcher = queryDispatcher; - _httpContextAccessor = httpContextAccessor; - } + public async ValueTask Generate() + { + _logger.LogInformation("SITEMAP REQUEST: {Ip}", _httpContextAccessor.HttpContext?.Request.Headers["X-Real-IP"]); - public async ValueTask Generate() - { - _logger.LogInformation("SITEMAP REQUEST: {Ip}", _httpContextAccessor.HttpContext?.Request.Headers["X-Real-IP"]); - - var builder = new StringBuilder("", 10 * 1024); + var builder = new StringBuilder("", 10 * 1024); - builder.AppendLine(""); + builder.AppendLine(""); - builder.AppendLine(""); - builder.AppendLine("https://geen.one/clubs"); - builder.AppendLine("yearly"); - builder.AppendLine(""); + builder.AppendLine(""); + builder.AppendLine("https://geen.one/clubs"); + builder.AppendLine("yearly"); + builder.AppendLine(""); - var clubsTask = _queryDispatcher.Execute(new ClubGetUrlsQuery()); - var playersTask = _queryDispatcher.Execute(new PlayerGetUrlsQuery()); - var mentionIdsTask = _queryDispatcher.Execute(new GetMentionIdentitiesQuery()); - - await Task.WhenAll(clubsTask, playersTask, mentionIdsTask); + var clubsTask = _queryDispatcher.Execute(new ClubGetUrlsQuery()); + var playersTask = _queryDispatcher.Execute(new PlayerGetUrlsQuery()); + var mentionIdsTask = _queryDispatcher.Execute(new GetMentionIdentitiesQuery()); - foreach (var club in clubsTask.Result) - { - builder.AppendLine(""); - builder.AppendLine($"https://geen.one/club/{club.UrlName}"); - builder.AppendLine("daily"); - builder.AppendLine("0.8"); - builder.AppendLine(""); + await Task.WhenAll(clubsTask, playersTask, mentionIdsTask); - if (!club.IsNational) - { - builder.AppendLine(""); - builder.AppendLine($"https://geen.one/club/{club.UrlName}/players"); - builder.AppendLine("monthly"); - builder.AppendLine("0.8"); - builder.AppendLine(""); - } - } + foreach (var club in clubsTask.Result) + { + builder.AppendLine(""); + builder.AppendLine($"https://geen.one/club/{club.UrlName}"); + builder.AppendLine("daily"); + builder.AppendLine("0.8"); + builder.AppendLine(""); - foreach (var playerUrl in playersTask.Result) + if (!club.IsNational) { builder.AppendLine(""); - builder.AppendLine($"https://geen.one/player/{playerUrl}"); - builder.AppendLine("daily"); + builder.AppendLine($"https://geen.one/club/{club.UrlName}/players"); + builder.AppendLine("monthly"); builder.AppendLine("0.8"); builder.AppendLine(""); } + } - foreach (var mention in mentionIdsTask.Result) - { - builder.AppendLine(""); - - if (mention.Club != null) - { - builder.AppendLine($"https://geen.one/club/{mention.Club.UrlName}/{mention.Id}"); - } - else if (mention.Player != null) - { - builder.AppendLine($"https://geen.one/player/{mention.Player.UrlName}/{mention.Id}"); - } - else - { - continue; - } - - builder.AppendLine("daily"); - builder.AppendLine("1"); - builder.AppendLine(""); - } + foreach (var playerUrl in playersTask.Result) + { + builder.AppendLine(""); + builder.AppendLine($"https://geen.one/player/{playerUrl}"); + builder.AppendLine("daily"); + builder.AppendLine("0.8"); + builder.AppendLine(""); + } + foreach (var mention in mentionIdsTask.Result) + { + builder.AppendLine(""); - builder.AppendLine(""); + if (mention.Club != null) + builder.AppendLine($"https://geen.one/club/{mention.Club.UrlName}/{mention.Id}"); + else if (mention.Player != null) + builder.AppendLine($"https://geen.one/player/{mention.Player.UrlName}/{mention.Id}"); + else + continue; - return builder.ToString(); + builder.AppendLine("daily"); + builder.AppendLine("1"); + builder.AppendLine(""); } + + + builder.AppendLine(""); + + return builder.ToString(); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/Admin/AdminClubController.cs b/src/Backend/Geen.Web/Controllers/Admin/AdminClubController.cs deleted file mode 100644 index 0d54e03..0000000 --- a/src/Backend/Geen.Web/Controllers/Admin/AdminClubController.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Geen.Core.Domains.Clubs; -using Geen.Core.Domains.Clubs.Commands; -using Geen.Core.Domains.Clubs.Queries; -using Geen.Core.Interfaces.Common; -using Geen.Web.Application.Authentication.Filters; -using Microsoft.AspNetCore.Mvc; - -namespace Geen.Web.Controllers.Admin -{ - [AuthenticationFilter] - public class AdminClubController : Controller - { - private readonly IQueryDispatcher _queryDispatcher; - private readonly ICommandDispatcher _commandDispatcher; - - public AdminClubController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher) - { - _queryDispatcher = queryDispatcher; - _commandDispatcher = commandDispatcher; - } - - [HttpGet("api/admin/club", Name = "getAdminClubList")] - public Task> List() - { - return _queryDispatcher.Execute(new ClubGetListQuery()); - } - - [HttpGet("api/admin/club/{id:int}", Name = "getAdminClub")] - public Task Get(int id) - { - return _queryDispatcher.Execute(new ClubGetByIdQuery { Id = id }); - } - - [HttpPost("api/admin/club", Name = "saveAdminClub")] - public Task Save([FromBody]ClubModel obj) - { - return _commandDispatcher.Execute(new ClubSaveCommand - { - Model = obj - }); - } - - [HttpGet("api/admin/club/next-id", Name = "getAdminClubNextId")] - public Task NextId() - { - return _queryDispatcher.Execute(new ClubNextIdQuery()); - } - } -} diff --git a/src/Backend/Geen.Web/Controllers/Admin/AdminCountryController.cs b/src/Backend/Geen.Web/Controllers/Admin/AdminCountryController.cs deleted file mode 100644 index 1f5a996..0000000 --- a/src/Backend/Geen.Web/Controllers/Admin/AdminCountryController.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Geen.Core.Domains.Countries; -using Geen.Core.Domains.Countries.Commands; -using Geen.Core.Domains.Countries.Queries; -using Geen.Core.Interfaces.Common; -using Geen.Web.Application.Authentication.Filters; -using Microsoft.AspNetCore.Mvc; - -namespace Geen.Web.Controllers.Admin -{ - [AuthenticationFilter] - public class AdminCountryController : Controller - { - private readonly IQueryDispatcher _queryDispatcher; - private readonly ICommandDispatcher _commandDispatcher; - - public AdminCountryController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher) - { - _queryDispatcher = queryDispatcher; - _commandDispatcher = commandDispatcher; - } - - [HttpGet("api/admin/country", Name = "getAdminCountryList")] - public Task> List() - { - return _queryDispatcher.Execute(new CountryGetListQuery()); - } - - [HttpGet("api/admin/country/{id:int}", Name = "getAdminCountry")] - public Task Get(int id) - { - return _queryDispatcher.Execute(new CountryGetByIdQuery { Id = id }); - } - - [HttpPost("api/admin/country", Name = "saveAdminCountry")] - public Task Save([FromBody]CountryModel obj) - { - return _commandDispatcher.Execute(new CountrySaveCommand - { - Model = obj - }); - } - } -} diff --git a/src/Backend/Geen.Web/Controllers/Admin/AdminLeagueController.cs b/src/Backend/Geen.Web/Controllers/Admin/AdminLeagueController.cs deleted file mode 100644 index 02c7623..0000000 --- a/src/Backend/Geen.Web/Controllers/Admin/AdminLeagueController.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Geen.Core.Domains.Leagues; -using Geen.Core.Domains.Leagues.Commands; -using Geen.Core.Domains.Leagues.Queries; -using Geen.Core.Interfaces.Common; -using Geen.Web.Application.Authentication.Filters; -using Microsoft.AspNetCore.Mvc; - -namespace Geen.Web.Controllers.Admin -{ - [AuthenticationFilter] - public class AdminLeagueController : Controller - { - private readonly IQueryDispatcher _queryDispatcher; - private readonly ICommandDispatcher _commandDispatcher; - - public AdminLeagueController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher) - { - _queryDispatcher = queryDispatcher; - _commandDispatcher = commandDispatcher; - } - - [HttpGet("api/admin/league", Name = "getAdminLeagueList")] - public Task> List() - { - return _queryDispatcher.Execute(new LeagueGetListQuery()); - } - - [HttpGet("api/admin/league/{id:int}", Name = "getAdminLeague")] - public Task Get(int id) - { - return _queryDispatcher.Execute(new LeagueGetByIdQuery { Id = id }); - } - - [HttpPost("api/admin/league", Name = "saveAdminLeague")] - public Task Save([FromBody]LeagueModel obj) - { - return _commandDispatcher.Execute(new LeagueSaveCommand - { - Model = obj - }); - } - } -} diff --git a/src/Backend/Geen.Web/Controllers/Admin/AdminMentionController.cs b/src/Backend/Geen.Web/Controllers/Admin/AdminMentionController.cs deleted file mode 100644 index 57128ae..0000000 --- a/src/Backend/Geen.Web/Controllers/Admin/AdminMentionController.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Geen.Core.Domains.Mentions; -using Geen.Core.Domains.Mentions.Commands; -using Geen.Core.Domains.Mentions.Queries; -using Geen.Core.Interfaces.Common; -using Geen.Web.Application.Attributes; -using Geen.Web.Application.Authentication.Filters; -using Geen.Web.Application.Models; -using Microsoft.AspNetCore.Mvc; - -namespace Geen.Web.Controllers.Admin -{ - [AuthenticationFilter] - public class AdminMentionController : Controller - { - private readonly IQueryDispatcher _queryDispatcher; - private readonly ICommandDispatcher _commandDispatcher; - - public AdminMentionController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher) - { - _queryDispatcher = queryDispatcher; - _commandDispatcher = commandDispatcher; - } - - [HttpGet("api/admin/mention/unapproved")] - public Task> UnapprovedList([FromJsonUri]GetMentionListQuery query) - { - return _queryDispatcher.Execute(query); - } - - [HttpGet("api/admin/mention/titles")] - public Task> TitlesList([FromJsonUri]GetMentionTitleListQuery query) - { - return _queryDispatcher.Execute(query); - } - - [HttpPost("api/admin/mention/approve")] - public Task Approve(long id) - { - return _commandDispatcher.Execute(new MentionApproveCommand - { - Id = id - }); - } - - [HttpPut("api/admin/mention/title")] - public Task ChangeTitle(long id, string title) - { - return _commandDispatcher.Execute(new MentionChangeTitleCommand - { - Id = id, - Title = title - }); - } - - [HttpPut("api/admin/mention/text")] - public Task ChangeText(long id, [FromBody]BodyText text) - { - return _commandDispatcher.Execute(new MentionChangeTextCommand - { - Id = id, - Text = text.Text - }); - } - - [HttpPost("api/admin/mention/disapprove")] - public Task Disapprove(long id) - { - return _commandDispatcher.Execute(new MentionDisapproveCommand - { - Id = id - }); - } - - [HttpDelete("api/admin/mention/{id:int}", Name = "mentionDelete")] - public Task Remove(long id) - { - return _commandDispatcher.Execute(new MentionRemoveCommand - { - Id = id - }); - } - - [HttpPut("api/admin/mention/anonymous-avatar")] - public Task SetAnonymousAvatar(long id) - { - return _commandDispatcher.Execute(new MentionSetDefaultAvatarCommand - { - Id = id - }); - } - } -} diff --git a/src/Backend/Geen.Web/Controllers/Admin/AdminPlayerController.cs b/src/Backend/Geen.Web/Controllers/Admin/AdminPlayerController.cs deleted file mode 100644 index c746c03..0000000 --- a/src/Backend/Geen.Web/Controllers/Admin/AdminPlayerController.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Geen.Core.Domains.Players; -using Geen.Core.Domains.Players.Commands; -using Geen.Core.Domains.Players.Queries; -using Geen.Core.Interfaces.Common; -using Geen.Web.Application.Attributes; -using Geen.Web.Application.Authentication.Filters; -using Microsoft.AspNetCore.Mvc; - -namespace Geen.Web.Controllers.Admin -{ - [AuthenticationFilter] - public class AdminPlayerController : Controller - { - private readonly IQueryDispatcher _queryDispatcher; - private readonly ICommandDispatcher _commandDispatcher; - - public AdminPlayerController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher) - { - _queryDispatcher = queryDispatcher; - _commandDispatcher = commandDispatcher; - } - - [HttpGet("api/admin/player", Name = "playerList")] - public Task> List([FromJsonUri]PlayerGetListQuery query) - { - return _queryDispatcher.Execute(query); - } - - [HttpGet("api/admin/player/{id:int}", Name = "getPlayer")] - public Task Get(int id) - { - return _queryDispatcher.Execute(new PlayerGetByIdQuery { Id = id }); - } - - [HttpPost("api/admin/player", Name = "savePlayer")] - public Task Save([FromBody]PlayerModel obj) - { - obj.FirstName = obj.FirstName.Trim(); - obj.LastName = obj.LastName.Trim(); - obj.UrlName = obj.UrlName.Trim(); - - return _commandDispatcher.Execute(new PlayerSaveCommand - { - Model = obj - }); - } - - [HttpGet("api/admin/player/next-id")] - public Task NextId() - { - return _queryDispatcher.Execute(new PlayerNextIdQuery()); - } - } -} diff --git a/src/Backend/Geen.Web/Controllers/Admin/AdminReplyController.cs b/src/Backend/Geen.Web/Controllers/Admin/AdminReplyController.cs deleted file mode 100644 index 2fd6834..0000000 --- a/src/Backend/Geen.Web/Controllers/Admin/AdminReplyController.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Geen.Core.Domains.Replies; -using Geen.Core.Domains.Replies.Commands; -using Geen.Core.Domains.Replies.Queries; -using Geen.Core.Interfaces.Common; -using Geen.Web.Application.Attributes; -using Geen.Web.Application.Authentication.Filters; -using Geen.Web.Application.Models; -using Microsoft.AspNetCore.Mvc; - -namespace Geen.Web.Controllers.Admin -{ - [AuthenticationFilter] - public class AdminReplyController : Controller - { - private readonly IQueryDispatcher _queryDispatcher; - private readonly ICommandDispatcher _commandDispatcher; - - public AdminReplyController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher) - { - _queryDispatcher = queryDispatcher; - _commandDispatcher = commandDispatcher; - } - - [HttpGet("api/admin/reply", Name = "unapproved")] - public Task> UnapprovedList([FromJsonUri]GetReplyUnapprovedListQuery query) - { - return _queryDispatcher.Execute(query); - } - - [HttpPatch("api/admin/reply/approve", Name = "approveReply")] - public Task Approve(string id) - { - return _commandDispatcher.Execute(new ReplyApproveCommand - { - Id = id - }); - } - - [HttpPatch("api/admin/reply/disapprove", Name = "disapproveReply")] - public Task Disapprove(string id) - { - return _commandDispatcher.Execute(new ReplyDisapproveCommand - { - Id = id - }); - } - - [HttpPut("api/admin/reply/text")] - public Task ChangeText(string id, [FromBody]BodyText text) - { - return _commandDispatcher.Execute(new ReplyChangeTextCommand - { - Id = id, - Text = text.Text - }); - } - - [HttpDelete("api/admin/reply/{id}", Name = "removeReply")] - public Task Remove(string id) - { - return _commandDispatcher.Execute(new ReplyRemoveCommand - { - ReplyId = id - }); - } - } -} diff --git a/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminClubController.cs b/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminClubController.cs new file mode 100644 index 0000000..9ade4f6 --- /dev/null +++ b/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminClubController.cs @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Geen.Core.Domains.Clubs; +using Geen.Core.Domains.Clubs.Commands; +using Geen.Core.Domains.Clubs.Queries; +using Geen.Core.Interfaces.Common; +using Geen.Web.Application.Authentication.Filters; +using Microsoft.AspNetCore.Mvc; + +namespace Geen.Web.Controllers.Areas.Admin; + +[AuthenticationFilter] +public class AdminClubController : Controller +{ + private readonly ICommandDispatcher _commandDispatcher; + private readonly IQueryDispatcher _queryDispatcher; + + public AdminClubController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher) + { + _queryDispatcher = queryDispatcher; + _commandDispatcher = commandDispatcher; + } + + [HttpGet("api/admin/club", Name = "getAdminClubList")] + public Task> List() + { + return _queryDispatcher.Execute(new ClubGetListQuery()); + } + + [HttpGet("api/admin/club/{id:int}", Name = "getAdminClub")] + public Task Get(int id) + { + return _queryDispatcher.Execute(new ClubGetByIdQuery { Id = id }); + } + + [HttpPost("api/admin/club", Name = "saveAdminClub")] + public Task Save([FromBody] ClubModel obj) + { + return _commandDispatcher.Execute(new ClubSaveCommand + { + Model = obj + }); + } + + [HttpGet("api/admin/club/next-id", Name = "getAdminClubNextId")] + public Task NextId() + { + return _queryDispatcher.Execute(new ClubNextIdQuery()); + } +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminCountryController.cs b/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminCountryController.cs new file mode 100644 index 0000000..30c7c2d --- /dev/null +++ b/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminCountryController.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Geen.Core.Domains.Countries; +using Geen.Core.Domains.Countries.Commands; +using Geen.Core.Domains.Countries.Queries; +using Geen.Core.Interfaces.Common; +using Geen.Web.Application.Authentication.Filters; +using Microsoft.AspNetCore.Mvc; + +namespace Geen.Web.Controllers.Areas.Admin; + +[AuthenticationFilter] +public class AdminCountryController : Controller +{ + private readonly ICommandDispatcher _commandDispatcher; + private readonly IQueryDispatcher _queryDispatcher; + + public AdminCountryController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher) + { + _queryDispatcher = queryDispatcher; + _commandDispatcher = commandDispatcher; + } + + [HttpGet("api/admin/country", Name = "getAdminCountryList")] + public Task> List() + { + return _queryDispatcher.Execute(new CountryGetListQuery()); + } + + [HttpGet("api/admin/country/{id:int}", Name = "getAdminCountry")] + public Task Get(int id) + { + return _queryDispatcher.Execute(new CountryGetByIdQuery { Id = id }); + } + + [HttpPost("api/admin/country", Name = "saveAdminCountry")] + public Task Save([FromBody] CountryModel obj) + { + return _commandDispatcher.Execute(new CountrySaveCommand + { + Model = obj + }); + } +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminLeagueController.cs b/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminLeagueController.cs new file mode 100644 index 0000000..6909481 --- /dev/null +++ b/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminLeagueController.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Geen.Core.Domains.Leagues; +using Geen.Core.Domains.Leagues.Commands; +using Geen.Core.Domains.Leagues.Queries; +using Geen.Core.Interfaces.Common; +using Geen.Web.Application.Authentication.Filters; +using Microsoft.AspNetCore.Mvc; + +namespace Geen.Web.Controllers.Areas.Admin; + +[AuthenticationFilter] +public class AdminLeagueController : Controller +{ + private readonly ICommandDispatcher _commandDispatcher; + private readonly IQueryDispatcher _queryDispatcher; + + public AdminLeagueController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher) + { + _queryDispatcher = queryDispatcher; + _commandDispatcher = commandDispatcher; + } + + [HttpGet("api/admin/league", Name = "getAdminLeagueList")] + public Task> List() + { + return _queryDispatcher.Execute(new LeagueGetListQuery()); + } + + [HttpGet("api/admin/league/{id:int}", Name = "getAdminLeague")] + public Task Get(int id) + { + return _queryDispatcher.Execute(new LeagueGetByIdQuery { Id = id }); + } + + [HttpPost("api/admin/league", Name = "saveAdminLeague")] + public Task Save([FromBody] LeagueModel obj) + { + return _commandDispatcher.Execute(new LeagueSaveCommand + { + Model = obj + }); + } +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminMentionController.cs b/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminMentionController.cs new file mode 100644 index 0000000..ad1e4fa --- /dev/null +++ b/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminMentionController.cs @@ -0,0 +1,93 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Geen.Core.Domains.Mentions; +using Geen.Core.Domains.Mentions.Commands; +using Geen.Core.Domains.Mentions.Queries; +using Geen.Core.Interfaces.Common; +using Geen.Web.Application.Attributes; +using Geen.Web.Application.Authentication.Filters; +using Geen.Web.Application.Models; +using Microsoft.AspNetCore.Mvc; + +namespace Geen.Web.Controllers.Areas.Admin; + +[AuthenticationFilter] +public class AdminMentionController : Controller +{ + private readonly ICommandDispatcher _commandDispatcher; + private readonly IQueryDispatcher _queryDispatcher; + + public AdminMentionController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher) + { + _queryDispatcher = queryDispatcher; + _commandDispatcher = commandDispatcher; + } + + [HttpGet("api/admin/mention/unapproved")] + public Task> UnapprovedList([FromJsonUri] GetMentionListQuery query) + { + return _queryDispatcher.Execute(query); + } + + [HttpGet("api/admin/mention/titles")] + public Task> TitlesList([FromJsonUri] GetMentionTitleListQuery query) + { + return _queryDispatcher.Execute(query); + } + + [HttpPost("api/admin/mention/approve")] + public Task Approve(long id) + { + return _commandDispatcher.Execute(new MentionApproveCommand + { + Id = id + }); + } + + [HttpPut("api/admin/mention/title")] + public Task ChangeTitle(long id, string title) + { + return _commandDispatcher.Execute(new MentionChangeTitleCommand + { + Id = id, + Title = title + }); + } + + [HttpPut("api/admin/mention/text")] + public Task ChangeText(long id, [FromBody] BodyText text) + { + return _commandDispatcher.Execute(new MentionChangeTextCommand + { + Id = id, + Text = text.Text + }); + } + + [HttpPost("api/admin/mention/disapprove")] + public Task Disapprove(long id) + { + return _commandDispatcher.Execute(new MentionDisapproveCommand + { + Id = id + }); + } + + [HttpDelete("api/admin/mention/{id:int}", Name = "mentionDelete")] + public Task Remove(long id) + { + return _commandDispatcher.Execute(new MentionRemoveCommand + { + Id = id + }); + } + + [HttpPut("api/admin/mention/anonymous-avatar")] + public Task SetAnonymousAvatar(long id) + { + return _commandDispatcher.Execute(new MentionSetDefaultAvatarCommand + { + Id = id + }); + } +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminPlayerController.cs b/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminPlayerController.cs new file mode 100644 index 0000000..40d3e13 --- /dev/null +++ b/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminPlayerController.cs @@ -0,0 +1,55 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Geen.Core.Domains.Players; +using Geen.Core.Domains.Players.Commands; +using Geen.Core.Domains.Players.Queries; +using Geen.Core.Interfaces.Common; +using Geen.Web.Application.Attributes; +using Geen.Web.Application.Authentication.Filters; +using Microsoft.AspNetCore.Mvc; + +namespace Geen.Web.Controllers.Areas.Admin; + +[AuthenticationFilter] +public class AdminPlayerController : Controller +{ + private readonly ICommandDispatcher _commandDispatcher; + private readonly IQueryDispatcher _queryDispatcher; + + public AdminPlayerController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher) + { + _queryDispatcher = queryDispatcher; + _commandDispatcher = commandDispatcher; + } + + [HttpGet("api/admin/player", Name = "playerList")] + public Task> List([FromJsonUri] PlayerGetListQuery query) + { + return _queryDispatcher.Execute(query); + } + + [HttpGet("api/admin/player/{id:int}", Name = "getPlayer")] + public Task Get(int id) + { + return _queryDispatcher.Execute(new PlayerGetByIdQuery { Id = id }); + } + + [HttpPost("api/admin/player", Name = "savePlayer")] + public Task Save([FromBody] PlayerModel obj) + { + obj.FirstName = obj.FirstName.Trim(); + obj.LastName = obj.LastName.Trim(); + obj.UrlName = obj.UrlName.Trim(); + + return _commandDispatcher.Execute(new PlayerSaveCommand + { + Model = obj + }); + } + + [HttpGet("api/admin/player/next-id")] + public Task NextId() + { + return _queryDispatcher.Execute(new PlayerNextIdQuery()); + } +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminReplyController.cs b/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminReplyController.cs new file mode 100644 index 0000000..dbb897f --- /dev/null +++ b/src/Backend/Geen.Web/Controllers/Areas/Admin/AdminReplyController.cs @@ -0,0 +1,68 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Geen.Core.Domains.Replies; +using Geen.Core.Domains.Replies.Commands; +using Geen.Core.Domains.Replies.Queries; +using Geen.Core.Interfaces.Common; +using Geen.Web.Application.Attributes; +using Geen.Web.Application.Authentication.Filters; +using Geen.Web.Application.Models; +using Microsoft.AspNetCore.Mvc; + +namespace Geen.Web.Controllers.Areas.Admin; + +[AuthenticationFilter] +public class AdminReplyController : Controller +{ + private readonly ICommandDispatcher _commandDispatcher; + private readonly IQueryDispatcher _queryDispatcher; + + public AdminReplyController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher) + { + _queryDispatcher = queryDispatcher; + _commandDispatcher = commandDispatcher; + } + + [HttpGet("api/admin/reply", Name = "unapproved")] + public Task> UnapprovedList([FromJsonUri] GetReplyUnapprovedListQuery query) + { + return _queryDispatcher.Execute(query); + } + + [HttpPatch("api/admin/reply/approve", Name = "approveReply")] + public Task Approve(string id) + { + return _commandDispatcher.Execute(new ReplyApproveCommand + { + Id = id + }); + } + + [HttpPatch("api/admin/reply/disapprove", Name = "disapproveReply")] + public Task Disapprove(string id) + { + return _commandDispatcher.Execute(new ReplyDisapproveCommand + { + Id = id + }); + } + + [HttpPut("api/admin/reply/text")] + public Task ChangeText(string id, [FromBody] BodyText text) + { + return _commandDispatcher.Execute(new ReplyChangeTextCommand + { + Id = id, + Text = text.Text + }); + } + + [HttpDelete("api/admin/reply/{id}", Name = "removeReply")] + public Task Remove(string id) + { + return _commandDispatcher.Execute(new ReplyRemoveCommand + { + ReplyId = id + }); + } +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/AuthenticationController.cs b/src/Backend/Geen.Web/Controllers/AuthenticationController.cs index f4d7f39..83a730b 100644 --- a/src/Backend/Geen.Web/Controllers/AuthenticationController.cs +++ b/src/Backend/Geen.Web/Controllers/AuthenticationController.cs @@ -1,45 +1,44 @@ -using Geen.Data.Settings; +using System; +using System.Threading.Tasks; +using Geen.Data.Settings; using Geen.Web.Application.Authentication.Extensions; using Geen.Web.Application.Authentication.Model; +using Geen.Web.Application.Authentication.Services; +using Geen.Web.Application.Constants; using Geen.Web.Application.Filters.Throttling; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; -using System; -using System.Threading.Tasks; -using Geen.Web.Application.Constants; -using Microsoft.AspNetCore.Http; -using AuthenticationService = Geen.Web.Application.Authentication.Services.AuthenticationService; -namespace Geen.Web.Controllers +namespace Geen.Web.Controllers; + +public class AuthenticationController : Controller { - public class AuthenticationController : Controller + private readonly AuthenticationService _authenticationService; + private readonly GeenSettings _geenSettings; + + public AuthenticationController(IOptions geenSettings, AuthenticationService authenticationService) { - private readonly AuthenticationService _authenticationService; - private readonly GeenSettings _geenSettings; + _geenSettings = geenSettings.Value; + _authenticationService = authenticationService; + } - public AuthenticationController(IOptions geenSettings, AuthenticationService authenticationService) - { - _geenSettings = geenSettings.Value; - _authenticationService = authenticationService; - } + [HttpPost("/api/authentication/login")] + [ThrottleFilter(0, 0, 5, 0)] + public async Task Login([FromBody] LoginModel model) + { + await Task.Delay(1000); - [HttpPost("/api/authentication/login")] - [ThrottleFilter(0, 0, 5, 0)] - public async Task Login([FromBody]LoginModel model) + if (model.IsSuccessAdminLogin(_geenSettings)) { - await Task.Delay(1000); - - if (model.IsSuccessAdminLogin(_geenSettings)) - { - var token = _authenticationService.CreateToken(model); - - Response.Cookies.Append(CookieConstants.AdministratorCookieName, token, new CookieOptions - { - Expires = DateTime.Now.AddYears(5) - }); - } + var token = _authenticationService.CreateToken(model); - return null; + Response.Cookies.Append(CookieConstants.AdministratorCookieName, token, new CookieOptions + { + Expires = DateTime.Now.AddYears(5) + }); } + + return null; } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/ClubController.cs b/src/Backend/Geen.Web/Controllers/ClubController.cs index 7e9bfa9..61cb619 100644 --- a/src/Backend/Geen.Web/Controllers/ClubController.cs +++ b/src/Backend/Geen.Web/Controllers/ClubController.cs @@ -6,48 +6,47 @@ using Geen.Core.Interfaces.Common; using Microsoft.AspNetCore.Mvc; -namespace Geen.Web.Controllers +namespace Geen.Web.Controllers; + +public class ClubController : Controller { - public class ClubController : Controller + private readonly IQueryDispatcher _queryDispatcher; + + public ClubController(IQueryDispatcher queryDispatcher) { - private readonly IQueryDispatcher _queryDispatcher; + _queryDispatcher = queryDispatcher; + } - public ClubController(IQueryDispatcher queryDispatcher) - { - _queryDispatcher = queryDispatcher; - } + [HttpGet("/api/club/list")] + public Task> Get() + { + return _queryDispatcher.Execute(new ClubGetListQuery()); + } - [HttpGet("/api/club/list")] - public Task> Get() + [HttpGet("/api/club/{urlName}")] + public Task Get(string urlName) + { + return _queryDispatcher.Execute(new ClubGetByUrlNameQuery { - return _queryDispatcher.Execute(new ClubGetListQuery()); - } + UrlName = urlName + }); + } - [HttpGet("/api/club/{urlName}")] - public Task Get(string urlName) - { - return _queryDispatcher.Execute(new ClubGetByUrlNameQuery - { - UrlName = urlName - }); - } - - [HttpGet("/api/club/{urlName}/coach")] - public Task Coach(string urlName) + [HttpGet("/api/club/{urlName}/coach")] + public Task Coach(string urlName) + { + return _queryDispatcher.Execute(new ClubGetCoachQuery { - return _queryDispatcher.Execute(new ClubGetCoachQuery - { - ClubUrlName = urlName - }); - } + ClubUrlName = urlName + }); + } - [HttpGet("/api/club/{urlName}/age/average")] - public Task GetAverageAge(string urlName) + [HttpGet("/api/club/{urlName}/age/average")] + public Task GetAverageAge(string urlName) + { + return _queryDispatcher.Execute(new ClubGetAverageAgeQuery { - return _queryDispatcher.Execute(new ClubGetAverageAgeQuery - { - UrlName = urlName - }); - } + UrlName = urlName + }); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/ErrorController.cs b/src/Backend/Geen.Web/Controllers/ErrorController.cs index 58df442..8724ef2 100644 --- a/src/Backend/Geen.Web/Controllers/ErrorController.cs +++ b/src/Backend/Geen.Web/Controllers/ErrorController.cs @@ -3,25 +3,24 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; -namespace Geen.Web.Controllers +namespace Geen.Web.Controllers; + +public class ErrorController : Controller { - public class ErrorController : Controller + private readonly ILogger _logger; + + public ErrorController(ILogger logger) { - private readonly ILogger _logger; + _logger = logger; + } - public ErrorController(ILogger logger) - { - _logger = logger; - } + [HttpPost("/api/error")] + public async Task LogBrowserError() + { + var requestBody = new StreamReader(Request.Body); - [HttpPost("/api/error")] - public async Task LogBrowserError() - { - var requestBody = new StreamReader(Request.Body); - - _logger.LogError("BROWSER, Agent={Agent}, ErrorMessage: {ErrorMessage}", - Request.Headers["User-Agent"].ToString(), - await requestBody.ReadToEndAsync()); - } + _logger.LogError("BROWSER, Agent={Agent}, ErrorMessage: {ErrorMessage}", + Request.Headers["User-Agent"].ToString(), + await requestBody.ReadToEndAsync()); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/LeagueController.cs b/src/Backend/Geen.Web/Controllers/LeagueController.cs index 7766af4..c4b6071 100644 --- a/src/Backend/Geen.Web/Controllers/LeagueController.cs +++ b/src/Backend/Geen.Web/Controllers/LeagueController.cs @@ -5,21 +5,20 @@ using Geen.Core.Interfaces.Common; using Microsoft.AspNetCore.Mvc; -namespace Geen.Web.Controllers +namespace Geen.Web.Controllers; + +public class LeagueController : Controller { - public class LeagueController : Controller - { - private readonly IQueryDispatcher _queryDispatcher; + private readonly IQueryDispatcher _queryDispatcher; - public LeagueController(IQueryDispatcher queryDispatcher) - { - _queryDispatcher = queryDispatcher; - } + public LeagueController(IQueryDispatcher queryDispatcher) + { + _queryDispatcher = queryDispatcher; + } - [HttpGet("/api/league/list")] - public Task> Get() - { - return _queryDispatcher.Execute(new LeagueGetListQuery()); - } + [HttpGet("/api/league/list")] + public Task> Get() + { + return _queryDispatcher.Execute(new LeagueGetListQuery()); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/MentionController.cs b/src/Backend/Geen.Web/Controllers/MentionController.cs index 231a7d3..e9f8fa9 100644 --- a/src/Backend/Geen.Web/Controllers/MentionController.cs +++ b/src/Backend/Geen.Web/Controllers/MentionController.cs @@ -1,120 +1,119 @@ -using Geen.Core.Interfaces.Common; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Geen.Core.Domains.Mentions; +using Geen.Core.Domains.Mentions.Commands; +using Geen.Core.Domains.Mentions.Queries; +using Geen.Core.Interfaces.Common; using Geen.Core.Models.Likes; using Geen.Web.Application.Attributes; using Geen.Web.Application.Authentication.Services; using Geen.Web.Application.Filters.Throttling; using Geen.Web.Application.Models; using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Geen.Core.Domains.Mentions; -using Geen.Core.Domains.Mentions.Commands; -using Geen.Core.Domains.Mentions.Queries; -namespace Geen.Web.Controllers +namespace Geen.Web.Controllers; + +public class MentionController : Controller { - public class MentionController : Controller - { - private readonly IQueryDispatcher _queryDispatcher; - private readonly ICommandDispatcher _commandDispatcher; + private readonly ICommandDispatcher _commandDispatcher; + private readonly IQueryDispatcher _queryDispatcher; - private readonly UserService _userService; + private readonly UserService _userService; - public MentionController(IQueryDispatcher queryDispatcher, - UserService userService, - ICommandDispatcher commandDispatcher) - { - _userService = userService; - _commandDispatcher = commandDispatcher; - _queryDispatcher = queryDispatcher; - } + public MentionController(IQueryDispatcher queryDispatcher, + UserService userService, + ICommandDispatcher commandDispatcher) + { + _userService = userService; + _commandDispatcher = commandDispatcher; + _queryDispatcher = queryDispatcher; + } - [HttpGet("/api/mention/{urlName}/{id:long}", Name = "getMention")] - public async Task Get(string urlName, long id) + [HttpGet("/api/mention/{urlName}/{id:long}", Name = "getMention")] + public async Task Get(string urlName, long id) + { + var result = await _queryDispatcher.Execute(new GetMentionByIdQuery { - var result = await _queryDispatcher.Execute(new GetMentionByIdQuery - { - Id = id - }); - - if (result == null || !result.ContainsUrlName(urlName)) - return null; - - return result; - } - - [HttpGet("/api/mention/list", Name = "getMentionList")] - public Task> GetList([FromJsonUri]GetMentionListQuery query) + Id = id + }); + + if (result == null || !result.ContainsUrlName(urlName)) + return null; + + return result; + } + + [HttpGet("/api/mention/list", Name = "getMentionList")] + public Task> GetList([FromJsonUri] GetMentionListQuery query) + { + query.IsApproved = true; + + return _queryDispatcher.Execute(query); + } + + [HttpGet("/api/mention/fresh/{unixtime:long}", Name = "fresh")] + public Task> GetList(long unixtime) + { + return _queryDispatcher.Execute(new GetFreshMentionsQuery { - query.IsApproved = true; - - return _queryDispatcher.Execute(query); - } + DateStart = DateTimeOffset.FromUnixTimeSeconds(unixtime).DateTime + }); + } + + [HttpPost("/api/mention/create", Name = "create")] + [ThrottleFilter(0, 0, 3, 0)] + public async Task Create([FromBody] MentionCreateDto request) + { + if (string.IsNullOrWhiteSpace(request.Text)) + return null; - [HttpGet("/api/mention/fresh/{unixtime:long}", Name = "fresh")] - public Task> GetList(long unixtime) + var result = await _commandDispatcher.Execute(new MentionCreateCommand { - return _queryDispatcher.Execute(new GetFreshMentionsQuery - { - DateStart = DateTimeOffset.FromUnixTimeSeconds(unixtime).DateTime - }); - } - - [HttpPost("/api/mention/create", Name = "create")] - [ThrottleFilter(0, 0, 3, 0)] - public async Task Create([FromBody]MentionCreateDto request) - { - if (string.IsNullOrWhiteSpace(request.Text)) - return null; - - var result = await _commandDispatcher.Execute(new MentionCreateCommand - { - Model = request.ToModel(), - User = _userService.GetCurrentUser() - }); - - return result; - } - - [HttpPost("/api/mention/like")] - //[ThrottleFilter(0, 0, 1, 0)] - public async Task Like(long id) + Model = request.ToModel(), + User = _userService.GetCurrentUser() + }); + + return result; + } + + [HttpPost("/api/mention/like")] + //[ThrottleFilter(0, 0, 1, 0)] + public async Task Like(long id) + { + await _commandDispatcher.Execute(new MentionLikeCommand { - await _commandDispatcher.Execute(new MentionLikeCommand - { - Id = id, - UserId = _userService.GetCurrentUser().Id - }); - - return await _queryDispatcher.Execute(new GetMentionLikeStatus { Id = id }); - } - - [HttpPost("/api/mention/dislike")] - //[ThrottleFilter(0, 0, 1, 0)] - public async Task Dislike(long id) + Id = id, + UserId = _userService.GetCurrentUser().Id + }); + + return await _queryDispatcher.Execute(new GetMentionLikeStatus { Id = id }); + } + + [HttpPost("/api/mention/dislike")] + //[ThrottleFilter(0, 0, 1, 0)] + public async Task Dislike(long id) + { + await _commandDispatcher.Execute(new MentionDislikeCommand { - await _commandDispatcher.Execute(new MentionDislikeCommand - { - Id = id, - UserId = _userService.GetCurrentUser().Id - }); + Id = id, + UserId = _userService.GetCurrentUser().Id + }); - return await _queryDispatcher.Execute(new GetMentionLikeStatus { Id = id }); - } + return await _queryDispatcher.Execute(new GetMentionLikeStatus { Id = id }); + } - [HttpGet("/api/mention/init")] - public Task Init() + [HttpGet("/api/mention/init")] + public Task Init() + { + var cmd = new MentionRandomLikerCommand { - var cmd = new MentionRandomLikerCommand - { - Count = 5, - DaysInteval = 20, - MaxLikes = 15, - MaxDislikes = 7 - }; - - return Task.WhenAll(_commandDispatcher.Execute(cmd)); - } + Count = 5, + DaysInteval = 20, + MaxLikes = 15, + MaxDislikes = 7 + }; + + return Task.WhenAll(_commandDispatcher.Execute(cmd)); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/PlayerController.cs b/src/Backend/Geen.Web/Controllers/PlayerController.cs index 9485c31..46b95d5 100644 --- a/src/Backend/Geen.Web/Controllers/PlayerController.cs +++ b/src/Backend/Geen.Web/Controllers/PlayerController.cs @@ -5,69 +5,68 @@ using Geen.Core.Interfaces.Common; using Microsoft.AspNetCore.Mvc; -namespace Geen.Web.Controllers +namespace Geen.Web.Controllers; + +public class PlayerController : Controller { - public class PlayerController : Controller + private readonly IQueryDispatcher _queryDispatcher; + + public PlayerController(IQueryDispatcher queryDispatcher) { - private readonly IQueryDispatcher _queryDispatcher; + _queryDispatcher = queryDispatcher; + } - public PlayerController(IQueryDispatcher queryDispatcher) - { - _queryDispatcher = queryDispatcher; - } + [HttpGet("/api/player/{urlName}", Name = "playerGet")] + public Task Get(string urlName) + { + return _queryDispatcher.Execute(new PlayerGetByUrlName { UrlName = urlName }); + } - [HttpGet("/api/player/{urlName}", Name = "playerGet")] - public Task Get(string urlName) + [HttpGet("/api/players/club/{urlName}", Name = "clubPlayersGet")] + public Task> GetFromClub(string urlName) + { + return _queryDispatcher.Execute(new PlayerGetByClubUrlNameQuery { - return _queryDispatcher.Execute(new PlayerGetByUrlName { UrlName = urlName }); - } + ClubUrlName = urlName + }); + } - [HttpGet("/api/players/club/{urlName}", Name = "clubPlayersGet")] - public Task> GetFromClub(string urlName) + [HttpGet("/api/players/club/{clubUrlName}/top", Name = "topClubPlayers")] + public Task> GetTopPlayers(string clubUrlName) + { + return _queryDispatcher.Execute(new GetTopPlayerQuery { - return _queryDispatcher.Execute(new PlayerGetByClubUrlNameQuery - { - ClubUrlName = urlName - }); - } + ClubUrlName = clubUrlName + }); + } - [HttpGet("/api/players/club/{clubUrlName}/top", Name = "topClubPlayers")] - public Task> GetTopPlayers(string clubUrlName) + [HttpGet("/api/players/search/{query}")] + public Task> SearchPlayers(string query) + { + return _queryDispatcher.Execute(new SearchPlayerQuery { - return _queryDispatcher.Execute(new GetTopPlayerQuery - { - ClubUrlName = clubUrlName - }); - } + Query = query + }); + } - [HttpGet("/api/players/search/{query}")] - public Task> SearchPlayers(string query) - { - return _queryDispatcher.Execute(new SearchPlayerQuery - { - Query = query - }); - } - - [HttpGet("/api/players/top", Name = "topPlayers")] - public Task> GetTopPlayers() - { - return _queryDispatcher.Execute(new GetTopPlayerQuery()); - } + [HttpGet("/api/players/top", Name = "topPlayers")] + public Task> GetTopPlayers() + { + return _queryDispatcher.Execute(new GetTopPlayerQuery()); + } - [HttpGet("/api/player/{urlName}/related")] - public Task> GetRelatedPlayers(string urlName) + [HttpGet("/api/player/{urlName}/related")] + public Task> GetRelatedPlayers(string urlName) + { + return _queryDispatcher.Execute(new GetRelatedPlayerQuery { - return _queryDispatcher.Execute(new GetRelatedPlayerQuery - { - UrlName = urlName - }); - } + UrlName = urlName + }); + } - [HttpGet("/api/player/random")] - public Task GetRandomPlayer() - { - return _queryDispatcher.Execute(new GetRandomPlayerQuery()); - } + [HttpGet("/api/player/random")] + public Task GetRandomPlayer() + { + return _queryDispatcher.Execute(new GetRandomPlayerQuery()); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/ReplyController.cs b/src/Backend/Geen.Web/Controllers/ReplyController.cs index b24f454..78d80a8 100644 --- a/src/Backend/Geen.Web/Controllers/ReplyController.cs +++ b/src/Backend/Geen.Web/Controllers/ReplyController.cs @@ -10,48 +10,47 @@ using Geen.Web.Application.Models; using Microsoft.AspNetCore.Mvc; -namespace Geen.Web.Controllers +namespace Geen.Web.Controllers; + +public class ReplyController : Controller { - public class ReplyController : Controller - { - private readonly IQueryDispatcher _queryDispatcher; - private readonly ICommandDispatcher _commandDispatcher; + private readonly ICommandDispatcher _commandDispatcher; + private readonly IQueryDispatcher _queryDispatcher; - private readonly UserService _userService; + private readonly UserService _userService; - public ReplyController(UserService userService, - IQueryDispatcher queryDispatcher, - ICommandDispatcher commandDispatcher) - { - _userService = userService; - _queryDispatcher = queryDispatcher; - _commandDispatcher = commandDispatcher; - } + public ReplyController(UserService userService, + IQueryDispatcher queryDispatcher, + ICommandDispatcher commandDispatcher) + { + _userService = userService; + _queryDispatcher = queryDispatcher; + _commandDispatcher = commandDispatcher; + } - [HttpGet("/api/reply")] - public Task> GetList([FromJsonUri] GetReplyListQuery query) - { - return _queryDispatcher.Execute(query); - } + [HttpGet("/api/reply")] + public Task> GetList([FromJsonUri] GetReplyListQuery query) + { + return _queryDispatcher.Execute(query); + } - [HttpGet("/api/reply/latest")] - public Task> GetLatest([FromJsonUri] GetReplyLatestQuery query) - { - return _queryDispatcher.Execute(query); - } + [HttpGet("/api/reply/latest")] + public Task> GetLatest([FromJsonUri] GetReplyLatestQuery query) + { + return _queryDispatcher.Execute(query); + } + + [HttpPost("/api/reply/create", Name = "createReply")] + [ThrottleFilter(0, 0, 3, 0)] + public async Task Create([FromBody] ReplyCreateDto request) + { + if (string.IsNullOrWhiteSpace(request.Text)) + return null; - [HttpPost("/api/reply/create", Name = "createReply")] - [ThrottleFilter(0, 0, 3, 0)] - public async Task Create([FromBody] ReplyCreateDto request) + return await _commandDispatcher.Execute(new ReplyCreateCommand { - if (string.IsNullOrWhiteSpace(request.Text)) - return null; - - return await _commandDispatcher.Execute(new ReplyCreateCommand - { - Model = request.ToModel(), - User = _userService.GetCurrentUser() - }); - } + Model = request.ToModel(), + User = _userService.GetCurrentUser() + }); } } \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/SearchController.cs b/src/Backend/Geen.Web/Controllers/SearchController.cs index b8bdb01..5d0431d 100644 --- a/src/Backend/Geen.Web/Controllers/SearchController.cs +++ b/src/Backend/Geen.Web/Controllers/SearchController.cs @@ -5,25 +5,24 @@ using Geen.Core.Interfaces.Common; using Microsoft.AspNetCore.Mvc; -namespace Geen.Web.Controllers +namespace Geen.Web.Controllers; + +public class SearchController : Controller { - public class SearchController : Controller - { - private readonly IQueryDispatcher _queryDispatcher; + private readonly IQueryDispatcher _queryDispatcher; - public SearchController(IQueryDispatcher queryDispatcher) - { - _queryDispatcher = queryDispatcher; - } + public SearchController(IQueryDispatcher queryDispatcher) + { + _queryDispatcher = queryDispatcher; + } - [HttpGet("/api/search/{query}")] - public Task> Get(string query) + [HttpGet("/api/search/{query}")] + public Task> Get(string query) + { + return _queryDispatcher.Execute(new SearchQuery { - return _queryDispatcher.Execute(new SearchQuery - { - Query = query, - Count = 100 - }); - } + Query = query, + Count = 100 + }); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Controllers/VoteController.cs b/src/Backend/Geen.Web/Controllers/VoteController.cs index 59c4fc3..883c056 100644 --- a/src/Backend/Geen.Web/Controllers/VoteController.cs +++ b/src/Backend/Geen.Web/Controllers/VoteController.cs @@ -5,29 +5,28 @@ using Geen.Core.Interfaces.Common; using Microsoft.AspNetCore.Mvc; -namespace Geen.Web.Controllers +namespace Geen.Web.Controllers; + +public class VotingController : Controller { - public class VotingController : Controller + private readonly ICommandDispatcher _commandDispatcher; + private readonly IQueryDispatcher _queryDispatcher; + + public VotingController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher) { - private readonly IQueryDispatcher _queryDispatcher; - private readonly ICommandDispatcher _commandDispatcher; + _queryDispatcher = queryDispatcher; + _commandDispatcher = commandDispatcher; + } - public VotingController(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher) - { - _queryDispatcher = queryDispatcher; - _commandDispatcher = commandDispatcher; - } + [HttpGet("/api/votes")] + public Task GetClubVotingModel() + { + return _queryDispatcher.Execute(new GetVoteDataQuery()); + } - [HttpGet("/api/votes")] - public Task GetClubVotingModel() - { - return _queryDispatcher.Execute(new GetVoteDataQuery()); - } - - [HttpPost("/api/vote")] - public Task Vote([FromBody]CreateVoteCommand command) - { - return _commandDispatcher.Execute(command); - } + [HttpPost("/api/vote")] + public Task Vote([FromBody] CreateVoteCommand command) + { + return _commandDispatcher.Execute(command); } -} +} \ No newline at end of file diff --git a/src/Backend/Geen.Web/Geen.Web.csproj b/src/Backend/Geen.Web/Geen.Web.csproj index bf3bc98..67c4d2f 100644 --- a/src/Backend/Geen.Web/Geen.Web.csproj +++ b/src/Backend/Geen.Web/Geen.Web.csproj @@ -1,17 +1,18 @@  - - net7.0 - - - - - - - - - - - - - + + net7.0 + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Backend/Geen.Web/Program.cs b/src/Backend/Geen.Web/Program.cs index 8188e2c..c701a80 100644 --- a/src/Backend/Geen.Web/Program.cs +++ b/src/Backend/Geen.Web/Program.cs @@ -2,31 +2,30 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -namespace Geen.Web +namespace Geen.Web; + +public class Program { - public class Program + public static void Main(string[] args) { - public static void Main(string[] args) - { - BuildWebHost(args).Run(); - } + BuildWebHost(args).Run(); + } - private static IHost BuildWebHost(string[] args) - { - return Host.CreateDefaultBuilder(args) - .ConfigureLogging(builder => - { - builder.ClearProviders() - .AddFilter("Microsoft", LogLevel.Error) - .AddFilter("System", LogLevel.Error) - .AddConsole(); - }) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.ConfigureKestrel(options => { }) - .UseUrls("http://*:7000") - .UseStartup(); - }).Build(); - } + private static IHost BuildWebHost(string[] args) + { + return Host.CreateDefaultBuilder(args) + .ConfigureLogging(builder => + { + builder.ClearProviders() + .AddFilter("Microsoft", LogLevel.Error) + .AddFilter("System", LogLevel.Error) + .AddConsole(); + }) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.ConfigureKestrel(options => { }) + .UseUrls("http://*:7000") + .UseStartup(); + }).Build(); } } \ No newline at end of file diff --git a/src/Backend/Geen.Web/Properties/launchSettings.json b/src/Backend/Geen.Web/Properties/launchSettings.json index 287e0a3..daf3e8e 100644 --- a/src/Backend/Geen.Web/Properties/launchSettings.json +++ b/src/Backend/Geen.Web/Properties/launchSettings.json @@ -1,4 +1,4 @@ -{ +{ "profiles": { "Geen.Web": { "commandName": "Project", diff --git a/src/Backend/Geen.Web/Startup.cs b/src/Backend/Geen.Web/Startup.cs index dba8256..236f73d 100644 --- a/src/Backend/Geen.Web/Startup.cs +++ b/src/Backend/Geen.Web/Startup.cs @@ -8,108 +8,107 @@ using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; -namespace Geen.Web +namespace Geen.Web; + +public class Startup { - public class Startup + public Startup(IConfiguration configuration) { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } + Configuration = configuration; + } - private IConfiguration Configuration { get; } + private IConfiguration Configuration { get; } - public void ConfigureServices(IServiceCollection services) - { - var settings = services.RegisterInternalServices(Configuration); + public void ConfigureServices(IServiceCollection services) + { + var settings = services.RegisterInternalServices(Configuration); - services.Configure( - options => options.Level = CompressionLevel.Fastest); + services.Configure( + options => options.Level = CompressionLevel.Fastest); - services.AddResponseCompression(options => - { - options.Providers.Add(); - options.MimeTypes = new[] - { - // Default - "text/plain", - "text/css", - "application/javascript", - "text/html", - "application/xml", - "text/xml", - "application/json", - "text/json", - // Custom - "image/svg+xml", - "font/woff2", - "application/x-font-ttf" - }; - }); - - services.AddCors(options => + services.AddResponseCompression(options => + { + options.Providers.Add(); + options.MimeTypes = new[] { - options.AddPolicy("AllowAnyOrigin", - builder => builder - .AllowAnyOrigin() - .AllowAnyMethod() - .AllowAnyHeader()); - }); + // Default + "text/plain", + "text/css", + "application/javascript", + "text/html", + "application/xml", + "text/xml", + "application/json", + "text/json", + // Custom + "image/svg+xml", + "font/woff2", + "application/x-font-ttf" + }; + }); - services.AddControllers(); + services.AddCors(options => + { + options.AddPolicy("AllowAnyOrigin", + builder => builder + .AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader()); + }); + + services.AddControllers(); - services.AddSwaggerGen(c => + services.AddSwaggerGen(c => + { + c.SwaggerDoc("v1", new OpenApiInfo { - c.SwaggerDoc("v1", new OpenApiInfo - { - Title = "GeenApi", Version = "v1" - }); + Title = "GeenApi", Version = "v1" }); - } + }); + } - public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) - { - app.UseCors("AllowAnyOrigin"); + public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) + { + app.UseCors("AllowAnyOrigin"); - app.UseResponseCompression(); - - app.UseFallbackRedirects(); - - app.UseStaticFiles(new StaticFileOptions + app.UseResponseCompression(); + + app.UseFallbackRedirects(); + + app.UseStaticFiles(new StaticFileOptions + { + OnPrepareResponse = context => { - OnPrepareResponse = context => - { - context.Context.Response.Headers.Add("cache-control", new[] {"public,max-age=31536000"}); - context.Context.Response.Headers.Add("Expires", new[] {DateTime.UtcNow.AddYears(1).ToString("R")}); - } - }); + context.Context.Response.Headers.Add("cache-control", new[] { "public,max-age=31536000" }); + context.Context.Response.Headers.Add("Expires", new[] { DateTime.UtcNow.AddYears(1).ToString("R") }); + } + }); - app.UseSitemap(); + app.UseSitemap(); #if DEBUG - app.UseSwagger(); - app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); + app.UseSwagger(); + app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); #endif - app.UseStaticFiles(new StaticFileOptions + app.UseStaticFiles(new StaticFileOptions + { + OnPrepareResponse = context => { - OnPrepareResponse = context => - { - context.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store"); - context.Context.Response.Headers.Add("Expires", "-1"); - } - }); + context.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store"); + context.Context.Response.Headers.Add("Expires", "-1"); + } + }); - app.UserAnonymous(); + app.UserAnonymous(); - app.UseRouting(); - app.UseEndpoints(routes => - { - routes.MapAreaControllerRoute("areaRoute", "Admin", "api/{area:exists}/{controller}/{action}/{id?}"); - routes.MapControllerRoute("default","{controller=Home}/{action=Index}/{id?}"); + app.UseRouting(); + app.UseEndpoints(routes => + { + routes.MapAreaControllerRoute("areaRoute", "Admin", "api/{area:exists}/{controller}/{action}/{id?}"); + routes.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); - routes.MapFallbackToFile("index.html"); - }); - } + routes.MapFallbackToFile("index.html"); + }); } } \ No newline at end of file diff --git a/src/Backend/Geen.Web/appsettings.Development.json b/src/Backend/Geen.Web/appsettings.Development.json index 453df2b..82cb3db 100644 --- a/src/Backend/Geen.Web/appsettings.Development.json +++ b/src/Backend/Geen.Web/appsettings.Development.json @@ -22,5 +22,5 @@ "Default": "Information", "Microsoft": "Error" } - } + } } diff --git a/src/Backend/Geen.Web/appsettings.json b/src/Backend/Geen.Web/appsettings.json index cabc7ae..0515677 100644 --- a/src/Backend/Geen.Web/appsettings.json +++ b/src/Backend/Geen.Web/appsettings.json @@ -22,5 +22,5 @@ "Default": "Information", "Microsoft": "Error" } - } + } } diff --git a/src/Backend/Geen.sln.DotSettings b/src/Backend/Geen.sln.DotSettings new file mode 100644 index 0000000..aff3e14 --- /dev/null +++ b/src/Backend/Geen.sln.DotSettings @@ -0,0 +1,2 @@ + + True \ No newline at end of file diff --git a/src/Backend/Shared/Geen.ClientGenerator/Geen.ClientGenerator.csproj b/src/Backend/Shared/Geen.ClientGenerator/Geen.ClientGenerator.csproj index 75cd042..602bbda 100644 --- a/src/Backend/Shared/Geen.ClientGenerator/Geen.ClientGenerator.csproj +++ b/src/Backend/Shared/Geen.ClientGenerator/Geen.ClientGenerator.csproj @@ -8,8 +8,8 @@ - - + + - + diff --git a/src/Backend/Shared/Geen.ClientGenerator/Program.cs b/src/Backend/Shared/Geen.ClientGenerator/Program.cs index 207f5c8..5d87edd 100644 --- a/src/Backend/Shared/Geen.ClientGenerator/Program.cs +++ b/src/Backend/Shared/Geen.ClientGenerator/Program.cs @@ -27,12 +27,9 @@ var generator = new TypeScriptClientGenerator(await OpenApiDocument.FromUrlAsync(geenSwaggerUrl), settings); var code = generator.GenerateFile(); -string outFile = "../../../../../../Frontend/src/client/apiClient.ts"; +var outFile = "../../../../../../Frontend/src/client/apiClient.ts"; -if (File.Exists(outFile)) -{ - File.Delete(outFile); -} +if (File.Exists(outFile)) File.Delete(outFile); Directory.CreateDirectory(Path.GetDirectoryName(outFile));