From 77a3417de131dab3c180c75dc80f79042d147fd4 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Sun, 21 Nov 2021 23:28:39 +0300 Subject: [PATCH 01/19] add some telegramBot --- .../ApplicationProfile.cs | 2 +- .../Controllers/AccountController.cs | 6 +- .../Models/IdentityContext.cs | 2 +- .../HwProj.AuthService.API/RoleInitializer.cs | 4 +- .../Services/AccountService.cs | 28 +- .../Services/AuthTokenService.cs | 14 +- .../Services/IAuthTokenService.cs | 2 +- .../Services/IUserManager.cs | 24 +- .../Services/ProxyUserManager.cs | 46 +- .../HwProj.AuthService.API/Startup.cs | 6 +- .../AuthServiceClient.cs | 2 +- .../ViewModels/{User.cs => UserViewModel.cs} | 4 +- .../Controllers/HomeworksController.cs | 17 +- .../Services/HomeworksService.cs | 5 + .../Services/IHomeworksService.cs | 2 + .../CoursesServiceClient.cs | 9 + .../ICoursesServiceClient.cs | 1 + .../ConfirmTelegramBotEventHandler.cs | 32 + .../HwProj.NotificationsService.API.csproj | 2 + .../Startup.cs | 4 + .../ConfigurationExtensions.cs | 17 + .../ITelegramBotClient.cs | 7 + .../TelegramBotClient.cs | 17 + .../HwProj.TelegramBotAPI/.dockerignore | 25 + .../Commands/CommandNames.cs | 9 + .../Commands/Commands.cs | 12 + .../Commands/GetCourses.cs | 56 + .../Commands/GetHomeworks.cs | 58 + .../Commands/StartCommand.cs | 48 + .../Controllers/TelegramBotController.cs | 43 + .../HwProj.TelegramBotAPI/Dockerfile | 20 + .../Events/ConfirmTelegramBotEvent.cs | 12 + .../Models/TelegramBotContext.cs | 13 + .../Models/TelegramUserModel.cs | 15 + .../Repositories/ITelegramBotRepository.cs | 7 + .../Repositories/TelegramBotRepository.cs | 10 + .../Service/CommandService.cs | 63 + .../Service/ICommandService.cs | 10 + .../Service/IUserService.cs | 11 + .../Service/UserService.cs | 78 + HwProj.sln | 16 + hwproj.front/package-lock.json | 24 +- hwproj.front/package.json | 4 +- hwproj.front/src/api/api.ts | 1416 ++++++++--------- hwproj.front/src/components/Auth/Login.tsx | 2 +- hwproj.front/src/components/Profile.tsx | 22 +- .../src/components/Styles/telegram.css | 4 + 47 files changed, 1446 insertions(+), 785 deletions(-) rename HwProj.Common/HwProj.Models/AuthService/ViewModels/{User.cs => UserViewModel.cs} (82%) create mode 100644 HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBot.Client/ConfigurationExtensions.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBot.Client/ITelegramBotClient.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBot.Client/TelegramBotClient.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/.dockerignore create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/Commands.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetCourses.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetHomeworks.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/StartCommand.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Controllers/TelegramBotController.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Dockerfile create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Events/ConfirmTelegramBotEvent.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramBotContext.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramUserModel.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/ITelegramBotRepository.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/TelegramBotRepository.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/CommandService.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/ICommandService.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/IUserService.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/UserService.cs create mode 100644 hwproj.front/src/components/Styles/telegram.css diff --git a/HwProj.AuthService/HwProj.AuthService.API/ApplicationProfile.cs b/HwProj.AuthService/HwProj.AuthService.API/ApplicationProfile.cs index fd607c4a2..455c5bec5 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/ApplicationProfile.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/ApplicationProfile.cs @@ -8,7 +8,7 @@ public class ApplicationProfile : Profile { public ApplicationProfile() { - CreateMap(); + CreateMap(); CreateMap(); CreateMap(); CreateMap(); diff --git a/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs b/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs index f6efbce7c..68d938eb1 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs @@ -90,7 +90,7 @@ public async Task EditExternal([FromBody] EditExternalViewModel m [HttpGet("findByEmail/{email}")] - [ProducesResponseType(typeof(User), (int)HttpStatusCode.OK)] + [ProducesResponseType(typeof(UserViewModel), (int)HttpStatusCode.OK)] public async Task FindByEmail(string email) { var user = await _userManager.FindByEmailAsync(email); @@ -99,9 +99,9 @@ public async Task FindByEmail(string email) [HttpPost("getRole")] [ProducesResponseType(typeof(string), (int)HttpStatusCode.OK)] - public async Task GetRolesAsync([FromBody] User user) + public async Task GetRolesAsync([FromBody] UserViewModel userViewModel) { - var roles = await _userManager.GetRolesAsync(user); + var roles = await _userManager.GetRolesAsync(userViewModel); return Ok(roles[0]); } diff --git a/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs b/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs index 6f35c9636..8c9b76ecc 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs @@ -4,7 +4,7 @@ namespace HwProj.AuthService.API.Models { - public sealed class IdentityContext : IdentityDbContext + public sealed class IdentityContext : IdentityDbContext { public IdentityContext(DbContextOptions options) : base(options) diff --git a/HwProj.AuthService/HwProj.AuthService.API/RoleInitializer.cs b/HwProj.AuthService/HwProj.AuthService.API/RoleInitializer.cs index f3bcd0143..353cfc3d8 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/RoleInitializer.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/RoleInitializer.cs @@ -9,7 +9,7 @@ namespace HwProj.AuthService.API { public class RoleInitializer { - public static async Task InitializeAsync(UserManager userManager, RoleManager roleManager, IEventBus eventBus) + public static async Task InitializeAsync(UserManager userManager, RoleManager roleManager, IEventBus eventBus) { if(await roleManager.FindByNameAsync(Roles.LecturerRole) == null) { @@ -26,7 +26,7 @@ public static async Task InitializeAsync(UserManager userManager, RoleMana if (await userManager.FindByEmailAsync(email) == null) { - var admin = new User { + var admin = new UserViewModel { Email = email, Name = "Admin", UserName = "Admin" diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs index 1894069ca..739a9c5e4 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs @@ -17,13 +17,13 @@ namespace HwProj.AuthService.API.Services public class AccountService : IAccountService { private readonly IUserManager _userManager; - private readonly SignInManager _signInManager; + private readonly SignInManager _signInManager; private readonly IAuthTokenService _tokenService; private readonly IEventBus _eventBus; private readonly IMapper _mapper; public AccountService(IUserManager userManager, - SignInManager signInManager, + SignInManager signInManager, IAuthTokenService authTokenService, IEventBus eventBus, IMapper mapper) @@ -128,7 +128,7 @@ public async Task> RegisterUserAsync(RegisterDataDTO mo return Result.Failed("User exist"); } - var user = _mapper.Map(model); + var user = _mapper.Map(model); user.UserName = user.Email.Split('@')[0]; var createUserTask = model.IsExternalAuth @@ -191,40 +191,40 @@ public async Task GetAllStudents() .ToArray();; } - private Task ChangeUserNameTask(User user, EditDataDTO model) + private Task ChangeUserNameTask(UserViewModel userViewModel, EditDataDTO model) { if (!string.IsNullOrWhiteSpace(model.Name)) { - user.Name = model.Name; + userViewModel.Name = model.Name; } if (!string.IsNullOrWhiteSpace(model.Name)) { - user.Surname = model.Surname; + userViewModel.Surname = model.Surname; } if (!string.IsNullOrWhiteSpace(model.Name)) { - user.MiddleName = model.MiddleName; + userViewModel.MiddleName = model.MiddleName; } - return _userManager.UpdateAsync(user); + return _userManager.UpdateAsync(userViewModel); } - private Task ChangePasswordAsync(User user, EditDataDTO model) + private Task ChangePasswordAsync(UserViewModel userViewModel, EditDataDTO model) { return !string.IsNullOrWhiteSpace(model.NewPassword) - ? _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword) + ? _userManager.ChangePasswordAsync(userViewModel, model.CurrentPassword, model.NewPassword) : Task.FromResult(IdentityResult.Success); } - private async Task SignIn(User user, string password) + private async Task SignIn(UserViewModel userViewModel, string password) { - await _signInManager.PasswordSignInAsync(user, password, false, false) + await _signInManager.PasswordSignInAsync(userViewModel, password, false, false) .ConfigureAwait(false); } - private async Task> GetToken(User user) + private async Task> GetToken(UserViewModel userViewModel) { - return Result.Success(await _tokenService.GetTokenAsync(user).ConfigureAwait(false)); + return Result.Success(await _tokenService.GetTokenAsync(userViewModel).ConfigureAwait(false)); } } } diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/AuthTokenService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/AuthTokenService.cs index e457a6126..b7165b23d 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/AuthTokenService.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/AuthTokenService.cs @@ -15,21 +15,21 @@ namespace HwProj.AuthService.API.Services { public class AuthTokenService : IAuthTokenService { - private readonly UserManager _userManager; + private readonly UserManager _userManager; private readonly IConfigurationSection _configuration; - public AuthTokenService(UserManager userManager, IConfiguration configuration) + public AuthTokenService(UserManager userManager, IConfiguration configuration) { _userManager = userManager; _configuration = configuration.GetSection("AppSettings"); } - public async Task GetTokenAsync(User user) + public async Task GetTokenAsync(UserViewModel userViewModel) { var securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_configuration["SecurityKey"])); var timeNow = DateTime.UtcNow; - var userRoles = await _userManager.GetRolesAsync(user).ConfigureAwait(false); + var userRoles = await _userManager.GetRolesAsync(userViewModel).ConfigureAwait(false); var token = new JwtSecurityToken( issuer: _configuration["ApiName"], @@ -37,9 +37,9 @@ public async Task GetTokenAsync(User user) expires: timeNow.AddMinutes(int.Parse(_configuration["ExpireInForToken"])), claims: new[] { - new Claim("_userName", user.UserName), - new Claim("_id", user.Id), - new Claim(ClaimTypes.Email, user.Email), + new Claim("_userName", userViewModel.UserName), + new Claim("_id", userViewModel.Id), + new Claim(ClaimTypes.Email, userViewModel.Email), new Claim(ClaimTypes.Role, userRoles.FirstOrDefault() ?? Roles.StudentRole) }, signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)); diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/IAuthTokenService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/IAuthTokenService.cs index ee0caef99..e96832cd8 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/IAuthTokenService.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/IAuthTokenService.cs @@ -6,6 +6,6 @@ namespace HwProj.AuthService.API.Services { public interface IAuthTokenService { - Task GetTokenAsync(User user); + Task GetTokenAsync(UserViewModel userViewModel); } } diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs index 9ce9db520..09796d197 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs @@ -7,17 +7,17 @@ namespace HwProj.AuthService.API.Services { public interface IUserManager { - Task CreateAsync(User user); - Task CreateAsync(User user, string password); - Task FindByIdAsync(string id); - Task FindByEmailAsync(string email); - Task UpdateAsync(User user); - Task AddToRoleAsync(User user, string role); - Task RemoveFromRoleAsync(User user, string role); - Task> GetRolesAsync(User user); - Task IsEmailConfirmedAsync(User user); - Task CheckPasswordAsync(User user, string password); - Task ChangePasswordAsync(User user, string currentPassword, string newPassword); - Task> GetUsersInRoleAsync(string role); + Task CreateAsync(UserViewModel userViewModel); + Task CreateAsync(UserViewModel userViewModel, string password); + Task FindByIdAsync(string id); + Task FindByEmailAsync(string email); + Task UpdateAsync(UserViewModel userViewModel); + Task AddToRoleAsync(UserViewModel userViewModel, string role); + Task RemoveFromRoleAsync(UserViewModel userViewModel, string role); + Task> GetRolesAsync(UserViewModel userViewModel); + Task IsEmailConfirmedAsync(UserViewModel userViewModel); + Task CheckPasswordAsync(UserViewModel userViewModel, string password); + Task ChangePasswordAsync(UserViewModel userViewModel, string currentPassword, string newPassword); + Task> GetUsersInRoleAsync(string role); } } diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs index e583ce6b3..2fd66cfcd 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs @@ -9,69 +9,69 @@ namespace HwProj.AuthService.API.Services { public class ProxyUserManager : IUserManager { - private readonly UserManager _aspUserManager; + private readonly UserManager _aspUserManager; - public ProxyUserManager(UserManager aspUserManager) + public ProxyUserManager(UserManager aspUserManager) { _aspUserManager = aspUserManager; } - public Task CreateAsync(User user) + public Task CreateAsync(UserViewModel userViewModel) { - return _aspUserManager.CreateAsync(user); + return _aspUserManager.CreateAsync(userViewModel); } - public Task CreateAsync(User user, string password) + public Task CreateAsync(UserViewModel userViewModel, string password) { - return _aspUserManager.CreateAsync(user, password); + return _aspUserManager.CreateAsync(userViewModel, password); } - public Task FindByIdAsync(string id) + public Task FindByIdAsync(string id) { return _aspUserManager.FindByIdAsync(id); } - public Task FindByEmailAsync(string email) + public Task FindByEmailAsync(string email) { return _aspUserManager.FindByEmailAsync(email); } - public Task UpdateAsync(User user) + public Task UpdateAsync(UserViewModel userViewModel) { - return _aspUserManager.UpdateAsync(user); + return _aspUserManager.UpdateAsync(userViewModel); } - public Task AddToRoleAsync(User user, string role) + public Task AddToRoleAsync(UserViewModel userViewModel, string role) { - return _aspUserManager.AddToRoleAsync(user, role); + return _aspUserManager.AddToRoleAsync(userViewModel, role); } - public Task RemoveFromRoleAsync(User user, string role) + public Task RemoveFromRoleAsync(UserViewModel userViewModel, string role) { - return _aspUserManager.RemoveFromRoleAsync(user, role); + return _aspUserManager.RemoveFromRoleAsync(userViewModel, role); } - public Task> GetRolesAsync(User user) + public Task> GetRolesAsync(UserViewModel userViewModel) { - return _aspUserManager.GetRolesAsync(user); + return _aspUserManager.GetRolesAsync(userViewModel); } - public Task IsEmailConfirmedAsync(User user) + public Task IsEmailConfirmedAsync(UserViewModel userViewModel) { - return _aspUserManager.IsEmailConfirmedAsync(user); + return _aspUserManager.IsEmailConfirmedAsync(userViewModel); } - public Task CheckPasswordAsync(User user, string password) + public Task CheckPasswordAsync(UserViewModel userViewModel, string password) { - return _aspUserManager.CheckPasswordAsync(user, password); + return _aspUserManager.CheckPasswordAsync(userViewModel, password); } - public Task ChangePasswordAsync(User user, string currentPassword, string newPassword) + public Task ChangePasswordAsync(UserViewModel userViewModel, string currentPassword, string newPassword) { - return _aspUserManager.ChangePasswordAsync(user, currentPassword, newPassword); + return _aspUserManager.ChangePasswordAsync(userViewModel, currentPassword, newPassword); } - public Task> GetUsersInRoleAsync(string role) + public Task> GetUsersInRoleAsync(string role) { return _aspUserManager.GetUsersInRoleAsync(role); } diff --git a/HwProj.AuthService/HwProj.AuthService.API/Startup.cs b/HwProj.AuthService/HwProj.AuthService.API/Startup.cs index 8f6b34a20..ba0681602 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Startup.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Startup.cs @@ -63,7 +63,7 @@ public void ConfigureServices(IServiceCollection services) services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); - services.AddIdentity(opts => + services.AddIdentity(opts => { opts.User.RequireUniqueEmail = true; opts.Password.RequiredLength = 6; @@ -73,7 +73,7 @@ public void ConfigureServices(IServiceCollection services) opts.Password.RequireDigit = false; }) .AddEntityFrameworkStores() - .AddUserManager>() + .AddUserManager>() .AddRoleManager>() .AddDefaultTokenProviders(); @@ -90,7 +90,7 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env) using (var scope = app.ApplicationServices.CreateScope()) { - var userManager = scope.ServiceProvider.GetService(typeof(UserManager)) as UserManager; + var userManager = scope.ServiceProvider.GetService(typeof(UserManager)) as UserManager; var rolesManager = scope.ServiceProvider.GetService(typeof(RoleManager)) as RoleManager; var eventBus = scope.ServiceProvider.GetService(); diff --git a/HwProj.AuthService/HwProj.AuthService.Client/AuthServiceClient.cs b/HwProj.AuthService/HwProj.AuthService.Client/AuthServiceClient.cs index 1fc663fd4..d061ac3c5 100644 --- a/HwProj.AuthService/HwProj.AuthService.Client/AuthServiceClient.cs +++ b/HwProj.AuthService/HwProj.AuthService.Client/AuthServiceClient.cs @@ -133,7 +133,7 @@ public async Task FindByEmailAsync(string email) }; var response = await _httpClient.SendAsync(httpRequest); - var user = await response.DeserializeAsync(); + var user = await response.DeserializeAsync(); return user?.Id; } diff --git a/HwProj.Common/HwProj.Models/AuthService/ViewModels/User.cs b/HwProj.Common/HwProj.Models/AuthService/ViewModels/UserViewModel.cs similarity index 82% rename from HwProj.Common/HwProj.Models/AuthService/ViewModels/User.cs rename to HwProj.Common/HwProj.Models/AuthService/ViewModels/UserViewModel.cs index b2975e353..92ecd955d 100644 --- a/HwProj.Common/HwProj.Models/AuthService/ViewModels/User.cs +++ b/HwProj.Common/HwProj.Models/AuthService/ViewModels/UserViewModel.cs @@ -2,7 +2,7 @@ namespace HwProj.Models.AuthService.ViewModels { - public class User : IdentityUser + public class UserViewModel : IdentityUser { public string GitHubId { get; set; } @@ -14,7 +14,7 @@ public class User : IdentityUser public bool IsExternalAuth { get; set; } - public User() + public UserViewModel() { } } diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/HomeworksController.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/HomeworksController.cs index 413512bde..0f67a4819 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/HomeworksController.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/HomeworksController.cs @@ -1,4 +1,5 @@ -using System.Threading.Tasks; +using System.Collections.Generic; +using System.Threading.Tasks; using AutoMapper; using HwProj.CoursesService.API.Models; using HwProj.CoursesService.API.Services; @@ -37,6 +38,20 @@ public async Task GetHomework(long homeworkId) homework.Tasks.ForEach(t => t.PutPossibilityForSendingSolution()); return homework; } + + [HttpGet("{courseId}/getAll")] + public async Task GetAllHomeworkFromCourse(long courseId) + { + var homeworkFromDb = await _homeworksService.GetAllHomeworkFromCourse(courseId); + List hwList = null; + foreach (var hw in homeworkFromDb) + { + var homework = _mapper.Map(hw); + homework.Tasks.ForEach(t => t.PutPossibilityForSendingSolution()); + hwList.Add(homework); + } + return hwList?.ToArray(); + } [HttpDelete("delete/{homeworkId}")] public async Task DeleteHomework(long homeworkId) diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs index cab03b83d..83f763948 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs @@ -40,6 +40,11 @@ public async Task GetHomeworkAsync(long homeworkId) return await _homeworksRepository.GetWithTasksAsync(homeworkId); } + public async Task GetAllHomeworkFromCourse(long courseId) + { + return await _homeworksRepository.GetAllWithTasksByCourseAsync(courseId); + } + public async Task DeleteHomeworkAsync(long homeworkId) { await _homeworksRepository.DeleteAsync(homeworkId); diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/IHomeworksService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/IHomeworksService.cs index 5c2d98a60..54a22f163 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/IHomeworksService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/IHomeworksService.cs @@ -9,6 +9,8 @@ public interface IHomeworksService Task GetHomeworkAsync(long homeworkId); + Task GetAllHomeworkFromCourse(long courseId); + Task DeleteHomeworkAsync(long homeworkId); Task UpdateHomeworkAsync(long homeworkId, Homework update); diff --git a/HwProj.CoursesService/HwProj.CoursesService.Client/CoursesServiceClient.cs b/HwProj.CoursesService/HwProj.CoursesService.Client/CoursesServiceClient.cs index a5022b969..5bab8ad13 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.Client/CoursesServiceClient.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.Client/CoursesServiceClient.cs @@ -150,6 +150,15 @@ public async Task GetHomework(long homeworkId) return await response.DeserializeAsync(); } + public async Task GetAllHomeworkByCourse(long courseId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _coursesServiceUri + $"api/Homeworks/{courseId}/getAll"); + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } + public async Task UpdateHomework(CreateHomeworkViewModel model, long homeworkId) { using var httpRequest = new HttpRequestMessage( diff --git a/HwProj.CoursesService/HwProj.CoursesService.Client/ICoursesServiceClient.cs b/HwProj.CoursesService/HwProj.CoursesService.Client/ICoursesServiceClient.cs index 0539ba487..e797b2ac4 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.Client/ICoursesServiceClient.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.Client/ICoursesServiceClient.cs @@ -17,6 +17,7 @@ public interface ICoursesServiceClient Task GetAllUserCourses(string userId); Task AddHomeworkToCourse(CreateHomeworkViewModel model, long courseId); Task GetHomework(long homeworkId); + Task GetAllHomeworkByCourse(long courseId); Task UpdateHomework(CreateHomeworkViewModel model, long homeworkId); Task DeleteHomework(long homeworkId); Task GetTask(long taskId); diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs new file mode 100644 index 000000000..8852468ff --- /dev/null +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs @@ -0,0 +1,32 @@ +using System; +using System.Threading.Tasks; +using HwProj.EventBus.Client.Interfaces; +using HwProj.Models.NotificationsService; +using HwProj.NotificationsService.API.Repositories; +using HwProj.TelegramBotAPI; + +namespace HwProj.NotificationsService.API.EventHandlers +{ + public class ConfirmTelegramBotEventHandler: IEventHandler + { + private readonly INotificationsRepository _notificationRepository; + + public ConfirmTelegramBotEventHandler(INotificationsRepository notificationRepository) + { + _notificationRepository = notificationRepository; + } + + public async Task HandleAsync(ConfirmTelegramBotEvent @event) + { + /*await _notificationRepository.AddAsync(new Notification + { + Sender = "TelegramBot", + Body = "Ваш профиль был успешно отредактирован.", + Category = "AuthService", + Date = DateTime.UtcNow, + HasSeen = false, + Owner = @event.UserId + });*/ + } + } +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj b/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj index c0f6cd39d..e61c18fa4 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj @@ -23,6 +23,8 @@ + + diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs index 3a4cb56cd..54fb7ba52 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs @@ -36,6 +36,7 @@ public void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); services.AddEventBus(Configuration); + /*services.AddTransient, ConfirmTelegramBotEventHandler>();*/ services.AddTransient, RegisterEventHandler>(); services.AddTransient, RateEventHandler>(); services.AddTransient, EditProfileEventHandler>(); @@ -52,12 +53,15 @@ public void ConfigureServices(IServiceCollection services) services.AddAuthServiceClient(httpClient, "http://localhost:5001"); services.AddCoursesServiceClient(httpClient, "http://localhost:5002"); services.AddSolutionServiceClient(httpClient, "http://localhost:5007"); + /*services.AddTelegramBotClient(httpClient, "http://localhost:5009");*/ + services.ConfigureHwProjServices("Notifications API"); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, IEventBus eventBus) { + /*eventBus.Subscribe();*/ eventBus.Subscribe(); eventBus.Subscribe(); eventBus.Subscribe(); diff --git a/HwProj.TelegramBot/HwProj.TelegramBot.Client/ConfigurationExtensions.cs b/HwProj.TelegramBot/HwProj.TelegramBot.Client/ConfigurationExtensions.cs new file mode 100644 index 000000000..1a72e95a4 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBot.Client/ConfigurationExtensions.cs @@ -0,0 +1,17 @@ +using System; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; + +namespace HwProj.TelegramBot.Client +{ + public static class ConfigurationExtensions + { + public static IServiceCollection AddTelegramBotClient(this IServiceCollection services, HttpClient httpClient, + string baseUri) + { + var solutionServiceClient = new TelegramBotClient(httpClient, new Uri(baseUri)); + services.AddSingleton(solutionServiceClient); + return services; + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBot.Client/ITelegramBotClient.cs b/HwProj.TelegramBot/HwProj.TelegramBot.Client/ITelegramBotClient.cs new file mode 100644 index 000000000..49d88b0a5 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBot.Client/ITelegramBotClient.cs @@ -0,0 +1,7 @@ +namespace HwProj.TelegramBot.Client +{ + public interface ITelegramBotClient + { + + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBot.Client/TelegramBotClient.cs b/HwProj.TelegramBot/HwProj.TelegramBot.Client/TelegramBotClient.cs new file mode 100644 index 000000000..25c30b4f6 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBot.Client/TelegramBotClient.cs @@ -0,0 +1,17 @@ +using System; +using System.Net.Http; + +namespace HwProj.TelegramBot.Client +{ + public class TelegramBotClient : ITelegramBotClient + { + private readonly HttpClient _httpClient; + private readonly Uri _telegramBotUri; + + public TelegramBotClient(HttpClient httpClient, Uri telegramBotUri) + { + _httpClient = httpClient; + _telegramBotUri = telegramBotUri; + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/.dockerignore b/HwProj.TelegramBot/HwProj.TelegramBotAPI/.dockerignore new file mode 100644 index 000000000..cd967fc3a --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/.dockerignore @@ -0,0 +1,25 @@ +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/.idea +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/azds.yaml +**/bin +**/charts +**/docker-compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +LICENSE +README.md \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs new file mode 100644 index 000000000..10bbf959d --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs @@ -0,0 +1,9 @@ +namespace HwProj.TelegramBotAPI +{ + public class CommandNames + { + public const string StartCommand = "/start"; + public const string GetCourses = "/courses"; + public const string GetHomeworks = "/homeworks"; + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/Commands.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/Commands.cs new file mode 100644 index 000000000..e3e9356fd --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/Commands.cs @@ -0,0 +1,12 @@ +using System.Threading.Tasks; +using Telegram.Bot.Types; + +namespace HwProj.TelegramBotAPI.Commands +{ + public abstract class Commands + { + public abstract string Name { get; } + + public abstract Task ExecuteAsync(Update update); + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetCourses.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetCourses.cs new file mode 100644 index 000000000..8d2bee8d5 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetCourses.cs @@ -0,0 +1,56 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using HwProj.CoursesService.API.Services; +using HwProj.CoursesService.Client; +using HwProj.TelegramBotAPI.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.ReplyMarkups; + +namespace HwProj.TelegramBotAPI.Commands +{ + public class GetCourses : Commands + { + private readonly ICoursesServiceClient _coursesServiceClient; + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + + public GetCourses(TelegramBot telegramBot, ICoursesServiceClient coursesServiceClient, IUserService userService) + { + _botClient = telegramBot.GetBot().Result; + _coursesServiceClient = coursesServiceClient; + _userService = userService; + } + + public override string Name => CommandNames.GetCourses; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.GetOrCreateChatId(update); + var courses = _coursesServiceClient.GetAllUserCourses(user.StudentId).Result; + + var rows = new List(); + var cols = new List(); + for (var i = 1; i < courses.Length + 1; i++) + { + var k = new InlineKeyboardButton + { + Text = $"/homeworks {courses[i - 1].Id}", + CallbackData = $"/homeworks {courses[i - 1].Id}" + }; + cols.Add(k); + if (i % 3 != 0) continue; + rows.Add(cols.ToArray()); + cols = new List(); + } + + if (courses.Length < 3) + { + rows.Add(cols.ToArray()); + } + var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); + + await _botClient.SendTextMessageAsync(user.ChatId, "Выберите курс:", replyMarkup:keyboardMarkup); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetHomeworks.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetHomeworks.cs new file mode 100644 index 000000000..3bb19bd73 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetHomeworks.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using HwProj.CoursesService.API.Repositories; +using HwProj.CoursesService.Client; +using HwProj.TelegramBotAPI.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.ReplyMarkups; + +namespace HwProj.TelegramBotAPI.Commands +{ + public class GetHomeworks : Commands + { + private readonly ICoursesServiceClient _coursesServiceClient; + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + + public GetHomeworks(TelegramBot telegramBot, ICoursesServiceClient coursesServiceClient, IUserService userService) + { + _botClient = telegramBot.GetBot().Result; + _coursesServiceClient = coursesServiceClient; + _userService = userService; + } + + public override string Name => CommandNames.GetHomeworks; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.GetOrCreateChatId(update); + var message = update.CallbackQuery.Data; + var text = message.Split(' '); + var homeworks = _coursesServiceClient.GetAllHomeworkByCourse(Int32.Parse(text[1])).Result; + + var rows = new List(); + var cols = new List(); + for (var i = 1; i < homeworks.Length + 1; i++) + { + var k = new InlineKeyboardButton + { + Text = homeworks[i - 1].Title, + CallbackData = $"/homeworks " + }; + cols.Add(k); + if (i % 3 != 0) continue; + rows.Add(cols.ToArray()); + cols = new List(); + } + + if (homeworks.Length < 3) + { + rows.Add(cols.ToArray()); + } + var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); + await _botClient.SendTextMessageAsync(user.ChatId, "Выберите homework:", replyMarkup:keyboardMarkup); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/StartCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/StartCommand.cs new file mode 100644 index 000000000..02cffd533 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/StartCommand.cs @@ -0,0 +1,48 @@ +using System.Threading.Tasks; +using HwProj.TelegramBotAPI.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; +using Telegram.Bot.Types.ReplyMarkups; + +namespace HwProj.TelegramBotAPI.Commands +{ + public class StartCommand : Commands + { + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + + public StartCommand(TelegramBot telegramBot, IUserService userService) + { + _botClient = telegramBot.GetBot().Result; + _userService = userService; + } + + public override string Name => CommandNames.StartCommand; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.GetOrCreateChatId(update); + + var inlineKeyboard = new InlineKeyboardMarkup(new[] + { + new[] + { + new InlineKeyboardButton() + { + Text = "Мои курсы", + CallbackData = "/courses" + }, + new InlineKeyboardButton() + { + Text = "/homeworks" + } + } + }); + + await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!", + ParseMode.Markdown, replyMarkup:inlineKeyboard); + + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Controllers/TelegramBotController.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Controllers/TelegramBotController.cs new file mode 100644 index 000000000..2d7259ea9 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Controllers/TelegramBotController.cs @@ -0,0 +1,43 @@ +using System; +using System.Threading.Tasks; +using HwProj.TelegramBotAPI.Service; +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; +using Telegram.Bot.Types; + + +namespace HwProj.TelegramBotAPI.Controllers +{ + [ApiController] + [Route("api/message/update")] + public class TelegramBotController : Controller + { + private readonly ICommandService _commandService; + + public TelegramBotController(ICommandService commandService) + { + _commandService = commandService; + } + + [HttpPost] + public async Task Update(Update update) + { + + if (update?.Message?.Chat == null && update?.CallbackQuery == null) + { + return Ok(); + } + + try + { + await _commandService.Execute(update); + } + catch (Exception e) + { + return Ok(); + } + + return Ok(); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Dockerfile b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Dockerfile new file mode 100644 index 000000000..de38d5668 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Dockerfile @@ -0,0 +1,20 @@ +FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base +WORKDIR /app +EXPOSE 80 +EXPOSE 443 + +FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build +WORKDIR /src +COPY ["HwProj.TelegramBot/HwProj.TelegramBotAPI/HwProj.TelegramBotAPI.csproj", "HwProj.TelegramBotAPI/"] +RUN dotnet restore "HwProj.TelegramBot/HwProj.TelegramBotAPI/HwProj.TelegramBotAPI.csproj" +COPY . . +WORKDIR "/src/HwProj.TelegramBotAPI" +RUN dotnet build "HwProj.TelegramBotAPI.csproj" -c Release -o /app/build + +FROM build AS publish +RUN dotnet publish "HwProj.TelegramBotAPI.csproj" -c Release -o /app/publish + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "HwProj.TelegramBotAPI.dll"] diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Events/ConfirmTelegramBotEvent.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Events/ConfirmTelegramBotEvent.cs new file mode 100644 index 000000000..44a9f16ad --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Events/ConfirmTelegramBotEvent.cs @@ -0,0 +1,12 @@ +using HwProj.EventBus.Client; +using HwProj.TelegramBotAPI.Models; + +namespace HwProj.TelegramBotAPI +{ + public class ConfirmTelegramBotEvent : Event + { + public TelegramUserModel TelegramUserModel { get; set; } + + public string Code { get; set; } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramBotContext.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramBotContext.cs new file mode 100644 index 000000000..dbef30995 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramBotContext.cs @@ -0,0 +1,13 @@ +using Microsoft.EntityFrameworkCore; + +namespace HwProj.TelegramBotAPI.Models +{ + public class TelegramBotContext : DbContext + { + public TelegramBotContext(DbContextOptions options) : base(options) + { + } + + public DbSet TelegramUser { get; set; } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramUserModel.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramUserModel.cs new file mode 100644 index 000000000..9e6edd09d --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramUserModel.cs @@ -0,0 +1,15 @@ +using HwProj.Repositories; + +namespace HwProj.TelegramBotAPI.Models +{ + public class TelegramUserModel + { + public long Id { get; set; } + + public string StudentId { get; set; } + + public long ChatId { get; set; } + + public bool IsRegister { get; set; } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/ITelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/ITelegramBotRepository.cs new file mode 100644 index 000000000..924b4657a --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/ITelegramBotRepository.cs @@ -0,0 +1,7 @@ +namespace HwProj.TelegramBotAPI.Repositories +{ + public interface ITelegramBotRepository + { + + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/TelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/TelegramBotRepository.cs new file mode 100644 index 000000000..a4e4956e2 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/TelegramBotRepository.cs @@ -0,0 +1,10 @@ +using HwProj.Repositories; +using HwProj.TelegramBotAPI.Models; + +namespace HwProj.TelegramBotAPI.Repositories +{ + /*public class TelegramBotRepository: ICrudRepository + { + + }*/ +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/CommandService.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/CommandService.cs new file mode 100644 index 000000000..7f3039651 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/CommandService.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + +namespace HwProj.TelegramBotAPI.Service +{ + public class CommandService : ICommandService + { + private readonly List _commands; + private Commands.Commands _lastCommand; + + public CommandService(IServiceProvider serviceProvider) + { + _commands = serviceProvider.GetServices().ToList(); + } + + public async Task Execute(Update update) + { + if(update?.Message?.Chat == null && update?.CallbackQuery == null) + return; + + if (update.Type == UpdateType.Message) + { + var message = update.Message?.Text; + var text = message.Split(' '); + + if (text[0] == "/start" && text.Length > 1) + { + await ExecuteCommand(CommandNames.StartCommand, update); + return; + } + switch (text[0]) + { + case "/start": + await ExecuteCommand(CommandNames.StartCommand, update); + break; + case "/courses": + await ExecuteCommand(CommandNames.GetCourses, update); + break; + case "/homeworks": + await ExecuteCommand(CommandNames.GetHomeworks, update); + break; + } + } + switch (update.CallbackQuery.Data.Split(' ')[0]) + { + case "/homeworks": + await ExecuteCommand(CommandNames.GetHomeworks, update); + break; + } + } + + private async Task ExecuteCommand(string commandName, Update update) + { + _lastCommand = _commands.First(x=> x.Name == commandName); + await _lastCommand.ExecuteAsync(update); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/ICommandService.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/ICommandService.cs new file mode 100644 index 000000000..bc172b7af --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/ICommandService.cs @@ -0,0 +1,10 @@ +using System.Threading.Tasks; +using Telegram.Bot.Types; + +namespace HwProj.TelegramBotAPI.Service +{ + public interface ICommandService + { + Task Execute(Update update); + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/IUserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/IUserService.cs new file mode 100644 index 000000000..a19f812cb --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/IUserService.cs @@ -0,0 +1,11 @@ +using System.Threading.Tasks; +using HwProj.TelegramBotAPI.Models; +using Telegram.Bot.Types; + +namespace HwProj.TelegramBotAPI.Service +{ + public interface IUserService + { + Task GetOrCreateChatId(Update update); + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/UserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/UserService.cs new file mode 100644 index 000000000..b339f53d0 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/UserService.cs @@ -0,0 +1,78 @@ +using System; +using System.Threading.Tasks; +using HwProj.AuthService.Client; +using HwProj.TelegramBotAPI.Models; +using Microsoft.EntityFrameworkCore; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + +namespace HwProj.TelegramBotAPI.Service +{ + public class UserService : IUserService + { + private readonly TelegramBotContext _context; + private readonly IAuthServiceClient _authClient; + + public UserService(TelegramBotContext context, IAuthServiceClient authClient) + { + _context = context; + _authClient = authClient; + } + + public async Task GetOrCreateChatId(Update update) + { + string studentId; + TelegramUserModel newUser; + if (update.CallbackQuery == null) + { + var message = update.Message?.Text; + var text = message.Split(' '); + if (text[0] == "/start" && text.Length > 1) + { + studentId= _authClient.FindByEmailAsync(text[1]).Result; + } + else if (text[0] == "/start" && text.Length == 1) + { + throw new Exception(); + } + else + { + studentId = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result.StudentId; + } + + newUser = new TelegramUserModel + { + Id = update.Message.Chat.Id, + StudentId = studentId, + ChatId = update.Message.Chat.Id, + IsRegister = true + }; + } + else + { + var message = update.CallbackQuery.Data; + var text = message.Split(' '); + studentId = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id).Result.StudentId; + + newUser = new TelegramUserModel + { + Id = update.CallbackQuery.Message.Chat.Id, + StudentId = studentId, + ChatId = update.CallbackQuery.Message.Chat.Id, + IsRegister = true + }; + } + var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == newUser.ChatId); + + if (user != null) + { + return user; + } + + var result = await _context.TelegramUser.AddAsync(newUser); + await _context.SaveChangesAsync(); + + return result.Entity; + } + } +} \ No newline at end of file diff --git a/HwProj.sln b/HwProj.sln index 3961fc3c1..5a8066027 100644 --- a/HwProj.sln +++ b/HwProj.sln @@ -69,6 +69,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HwProj.SolutionsService.Cli EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HwProj.Exceptions", "HwProj.Common\HwProj.Exceptions\HwProj.Exceptions.csproj", "{51463655-7668-4C7D-9FDE-D4D7CDAA82B8}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "HwProj.TelegramBot", "HwProj.TelegramBot", "{42822186-2040-4216-9C1D-9849EA5D3CB5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HwProj.TelegramBot.Client", "HwProj.TelegramBot\HwProj.TelegramBot.Client\HwProj.TelegramBot.Client.csproj", "{00F850B0-419E-44EA-9AFC-CBF3CBA26C91}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HwProj.TelegramBotAPI", "HwProj.TelegramBot\HwProj.TelegramBotAPI\HwProj.TelegramBotAPI.csproj", "{677D77E8-ACFA-49FE-A752-F787B5F7A3EE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -159,6 +165,14 @@ Global {51463655-7668-4C7D-9FDE-D4D7CDAA82B8}.Debug|Any CPU.Build.0 = Debug|Any CPU {51463655-7668-4C7D-9FDE-D4D7CDAA82B8}.Release|Any CPU.ActiveCfg = Release|Any CPU {51463655-7668-4C7D-9FDE-D4D7CDAA82B8}.Release|Any CPU.Build.0 = Release|Any CPU + {00F850B0-419E-44EA-9AFC-CBF3CBA26C91}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {00F850B0-419E-44EA-9AFC-CBF3CBA26C91}.Debug|Any CPU.Build.0 = Debug|Any CPU + {00F850B0-419E-44EA-9AFC-CBF3CBA26C91}.Release|Any CPU.ActiveCfg = Release|Any CPU + {00F850B0-419E-44EA-9AFC-CBF3CBA26C91}.Release|Any CPU.Build.0 = Release|Any CPU + {677D77E8-ACFA-49FE-A752-F787B5F7A3EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {677D77E8-ACFA-49FE-A752-F787B5F7A3EE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {677D77E8-ACFA-49FE-A752-F787B5F7A3EE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {677D77E8-ACFA-49FE-A752-F787B5F7A3EE}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -185,6 +199,8 @@ Global {0CBD72C5-1CCF-4C13-8046-732398816160} = {1EAEB779-E7C8-4EF9-B9A9-22CB8E3C246D} {C1ACAB32-4100-4C19-AE08-57FA9BA75DF2} = {A85A3030-2878-4923-B450-9683832CDAC1} {51463655-7668-4C7D-9FDE-D4D7CDAA82B8} = {77D857A8-45C6-4432-B4BF-A2F2C9ECA7FE} + {00F850B0-419E-44EA-9AFC-CBF3CBA26C91} = {42822186-2040-4216-9C1D-9849EA5D3CB5} + {677D77E8-ACFA-49FE-A752-F787B5F7A3EE} = {42822186-2040-4216-9C1D-9849EA5D3CB5} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {C03BF138-4A5B-4261-9495-6D3AC6CE9779} diff --git a/hwproj.front/package-lock.json b/hwproj.front/package-lock.json index 30e284109..0cfda625e 100644 --- a/hwproj.front/package-lock.json +++ b/hwproj.front/package-lock.json @@ -16261,6 +16261,14 @@ "remove-accents": "0.4.2" } }, + "material-ui-image": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/material-ui-image/-/material-ui-image-3.3.2.tgz", + "integrity": "sha512-WE5QE0Rjdx9jPKuI0LWI7s8VQ9cifPIXObu8AUCRcidXGV3NqPI9C8c9A/C0MofKpkZ3buG8+IT9N7GgSmxXeg==", + "requires": { + "prop-types": "^15.5.8" + } + }, "md5.js": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", @@ -19633,9 +19641,9 @@ } }, "react-social-login-buttons": { - "version": "3.5.1", - "resolved": "https://registry.npmjs.org/react-social-login-buttons/-/react-social-login-buttons-3.5.1.tgz", - "integrity": "sha512-3TjHYARN9cOfEEl6uQeeB1oMV/dJ2lyxqK98Y+HuvP0E9Q0HJoFvNps6h6EYKE6Yw6LMllUeR5264tSqalM/ww==" + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/react-social-login-buttons/-/react-social-login-buttons-3.6.0.tgz", + "integrity": "sha512-m5E72jHWgC4VBxRziZYQC5kQIzooGRF+dDE97K5JgSlcDPXkNxCjCzP+Qp9fNhNujG7APvPx2Qhzi1BO2xi17Q==" }, "react-syntax-highlighter": { "version": "13.5.3", @@ -21940,6 +21948,16 @@ } } }, + "telegram-login-button": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/telegram-login-button/-/telegram-login-button-0.0.3.tgz", + "integrity": "sha512-R5f3z/YANJjFxIBQxagjrVf+1im/u2CecKlTbFjun9MhPAge8KY3gJ8gTp0TuVJ+L5JShlRDdvrGQibjUiUk0Q==", + "dev": true, + "requires": { + "@babel/runtime": "^7.6.0", + "prop-types": "^15.7.2" + } + }, "telejson": { "version": "5.3.3", "resolved": "https://registry.npmjs.org/telejson/-/telejson-5.3.3.tgz", diff --git a/hwproj.front/package.json b/hwproj.front/package.json index 070b9a68c..1fef04187 100644 --- a/hwproj.front/package.json +++ b/hwproj.front/package.json @@ -28,6 +28,7 @@ "html-react-parser": "^1.2.8", "jwt-decode": "^3.1.2", "lowdb": "^1.0.0", + "material-ui-image": "^3.3.2", "portable-fetch": "^3.0.0", "prop-types": "^15.7.2", "react": "^16.12.0", @@ -37,7 +38,7 @@ "react-query": "^3.21.1", "react-router-dom": "^5.2.1", "react-scripts": "^4.0.3", - "react-social-login-buttons": "^3.5.1" + "react-social-login-buttons": "^3.6.0" }, "scripts": { "start": "react-scripts start", @@ -68,6 +69,7 @@ "@types/react-dom": "^16.9.14", "@types/react-router-dom": "^4.3.5", "prettier": "2.2.1", + "telegram-login-button": "0.0.3", "typescript": "^3.9.10" } } diff --git a/hwproj.front/src/api/api.ts b/hwproj.front/src/api/api.ts index 8a97ad17d..49b3eeb53 100644 --- a/hwproj.front/src/api/api.ts +++ b/hwproj.front/src/api/api.ts @@ -5,7 +5,7 @@ * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1 - * + * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -79,43 +79,43 @@ export class RequiredError extends Error { } /** - * + * * @export * @interface AccountDataDto */ export interface AccountDataDto { /** - * + * * @type {string} * @memberof AccountDataDto */ name?: string; /** - * + * * @type {string} * @memberof AccountDataDto */ surname?: string; /** - * + * * @type {string} * @memberof AccountDataDto */ middleName?: string; /** - * + * * @type {string} * @memberof AccountDataDto */ email?: string; /** - * + * * @type {string} * @memberof AccountDataDto */ role?: string; /** - * + * * @type {boolean} * @memberof AccountDataDto */ @@ -123,19 +123,19 @@ export interface AccountDataDto { } /** - * + * * @export * @interface CourseMateViewModel */ export interface CourseMateViewModel { /** - * + * * @type {string} * @memberof CourseMateViewModel */ studentId?: string; /** - * + * * @type {boolean} * @memberof CourseMateViewModel */ @@ -143,61 +143,61 @@ export interface CourseMateViewModel { } /** - * + * * @export * @interface CourseViewModel */ export interface CourseViewModel { /** - * + * * @type {number} * @memberof CourseViewModel */ id?: number; /** - * + * * @type {string} * @memberof CourseViewModel */ name?: string; /** - * + * * @type {string} * @memberof CourseViewModel */ groupName?: string; /** - * + * * @type {boolean} * @memberof CourseViewModel */ isOpen?: boolean; /** - * + * * @type {boolean} * @memberof CourseViewModel */ isCompleted?: boolean; /** - * + * * @type {string} * @memberof CourseViewModel */ mentorIds?: string; /** - * + * * @type {string} * @memberof CourseViewModel */ inviteCode?: string; /** - * + * * @type {Array} * @memberof CourseViewModel */ courseMates?: Array; /** - * + * * @type {Array} * @memberof CourseViewModel */ @@ -205,25 +205,25 @@ export interface CourseViewModel { } /** - * + * * @export * @interface CreateCourseViewModel */ export interface CreateCourseViewModel { /** - * + * * @type {string} * @memberof CreateCourseViewModel */ name: string; /** - * + * * @type {string} * @memberof CreateCourseViewModel */ groupName?: string; /** - * + * * @type {boolean} * @memberof CreateCourseViewModel */ @@ -231,31 +231,31 @@ export interface CreateCourseViewModel { } /** - * + * * @export * @interface CreateGroupViewModel */ export interface CreateGroupViewModel { /** - * + * * @type {string} * @memberof CreateGroupViewModel */ name: string; /** - * + * * @type {Array} * @memberof CreateGroupViewModel */ groupMates: Array; /** - * + * * @type {number} * @memberof CreateGroupViewModel */ courseId: number; /** - * + * * @type {Array} * @memberof CreateGroupViewModel */ @@ -263,25 +263,25 @@ export interface CreateGroupViewModel { } /** - * + * * @export * @interface CreateHomeworkViewModel */ export interface CreateHomeworkViewModel { /** - * + * * @type {string} * @memberof CreateHomeworkViewModel */ title: string; /** - * + * * @type {string} * @memberof CreateHomeworkViewModel */ description?: string; /** - * + * * @type {Array} * @memberof CreateHomeworkViewModel */ @@ -289,49 +289,49 @@ export interface CreateHomeworkViewModel { } /** - * + * * @export * @interface CreateTaskViewModel */ export interface CreateTaskViewModel { /** - * + * * @type {string} * @memberof CreateTaskViewModel */ title: string; /** - * + * * @type {string} * @memberof CreateTaskViewModel */ description?: string; /** - * + * * @type {boolean} * @memberof CreateTaskViewModel */ hasDeadline?: boolean; /** - * + * * @type {Date} * @memberof CreateTaskViewModel */ deadlineDate?: Date; /** - * + * * @type {boolean} * @memberof CreateTaskViewModel */ isDeadlineStrict?: boolean; /** - * + * * @type {Date} * @memberof CreateTaskViewModel */ publicationDate?: Date; /** - * + * * @type {number} * @memberof CreateTaskViewModel */ @@ -339,37 +339,37 @@ export interface CreateTaskViewModel { } /** - * + * * @export * @interface EditAccountViewModel */ export interface EditAccountViewModel { /** - * + * * @type {string} * @memberof EditAccountViewModel */ name: string; /** - * + * * @type {string} * @memberof EditAccountViewModel */ surname: string; /** - * + * * @type {string} * @memberof EditAccountViewModel */ middleName?: string; /** - * + * * @type {string} * @memberof EditAccountViewModel */ currentPassword: string; /** - * + * * @type {string} * @memberof EditAccountViewModel */ @@ -377,25 +377,25 @@ export interface EditAccountViewModel { } /** - * + * * @export * @interface EditExternalViewModel */ export interface EditExternalViewModel { /** - * + * * @type {string} * @memberof EditExternalViewModel */ name: string; /** - * + * * @type {string} * @memberof EditExternalViewModel */ surname: string; /** - * + * * @type {string} * @memberof EditExternalViewModel */ @@ -403,13 +403,13 @@ export interface EditExternalViewModel { } /** - * + * * @export * @interface GroupMateViewModel */ export interface GroupMateViewModel { /** - * + * * @type {string} * @memberof GroupMateViewModel */ @@ -417,37 +417,37 @@ export interface GroupMateViewModel { } /** - * + * * @export * @interface GroupViewModel */ export interface GroupViewModel { /** - * + * * @type {number} * @memberof GroupViewModel */ id?: number; /** - * + * * @type {number} * @memberof GroupViewModel */ courseId?: number; /** - * + * * @type {string} * @memberof GroupViewModel */ name?: string; /** - * + * * @type {Array} * @memberof GroupViewModel */ tasks?: Array; /** - * + * * @type {Array} * @memberof GroupViewModel */ @@ -455,73 +455,73 @@ export interface GroupViewModel { } /** - * + * * @export * @interface HomeworkTaskViewModel */ export interface HomeworkTaskViewModel { /** - * + * * @type {number} * @memberof HomeworkTaskViewModel */ id?: number; /** - * + * * @type {string} * @memberof HomeworkTaskViewModel */ title?: string; /** - * + * * @type {string} * @memberof HomeworkTaskViewModel */ description?: string; /** - * + * * @type {number} * @memberof HomeworkTaskViewModel */ maxRating?: number; /** - * + * * @type {boolean} * @memberof HomeworkTaskViewModel */ hasDeadline?: boolean; /** - * + * * @type {Date} * @memberof HomeworkTaskViewModel */ deadlineDate?: Date; /** - * + * * @type {boolean} * @memberof HomeworkTaskViewModel */ isDeadlineStrict?: boolean; /** - * + * * @type {boolean} * @memberof HomeworkTaskViewModel */ canSendSolution?: boolean; /** - * + * * @type {Date} * @memberof HomeworkTaskViewModel */ publicationDate?: Date; /** - * + * * @type {number} * @memberof HomeworkTaskViewModel */ homeworkId?: number; /** - * + * * @type {boolean} * @memberof HomeworkTaskViewModel */ @@ -529,43 +529,43 @@ export interface HomeworkTaskViewModel { } /** - * + * * @export * @interface HomeworkViewModel */ export interface HomeworkViewModel { /** - * + * * @type {number} * @memberof HomeworkViewModel */ id?: number; /** - * + * * @type {string} * @memberof HomeworkViewModel */ title?: string; /** - * + * * @type {string} * @memberof HomeworkViewModel */ description?: string; /** - * + * * @type {Date} * @memberof HomeworkViewModel */ date?: Date; /** - * + * * @type {number} * @memberof HomeworkViewModel */ courseId?: number; /** - * + * * @type {Array} * @memberof HomeworkViewModel */ @@ -573,13 +573,13 @@ export interface HomeworkViewModel { } /** - * + * * @export * @interface InviteLecturerViewModel */ export interface InviteLecturerViewModel { /** - * + * * @type {string} * @memberof InviteLecturerViewModel */ @@ -587,25 +587,25 @@ export interface InviteLecturerViewModel { } /** - * + * * @export * @interface LoginViewModel */ export interface LoginViewModel { /** - * + * * @type {string} * @memberof LoginViewModel */ email: string; /** - * + * * @type {string} * @memberof LoginViewModel */ password: string; /** - * + * * @type {boolean} * @memberof LoginViewModel */ @@ -613,43 +613,43 @@ export interface LoginViewModel { } /** - * + * * @export * @interface NotificationViewModel */ export interface NotificationViewModel { /** - * + * * @type {number} * @memberof NotificationViewModel */ id?: number; /** - * + * * @type {string} * @memberof NotificationViewModel */ sender?: string; /** - * + * * @type {string} * @memberof NotificationViewModel */ owner?: string; /** - * + * * @type {string} * @memberof NotificationViewModel */ category?: string; /** - * + * * @type {string} * @memberof NotificationViewModel */ body?: string; /** - * + * * @type {boolean} * @memberof NotificationViewModel */ @@ -657,43 +657,43 @@ export interface NotificationViewModel { } /** - * + * * @export * @interface RegisterViewModel */ export interface RegisterViewModel { /** - * + * * @type {string} * @memberof RegisterViewModel */ name: string; /** - * + * * @type {string} * @memberof RegisterViewModel */ surname: string; /** - * + * * @type {string} * @memberof RegisterViewModel */ middleName?: string; /** - * + * * @type {string} * @memberof RegisterViewModel */ email: string; /** - * + * * @type {string} * @memberof RegisterViewModel */ password: string; /** - * + * * @type {string} * @memberof RegisterViewModel */ @@ -701,19 +701,19 @@ export interface RegisterViewModel { } /** - * + * * @export * @interface Result */ export interface Result { /** - * + * * @type {boolean} * @memberof Result */ succeeded?: boolean; /** - * + * * @type {Array} * @memberof Result */ @@ -721,25 +721,25 @@ export interface Result { } /** - * + * * @export * @interface ResultTokenCredentials */ export interface ResultTokenCredentials { /** - * + * * @type {TokenCredentials} * @memberof ResultTokenCredentials */ value?: TokenCredentials; /** - * + * * @type {boolean} * @memberof ResultTokenCredentials */ succeeded?: boolean; /** - * + * * @type {Array} * @memberof ResultTokenCredentials */ @@ -747,67 +747,67 @@ export interface ResultTokenCredentials { } /** - * + * * @export * @interface Solution */ export interface Solution { /** - * + * * @type {number} * @memberof Solution */ id?: number; /** - * + * * @type {string} * @memberof Solution */ githubUrl?: string; /** - * + * * @type {string} * @memberof Solution */ comment?: string; /** - * + * * @type {number} * @memberof Solution */ state?: Solution.StateEnum; /** - * + * * @type {number} * @memberof Solution */ rating?: number; /** - * + * * @type {string} * @memberof Solution */ studentId?: string; /** - * + * * @type {number} * @memberof Solution */ groupId?: number; /** - * + * * @type {number} * @memberof Solution */ taskId?: number; /** - * + * * @type {Date} * @memberof Solution */ publicationDate?: Date; /** - * + * * @type {string} * @memberof Solution */ @@ -831,37 +831,37 @@ export namespace Solution { } /** - * + * * @export * @interface SolutionViewModel */ export interface SolutionViewModel { /** - * + * * @type {string} * @memberof SolutionViewModel */ githubUrl: string; /** - * + * * @type {string} * @memberof SolutionViewModel */ comment?: string; /** - * + * * @type {string} * @memberof SolutionViewModel */ studentId?: string; /** - * + * * @type {Date} * @memberof SolutionViewModel */ publicationDate?: Date; /** - * + * * @type {string} * @memberof SolutionViewModel */ @@ -869,19 +869,19 @@ export interface SolutionViewModel { } /** - * + * * @export * @interface StatisticsCourseHomeworksModel */ export interface StatisticsCourseHomeworksModel { /** - * + * * @type {number} * @memberof StatisticsCourseHomeworksModel */ id?: number; /** - * + * * @type {Array} * @memberof StatisticsCourseHomeworksModel */ @@ -889,31 +889,31 @@ export interface StatisticsCourseHomeworksModel { } /** - * + * * @export * @interface StatisticsCourseMatesModel */ export interface StatisticsCourseMatesModel { /** - * + * * @type {string} * @memberof StatisticsCourseMatesModel */ id?: string; /** - * + * * @type {string} * @memberof StatisticsCourseMatesModel */ name?: string; /** - * + * * @type {string} * @memberof StatisticsCourseMatesModel */ surname?: string; /** - * + * * @type {Array} * @memberof StatisticsCourseMatesModel */ @@ -921,25 +921,25 @@ export interface StatisticsCourseMatesModel { } /** - * + * * @export * @interface StatisticsCourseSolutionsModel */ export interface StatisticsCourseSolutionsModel { /** - * + * * @type {number} * @memberof StatisticsCourseSolutionsModel */ id?: number; /** - * + * * @type {number} * @memberof StatisticsCourseSolutionsModel */ state?: StatisticsCourseSolutionsModel.StateEnum; /** - * + * * @type {number} * @memberof StatisticsCourseSolutionsModel */ @@ -963,19 +963,19 @@ export namespace StatisticsCourseSolutionsModel { } /** - * + * * @export * @interface StatisticsCourseTasksModel */ export interface StatisticsCourseTasksModel { /** - * + * * @type {number} * @memberof StatisticsCourseTasksModel */ id?: number; /** - * + * * @type {Array} * @memberof StatisticsCourseTasksModel */ @@ -983,19 +983,19 @@ export interface StatisticsCourseTasksModel { } /** - * + * * @export * @interface TokenCredentials */ export interface TokenCredentials { /** - * + * * @type {string} * @memberof TokenCredentials */ accessToken?: string; /** - * + * * @type {number} * @memberof TokenCredentials */ @@ -1003,31 +1003,31 @@ export interface TokenCredentials { } /** - * + * * @export * @interface UpdateCourseViewModel */ export interface UpdateCourseViewModel { /** - * + * * @type {string} * @memberof UpdateCourseViewModel */ name: string; /** - * + * * @type {string} * @memberof UpdateCourseViewModel */ groupName?: string; /** - * + * * @type {boolean} * @memberof UpdateCourseViewModel */ isOpen: boolean; /** - * + * * @type {boolean} * @memberof UpdateCourseViewModel */ @@ -1035,25 +1035,25 @@ export interface UpdateCourseViewModel { } /** - * + * * @export * @interface UpdateGroupViewModel */ export interface UpdateGroupViewModel { /** - * + * * @type {string} * @memberof UpdateGroupViewModel */ name?: string; /** - * + * * @type {Array} * @memberof UpdateGroupViewModel */ tasks?: Array; /** - * + * * @type {Array} * @memberof UpdateGroupViewModel */ @@ -1061,43 +1061,43 @@ export interface UpdateGroupViewModel { } /** - * + * * @export * @interface UserCourseDescription */ export interface UserCourseDescription { /** - * + * * @type {number} * @memberof UserCourseDescription */ id?: number; /** - * + * * @type {string} * @memberof UserCourseDescription */ name?: string; /** - * + * * @type {string} * @memberof UserCourseDescription */ groupName?: string; /** - * + * * @type {boolean} * @memberof UserCourseDescription */ isOpen?: boolean; /** - * + * * @type {boolean} * @memberof UserCourseDescription */ isCompleted?: boolean; /** - * + * * @type {boolean} * @memberof UserCourseDescription */ @@ -1105,19 +1105,19 @@ export interface UserCourseDescription { } /** - * + * * @export * @interface UserDataDto */ export interface UserDataDto { /** - * + * * @type {AccountDataDto} * @memberof UserDataDto */ userData?: AccountDataDto; /** - * + * * @type {Array} * @memberof UserDataDto */ @@ -1132,8 +1132,8 @@ export interface UserDataDto { export const AccountApiFetchParamCreator = function (configuration?: Configuration) { return { /** - * - * @param {EditExternalViewModel} [model] + * + * @param {EditExternalViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1147,8 +1147,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -1167,8 +1167,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * - * @param {EditAccountViewModel} [model] + * + * @param {EditAccountViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1182,8 +1182,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -1202,7 +1202,7 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1216,8 +1216,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -1232,8 +1232,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * - * @param {string} userId + * + * @param {string} userId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1252,8 +1252,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -1268,7 +1268,7 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1282,8 +1282,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -1298,8 +1298,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * - * @param {string} [tokenId] + * + * @param {string} [tokenId] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1313,8 +1313,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -1333,8 +1333,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * - * @param {InviteLecturerViewModel} [model] + * + * @param {InviteLecturerViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1348,8 +1348,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -1368,8 +1368,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * - * @param {LoginViewModel} [model] + * + * @param {LoginViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1383,8 +1383,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -1403,8 +1403,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * - * @param {RegisterViewModel} [model] + * + * @param {RegisterViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1418,8 +1418,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -1447,8 +1447,8 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati export const AccountApiFp = function(configuration?: Configuration) { return { /** - * - * @param {EditExternalViewModel} [model] + * + * @param {EditExternalViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1465,8 +1465,8 @@ export const AccountApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {EditAccountViewModel} [model] + * + * @param {EditAccountViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1483,7 +1483,7 @@ export const AccountApiFp = function(configuration?: Configuration) { }; }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1500,8 +1500,8 @@ export const AccountApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {string} userId + * + * @param {string} userId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1518,7 +1518,7 @@ export const AccountApiFp = function(configuration?: Configuration) { }; }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1535,8 +1535,8 @@ export const AccountApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {string} [tokenId] + * + * @param {string} [tokenId] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1553,8 +1553,8 @@ export const AccountApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {InviteLecturerViewModel} [model] + * + * @param {InviteLecturerViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1571,8 +1571,8 @@ export const AccountApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {LoginViewModel} [model] + * + * @param {LoginViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1589,8 +1589,8 @@ export const AccountApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {RegisterViewModel} [model] + * + * @param {RegisterViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1616,8 +1616,8 @@ export const AccountApiFp = function(configuration?: Configuration) { export const AccountApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) { return { /** - * - * @param {EditExternalViewModel} [model] + * + * @param {EditExternalViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1625,8 +1625,8 @@ export const AccountApiFactory = function (configuration?: Configuration, fetch? return AccountApiFp(configuration).apiAccountEditExternalPut(model, options)(fetch, basePath); }, /** - * - * @param {EditAccountViewModel} [model] + * + * @param {EditAccountViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1634,7 +1634,7 @@ export const AccountApiFactory = function (configuration?: Configuration, fetch? return AccountApiFp(configuration).apiAccountEditPut(model, options)(fetch, basePath); }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1642,8 +1642,8 @@ export const AccountApiFactory = function (configuration?: Configuration, fetch? return AccountApiFp(configuration).apiAccountGetAllStudentsGet(options)(fetch, basePath); }, /** - * - * @param {string} userId + * + * @param {string} userId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1651,7 +1651,7 @@ export const AccountApiFactory = function (configuration?: Configuration, fetch? return AccountApiFp(configuration).apiAccountGetUserDataByUserIdGet(userId, options)(fetch, basePath); }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1659,8 +1659,8 @@ export const AccountApiFactory = function (configuration?: Configuration, fetch? return AccountApiFp(configuration).apiAccountGetUserDataGet(options)(fetch, basePath); }, /** - * - * @param {string} [tokenId] + * + * @param {string} [tokenId] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1668,8 +1668,8 @@ export const AccountApiFactory = function (configuration?: Configuration, fetch? return AccountApiFp(configuration).apiAccountGooglePost(tokenId, options)(fetch, basePath); }, /** - * - * @param {InviteLecturerViewModel} [model] + * + * @param {InviteLecturerViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1677,8 +1677,8 @@ export const AccountApiFactory = function (configuration?: Configuration, fetch? return AccountApiFp(configuration).apiAccountInviteNewLecturerPost(model, options)(fetch, basePath); }, /** - * - * @param {LoginViewModel} [model] + * + * @param {LoginViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1686,8 +1686,8 @@ export const AccountApiFactory = function (configuration?: Configuration, fetch? return AccountApiFp(configuration).apiAccountLoginPost(model, options)(fetch, basePath); }, /** - * - * @param {RegisterViewModel} [model] + * + * @param {RegisterViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1705,8 +1705,8 @@ export const AccountApiFactory = function (configuration?: Configuration, fetch? */ export class AccountApi extends BaseAPI { /** - * - * @param {EditExternalViewModel} [model] + * + * @param {EditExternalViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AccountApi @@ -1716,8 +1716,8 @@ export class AccountApi extends BaseAPI { } /** - * - * @param {EditAccountViewModel} [model] + * + * @param {EditAccountViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AccountApi @@ -1727,7 +1727,7 @@ export class AccountApi extends BaseAPI { } /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AccountApi @@ -1737,8 +1737,8 @@ export class AccountApi extends BaseAPI { } /** - * - * @param {string} userId + * + * @param {string} userId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AccountApi @@ -1748,7 +1748,7 @@ export class AccountApi extends BaseAPI { } /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AccountApi @@ -1758,8 +1758,8 @@ export class AccountApi extends BaseAPI { } /** - * - * @param {string} [tokenId] + * + * @param {string} [tokenId] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AccountApi @@ -1769,8 +1769,8 @@ export class AccountApi extends BaseAPI { } /** - * - * @param {InviteLecturerViewModel} [model] + * + * @param {InviteLecturerViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AccountApi @@ -1780,8 +1780,8 @@ export class AccountApi extends BaseAPI { } /** - * - * @param {LoginViewModel} [model] + * + * @param {LoginViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AccountApi @@ -1791,8 +1791,8 @@ export class AccountApi extends BaseAPI { } /** - * - * @param {RegisterViewModel} [model] + * + * @param {RegisterViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AccountApi @@ -1810,10 +1810,10 @@ export class AccountApi extends BaseAPI { export const CourseGroupsApiFetchParamCreator = function (configuration?: Configuration) { return { /** - * - * @param {number} courseId - * @param {number} groupId - * @param {string} [userId] + * + * @param {number} courseId + * @param {number} groupId + * @param {string} [userId] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1837,8 +1837,8 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -1857,9 +1857,9 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config }; }, /** - * - * @param {number} courseId - * @param {CreateGroupViewModel} [model] + * + * @param {number} courseId + * @param {CreateGroupViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1878,8 +1878,8 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -1898,9 +1898,9 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config }; }, /** - * - * @param {number} courseId - * @param {number} groupId + * + * @param {number} courseId + * @param {number} groupId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1924,8 +1924,8 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -1940,8 +1940,8 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config }; }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1960,8 +1960,8 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -1976,8 +1976,8 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config }; }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -1996,8 +1996,8 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2012,10 +2012,10 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config }; }, /** - * - * @param {number} courseId - * @param {number} groupId - * @param {string} [userId] + * + * @param {number} courseId + * @param {number} groupId + * @param {string} [userId] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2039,8 +2039,8 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2059,10 +2059,10 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config }; }, /** - * - * @param {number} courseId - * @param {number} groupId - * @param {UpdateGroupViewModel} [model] + * + * @param {number} courseId + * @param {number} groupId + * @param {UpdateGroupViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2086,8 +2086,8 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2106,8 +2106,8 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config }; }, /** - * - * @param {number} groupId + * + * @param {number} groupId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2126,8 +2126,8 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2142,8 +2142,8 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config }; }, /** - * - * @param {number} groupId + * + * @param {number} groupId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2162,8 +2162,8 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2187,10 +2187,10 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config export const CourseGroupsApiFp = function(configuration?: Configuration) { return { /** - * - * @param {number} courseId - * @param {number} groupId - * @param {string} [userId] + * + * @param {number} courseId + * @param {number} groupId + * @param {string} [userId] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2207,9 +2207,9 @@ export const CourseGroupsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} courseId - * @param {CreateGroupViewModel} [model] + * + * @param {number} courseId + * @param {CreateGroupViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2226,9 +2226,9 @@ export const CourseGroupsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} courseId - * @param {number} groupId + * + * @param {number} courseId + * @param {number} groupId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2245,8 +2245,8 @@ export const CourseGroupsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2263,8 +2263,8 @@ export const CourseGroupsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2281,10 +2281,10 @@ export const CourseGroupsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} courseId - * @param {number} groupId - * @param {string} [userId] + * + * @param {number} courseId + * @param {number} groupId + * @param {string} [userId] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2301,10 +2301,10 @@ export const CourseGroupsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} courseId - * @param {number} groupId - * @param {UpdateGroupViewModel} [model] + * + * @param {number} courseId + * @param {number} groupId + * @param {UpdateGroupViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2321,8 +2321,8 @@ export const CourseGroupsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} groupId + * + * @param {number} groupId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2339,8 +2339,8 @@ export const CourseGroupsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} groupId + * + * @param {number} groupId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2366,10 +2366,10 @@ export const CourseGroupsApiFp = function(configuration?: Configuration) { export const CourseGroupsApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) { return { /** - * - * @param {number} courseId - * @param {number} groupId - * @param {string} [userId] + * + * @param {number} courseId + * @param {number} groupId + * @param {string} [userId] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2377,9 +2377,9 @@ export const CourseGroupsApiFactory = function (configuration?: Configuration, f return CourseGroupsApiFp(configuration).apiCourseGroupsByCourseIdAddStudentInGroupByGroupIdPost(courseId, groupId, userId, options)(fetch, basePath); }, /** - * - * @param {number} courseId - * @param {CreateGroupViewModel} [model] + * + * @param {number} courseId + * @param {CreateGroupViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2387,9 +2387,9 @@ export const CourseGroupsApiFactory = function (configuration?: Configuration, f return CourseGroupsApiFp(configuration).apiCourseGroupsByCourseIdCreatePost(courseId, model, options)(fetch, basePath); }, /** - * - * @param {number} courseId - * @param {number} groupId + * + * @param {number} courseId + * @param {number} groupId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2397,8 +2397,8 @@ export const CourseGroupsApiFactory = function (configuration?: Configuration, f return CourseGroupsApiFp(configuration).apiCourseGroupsByCourseIdDeleteByGroupIdDelete(courseId, groupId, options)(fetch, basePath); }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2406,8 +2406,8 @@ export const CourseGroupsApiFactory = function (configuration?: Configuration, f return CourseGroupsApiFp(configuration).apiCourseGroupsByCourseIdGetAllGet(courseId, options)(fetch, basePath); }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2415,10 +2415,10 @@ export const CourseGroupsApiFactory = function (configuration?: Configuration, f return CourseGroupsApiFp(configuration).apiCourseGroupsByCourseIdGetGet(courseId, options)(fetch, basePath); }, /** - * - * @param {number} courseId - * @param {number} groupId - * @param {string} [userId] + * + * @param {number} courseId + * @param {number} groupId + * @param {string} [userId] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2426,10 +2426,10 @@ export const CourseGroupsApiFactory = function (configuration?: Configuration, f return CourseGroupsApiFp(configuration).apiCourseGroupsByCourseIdRemoveStudentFromGroupByGroupIdPost(courseId, groupId, userId, options)(fetch, basePath); }, /** - * - * @param {number} courseId - * @param {number} groupId - * @param {UpdateGroupViewModel} [model] + * + * @param {number} courseId + * @param {number} groupId + * @param {UpdateGroupViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2437,8 +2437,8 @@ export const CourseGroupsApiFactory = function (configuration?: Configuration, f return CourseGroupsApiFp(configuration).apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId, groupId, model, options)(fetch, basePath); }, /** - * - * @param {number} groupId + * + * @param {number} groupId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2446,8 +2446,8 @@ export const CourseGroupsApiFactory = function (configuration?: Configuration, f return CourseGroupsApiFp(configuration).apiCourseGroupsGetByGroupIdGet(groupId, options)(fetch, basePath); }, /** - * - * @param {number} groupId + * + * @param {number} groupId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2465,10 +2465,10 @@ export const CourseGroupsApiFactory = function (configuration?: Configuration, f */ export class CourseGroupsApi extends BaseAPI { /** - * - * @param {number} courseId - * @param {number} groupId - * @param {string} [userId] + * + * @param {number} courseId + * @param {number} groupId + * @param {string} [userId] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CourseGroupsApi @@ -2478,9 +2478,9 @@ export class CourseGroupsApi extends BaseAPI { } /** - * - * @param {number} courseId - * @param {CreateGroupViewModel} [model] + * + * @param {number} courseId + * @param {CreateGroupViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CourseGroupsApi @@ -2490,9 +2490,9 @@ export class CourseGroupsApi extends BaseAPI { } /** - * - * @param {number} courseId - * @param {number} groupId + * + * @param {number} courseId + * @param {number} groupId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CourseGroupsApi @@ -2502,8 +2502,8 @@ export class CourseGroupsApi extends BaseAPI { } /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CourseGroupsApi @@ -2513,8 +2513,8 @@ export class CourseGroupsApi extends BaseAPI { } /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CourseGroupsApi @@ -2524,10 +2524,10 @@ export class CourseGroupsApi extends BaseAPI { } /** - * - * @param {number} courseId - * @param {number} groupId - * @param {string} [userId] + * + * @param {number} courseId + * @param {number} groupId + * @param {string} [userId] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CourseGroupsApi @@ -2537,10 +2537,10 @@ export class CourseGroupsApi extends BaseAPI { } /** - * - * @param {number} courseId - * @param {number} groupId - * @param {UpdateGroupViewModel} [model] + * + * @param {number} courseId + * @param {number} groupId + * @param {UpdateGroupViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CourseGroupsApi @@ -2550,8 +2550,8 @@ export class CourseGroupsApi extends BaseAPI { } /** - * - * @param {number} groupId + * + * @param {number} groupId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CourseGroupsApi @@ -2561,8 +2561,8 @@ export class CourseGroupsApi extends BaseAPI { } /** - * - * @param {number} groupId + * + * @param {number} groupId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CourseGroupsApi @@ -2580,9 +2580,9 @@ export class CourseGroupsApi extends BaseAPI { export const CoursesApiFetchParamCreator = function (configuration?: Configuration) { return { /** - * - * @param {number} courseId - * @param {string} lecturerEmail + * + * @param {number} courseId + * @param {string} lecturerEmail * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2606,8 +2606,8 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2622,9 +2622,9 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * - * @param {number} courseId - * @param {string} studentId + * + * @param {number} courseId + * @param {string} studentId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2648,8 +2648,8 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2664,8 +2664,8 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2684,8 +2684,8 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2700,8 +2700,8 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2720,8 +2720,8 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2736,8 +2736,8 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * - * @param {CreateCourseViewModel} [model] + * + * @param {CreateCourseViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2751,8 +2751,8 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2771,7 +2771,7 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2785,8 +2785,8 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2801,9 +2801,9 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * - * @param {number} courseId - * @param {string} studentId + * + * @param {number} courseId + * @param {string} studentId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2827,8 +2827,8 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2843,8 +2843,8 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2863,8 +2863,8 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2879,9 +2879,9 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * - * @param {number} courseId - * @param {UpdateCourseViewModel} [model] + * + * @param {number} courseId + * @param {UpdateCourseViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2900,8 +2900,8 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2920,7 +2920,7 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati }; }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2934,8 +2934,8 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -2959,9 +2959,9 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati export const CoursesApiFp = function(configuration?: Configuration) { return { /** - * - * @param {number} courseId - * @param {string} lecturerEmail + * + * @param {number} courseId + * @param {string} lecturerEmail * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2978,9 +2978,9 @@ export const CoursesApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} courseId - * @param {string} studentId + * + * @param {number} courseId + * @param {string} studentId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -2997,8 +2997,8 @@ export const CoursesApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3015,8 +3015,8 @@ export const CoursesApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3033,8 +3033,8 @@ export const CoursesApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {CreateCourseViewModel} [model] + * + * @param {CreateCourseViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3051,7 +3051,7 @@ export const CoursesApiFp = function(configuration?: Configuration) { }; }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3068,9 +3068,9 @@ export const CoursesApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} courseId - * @param {string} studentId + * + * @param {number} courseId + * @param {string} studentId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3087,8 +3087,8 @@ export const CoursesApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3105,9 +3105,9 @@ export const CoursesApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} courseId - * @param {UpdateCourseViewModel} [model] + * + * @param {number} courseId + * @param {UpdateCourseViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3124,7 +3124,7 @@ export const CoursesApiFp = function(configuration?: Configuration) { }; }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3150,9 +3150,9 @@ export const CoursesApiFp = function(configuration?: Configuration) { export const CoursesApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) { return { /** - * - * @param {number} courseId - * @param {string} lecturerEmail + * + * @param {number} courseId + * @param {string} lecturerEmail * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3160,9 +3160,9 @@ export const CoursesApiFactory = function (configuration?: Configuration, fetch? return CoursesApiFp(configuration).apiCoursesAcceptLecturerByCourseIdByLecturerEmailGet(courseId, lecturerEmail, options)(fetch, basePath); }, /** - * - * @param {number} courseId - * @param {string} studentId + * + * @param {number} courseId + * @param {string} studentId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3170,8 +3170,8 @@ export const CoursesApiFactory = function (configuration?: Configuration, fetch? return CoursesApiFp(configuration).apiCoursesAcceptStudentByCourseIdByStudentIdPost(courseId, studentId, options)(fetch, basePath); }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3179,8 +3179,8 @@ export const CoursesApiFactory = function (configuration?: Configuration, fetch? return CoursesApiFp(configuration).apiCoursesByCourseIdDelete(courseId, options)(fetch, basePath); }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3188,8 +3188,8 @@ export const CoursesApiFactory = function (configuration?: Configuration, fetch? return CoursesApiFp(configuration).apiCoursesByCourseIdGet(courseId, options)(fetch, basePath); }, /** - * - * @param {CreateCourseViewModel} [model] + * + * @param {CreateCourseViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3197,7 +3197,7 @@ export const CoursesApiFactory = function (configuration?: Configuration, fetch? return CoursesApiFp(configuration).apiCoursesCreatePost(model, options)(fetch, basePath); }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3205,9 +3205,9 @@ export const CoursesApiFactory = function (configuration?: Configuration, fetch? return CoursesApiFp(configuration).apiCoursesGet(options)(fetch, basePath); }, /** - * - * @param {number} courseId - * @param {string} studentId + * + * @param {number} courseId + * @param {string} studentId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3215,8 +3215,8 @@ export const CoursesApiFactory = function (configuration?: Configuration, fetch? return CoursesApiFp(configuration).apiCoursesRejectStudentByCourseIdByStudentIdPost(courseId, studentId, options)(fetch, basePath); }, /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3224,9 +3224,9 @@ export const CoursesApiFactory = function (configuration?: Configuration, fetch? return CoursesApiFp(configuration).apiCoursesSignInCourseByCourseIdPost(courseId, options)(fetch, basePath); }, /** - * - * @param {number} courseId - * @param {UpdateCourseViewModel} [model] + * + * @param {number} courseId + * @param {UpdateCourseViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3234,7 +3234,7 @@ export const CoursesApiFactory = function (configuration?: Configuration, fetch? return CoursesApiFp(configuration).apiCoursesUpdateByCourseIdPost(courseId, model, options)(fetch, basePath); }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3252,9 +3252,9 @@ export const CoursesApiFactory = function (configuration?: Configuration, fetch? */ export class CoursesApi extends BaseAPI { /** - * - * @param {number} courseId - * @param {string} lecturerEmail + * + * @param {number} courseId + * @param {string} lecturerEmail * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CoursesApi @@ -3264,9 +3264,9 @@ export class CoursesApi extends BaseAPI { } /** - * - * @param {number} courseId - * @param {string} studentId + * + * @param {number} courseId + * @param {string} studentId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CoursesApi @@ -3276,8 +3276,8 @@ export class CoursesApi extends BaseAPI { } /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CoursesApi @@ -3287,8 +3287,8 @@ export class CoursesApi extends BaseAPI { } /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CoursesApi @@ -3298,8 +3298,8 @@ export class CoursesApi extends BaseAPI { } /** - * - * @param {CreateCourseViewModel} [model] + * + * @param {CreateCourseViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CoursesApi @@ -3309,7 +3309,7 @@ export class CoursesApi extends BaseAPI { } /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CoursesApi @@ -3319,9 +3319,9 @@ export class CoursesApi extends BaseAPI { } /** - * - * @param {number} courseId - * @param {string} studentId + * + * @param {number} courseId + * @param {string} studentId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CoursesApi @@ -3331,8 +3331,8 @@ export class CoursesApi extends BaseAPI { } /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CoursesApi @@ -3342,9 +3342,9 @@ export class CoursesApi extends BaseAPI { } /** - * - * @param {number} courseId - * @param {UpdateCourseViewModel} [model] + * + * @param {number} courseId + * @param {UpdateCourseViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CoursesApi @@ -3354,7 +3354,7 @@ export class CoursesApi extends BaseAPI { } /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CoursesApi @@ -3372,9 +3372,9 @@ export class CoursesApi extends BaseAPI { export const HomeworksApiFetchParamCreator = function (configuration?: Configuration) { return { /** - * - * @param {number} courseId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * + * @param {number} courseId + * @param {CreateHomeworkViewModel} [homeworkViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3393,8 +3393,8 @@ export const HomeworksApiFetchParamCreator = function (configuration?: Configura // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -3413,8 +3413,8 @@ export const HomeworksApiFetchParamCreator = function (configuration?: Configura }; }, /** - * - * @param {number} homeworkId + * + * @param {number} homeworkId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3433,8 +3433,8 @@ export const HomeworksApiFetchParamCreator = function (configuration?: Configura // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -3449,8 +3449,8 @@ export const HomeworksApiFetchParamCreator = function (configuration?: Configura }; }, /** - * - * @param {number} homeworkId + * + * @param {number} homeworkId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3469,8 +3469,8 @@ export const HomeworksApiFetchParamCreator = function (configuration?: Configura // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -3485,9 +3485,9 @@ export const HomeworksApiFetchParamCreator = function (configuration?: Configura }; }, /** - * - * @param {number} homeworkId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * + * @param {number} homeworkId + * @param {CreateHomeworkViewModel} [homeworkViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3506,8 +3506,8 @@ export const HomeworksApiFetchParamCreator = function (configuration?: Configura // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -3535,9 +3535,9 @@ export const HomeworksApiFetchParamCreator = function (configuration?: Configura export const HomeworksApiFp = function(configuration?: Configuration) { return { /** - * - * @param {number} courseId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * + * @param {number} courseId + * @param {CreateHomeworkViewModel} [homeworkViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3554,8 +3554,8 @@ export const HomeworksApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} homeworkId + * + * @param {number} homeworkId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3572,8 +3572,8 @@ export const HomeworksApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} homeworkId + * + * @param {number} homeworkId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3590,9 +3590,9 @@ export const HomeworksApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} homeworkId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * + * @param {number} homeworkId + * @param {CreateHomeworkViewModel} [homeworkViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3618,9 +3618,9 @@ export const HomeworksApiFp = function(configuration?: Configuration) { export const HomeworksApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) { return { /** - * - * @param {number} courseId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * + * @param {number} courseId + * @param {CreateHomeworkViewModel} [homeworkViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3628,8 +3628,8 @@ export const HomeworksApiFactory = function (configuration?: Configuration, fetc return HomeworksApiFp(configuration).apiHomeworksByCourseIdAddPost(courseId, homeworkViewModel, options)(fetch, basePath); }, /** - * - * @param {number} homeworkId + * + * @param {number} homeworkId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3637,8 +3637,8 @@ export const HomeworksApiFactory = function (configuration?: Configuration, fetc return HomeworksApiFp(configuration).apiHomeworksDeleteByHomeworkIdDelete(homeworkId, options)(fetch, basePath); }, /** - * - * @param {number} homeworkId + * + * @param {number} homeworkId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3646,9 +3646,9 @@ export const HomeworksApiFactory = function (configuration?: Configuration, fetc return HomeworksApiFp(configuration).apiHomeworksGetByHomeworkIdGet(homeworkId, options)(fetch, basePath); }, /** - * - * @param {number} homeworkId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * + * @param {number} homeworkId + * @param {CreateHomeworkViewModel} [homeworkViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3666,9 +3666,9 @@ export const HomeworksApiFactory = function (configuration?: Configuration, fetc */ export class HomeworksApi extends BaseAPI { /** - * - * @param {number} courseId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * + * @param {number} courseId + * @param {CreateHomeworkViewModel} [homeworkViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof HomeworksApi @@ -3678,8 +3678,8 @@ export class HomeworksApi extends BaseAPI { } /** - * - * @param {number} homeworkId + * + * @param {number} homeworkId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof HomeworksApi @@ -3689,8 +3689,8 @@ export class HomeworksApi extends BaseAPI { } /** - * - * @param {number} homeworkId + * + * @param {number} homeworkId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof HomeworksApi @@ -3700,9 +3700,9 @@ export class HomeworksApi extends BaseAPI { } /** - * - * @param {number} homeworkId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * + * @param {number} homeworkId + * @param {CreateHomeworkViewModel} [homeworkViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof HomeworksApi @@ -3720,7 +3720,7 @@ export class HomeworksApi extends BaseAPI { export const NotificationsApiFetchParamCreator = function (configuration?: Configuration) { return { /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3734,8 +3734,8 @@ export const NotificationsApiFetchParamCreator = function (configuration?: Confi // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -3750,8 +3750,8 @@ export const NotificationsApiFetchParamCreator = function (configuration?: Confi }; }, /** - * - * @param {Array} [notificationIds] + * + * @param {Array} [notificationIds] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3765,8 +3765,8 @@ export const NotificationsApiFetchParamCreator = function (configuration?: Confi // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -3794,7 +3794,7 @@ export const NotificationsApiFetchParamCreator = function (configuration?: Confi export const NotificationsApiFp = function(configuration?: Configuration) { return { /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3811,8 +3811,8 @@ export const NotificationsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {Array} [notificationIds] + * + * @param {Array} [notificationIds] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3838,7 +3838,7 @@ export const NotificationsApiFp = function(configuration?: Configuration) { export const NotificationsApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) { return { /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3846,8 +3846,8 @@ export const NotificationsApiFactory = function (configuration?: Configuration, return NotificationsApiFp(configuration).apiNotificationsGetGet(options)(fetch, basePath); }, /** - * - * @param {Array} [notificationIds] + * + * @param {Array} [notificationIds] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3865,7 +3865,7 @@ export const NotificationsApiFactory = function (configuration?: Configuration, */ export class NotificationsApi extends BaseAPI { /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof NotificationsApi @@ -3875,8 +3875,8 @@ export class NotificationsApi extends BaseAPI { } /** - * - * @param {Array} [notificationIds] + * + * @param {Array} [notificationIds] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof NotificationsApi @@ -3894,10 +3894,10 @@ export class NotificationsApi extends BaseAPI { export const SolutionsApiFetchParamCreator = function (configuration?: Configuration) { return { /** - * - * @param {number} taskId - * @param {number} groupId - * @param {SolutionViewModel} [model] + * + * @param {number} taskId + * @param {number} groupId + * @param {SolutionViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3921,8 +3921,8 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -3941,9 +3941,9 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura }; }, /** - * - * @param {number} groupId - * @param {number} taskId + * + * @param {number} groupId + * @param {number} taskId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -3967,8 +3967,8 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -3983,8 +3983,8 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura }; }, /** - * - * @param {number} solutionId + * + * @param {number} solutionId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4003,8 +4003,8 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -4019,9 +4019,9 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura }; }, /** - * - * @param {number} taskId - * @param {SolutionViewModel} [model] + * + * @param {number} taskId + * @param {SolutionViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4040,8 +4040,8 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -4060,8 +4060,8 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura }; }, /** - * - * @param {number} solutionId + * + * @param {number} solutionId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4080,8 +4080,8 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -4096,7 +4096,7 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura }; }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4110,8 +4110,8 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -4126,8 +4126,8 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura }; }, /** - * - * @param {number} solutionId + * + * @param {number} solutionId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4146,8 +4146,8 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -4162,10 +4162,10 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura }; }, /** - * - * @param {number} solutionId - * @param {number} newRating - * @param {string} [lecturerComment] + * + * @param {number} solutionId + * @param {number} newRating + * @param {string} [lecturerComment] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4189,8 +4189,8 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -4209,9 +4209,9 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura }; }, /** - * - * @param {number} taskId - * @param {string} studentId + * + * @param {number} taskId + * @param {string} studentId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4235,8 +4235,8 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -4260,10 +4260,10 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura export const SolutionsApiFp = function(configuration?: Configuration) { return { /** - * - * @param {number} taskId - * @param {number} groupId - * @param {SolutionViewModel} [model] + * + * @param {number} taskId + * @param {number} groupId + * @param {SolutionViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4280,9 +4280,9 @@ export const SolutionsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} groupId - * @param {number} taskId + * + * @param {number} groupId + * @param {number} taskId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4299,8 +4299,8 @@ export const SolutionsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} solutionId + * + * @param {number} solutionId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4317,9 +4317,9 @@ export const SolutionsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} taskId - * @param {SolutionViewModel} [model] + * + * @param {number} taskId + * @param {SolutionViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4336,8 +4336,8 @@ export const SolutionsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} solutionId + * + * @param {number} solutionId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4354,7 +4354,7 @@ export const SolutionsApiFp = function(configuration?: Configuration) { }; }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4371,8 +4371,8 @@ export const SolutionsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} solutionId + * + * @param {number} solutionId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4389,10 +4389,10 @@ export const SolutionsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} solutionId - * @param {number} newRating - * @param {string} [lecturerComment] + * + * @param {number} solutionId + * @param {number} newRating + * @param {string} [lecturerComment] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4409,9 +4409,9 @@ export const SolutionsApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} taskId - * @param {string} studentId + * + * @param {number} taskId + * @param {string} studentId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4437,10 +4437,10 @@ export const SolutionsApiFp = function(configuration?: Configuration) { export const SolutionsApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) { return { /** - * - * @param {number} taskId - * @param {number} groupId - * @param {SolutionViewModel} [model] + * + * @param {number} taskId + * @param {number} groupId + * @param {SolutionViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4448,9 +4448,9 @@ export const SolutionsApiFactory = function (configuration?: Configuration, fetc return SolutionsApiFp(configuration).apiSolutionsByGroupIdByTaskIdPost(taskId, groupId, model, options)(fetch, basePath); }, /** - * - * @param {number} groupId - * @param {number} taskId + * + * @param {number} groupId + * @param {number} taskId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4458,8 +4458,8 @@ export const SolutionsApiFactory = function (configuration?: Configuration, fetc return SolutionsApiFp(configuration).apiSolutionsByGroupIdTaskSolutionsByTaskIdGet(groupId, taskId, options)(fetch, basePath); }, /** - * - * @param {number} solutionId + * + * @param {number} solutionId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4467,9 +4467,9 @@ export const SolutionsApiFactory = function (configuration?: Configuration, fetc return SolutionsApiFp(configuration).apiSolutionsBySolutionIdGet(solutionId, options)(fetch, basePath); }, /** - * - * @param {number} taskId - * @param {SolutionViewModel} [model] + * + * @param {number} taskId + * @param {SolutionViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4477,8 +4477,8 @@ export const SolutionsApiFactory = function (configuration?: Configuration, fetc return SolutionsApiFp(configuration).apiSolutionsByTaskIdPost(taskId, model, options)(fetch, basePath); }, /** - * - * @param {number} solutionId + * + * @param {number} solutionId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4486,7 +4486,7 @@ export const SolutionsApiFactory = function (configuration?: Configuration, fetc return SolutionsApiFp(configuration).apiSolutionsDeleteBySolutionIdDelete(solutionId, options)(fetch, basePath); }, /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4494,8 +4494,8 @@ export const SolutionsApiFactory = function (configuration?: Configuration, fetc return SolutionsApiFp(configuration).apiSolutionsGet(options)(fetch, basePath); }, /** - * - * @param {number} solutionId + * + * @param {number} solutionId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4503,10 +4503,10 @@ export const SolutionsApiFactory = function (configuration?: Configuration, fetc return SolutionsApiFp(configuration).apiSolutionsMarkSolutionFinalBySolutionIdPost(solutionId, options)(fetch, basePath); }, /** - * - * @param {number} solutionId - * @param {number} newRating - * @param {string} [lecturerComment] + * + * @param {number} solutionId + * @param {number} newRating + * @param {string} [lecturerComment] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4514,9 +4514,9 @@ export const SolutionsApiFactory = function (configuration?: Configuration, fetc return SolutionsApiFp(configuration).apiSolutionsRateSolutionBySolutionIdByNewRatingPost(solutionId, newRating, lecturerComment, options)(fetch, basePath); }, /** - * - * @param {number} taskId - * @param {string} studentId + * + * @param {number} taskId + * @param {string} studentId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4534,10 +4534,10 @@ export const SolutionsApiFactory = function (configuration?: Configuration, fetc */ export class SolutionsApi extends BaseAPI { /** - * - * @param {number} taskId - * @param {number} groupId - * @param {SolutionViewModel} [model] + * + * @param {number} taskId + * @param {number} groupId + * @param {SolutionViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SolutionsApi @@ -4547,9 +4547,9 @@ export class SolutionsApi extends BaseAPI { } /** - * - * @param {number} groupId - * @param {number} taskId + * + * @param {number} groupId + * @param {number} taskId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SolutionsApi @@ -4559,8 +4559,8 @@ export class SolutionsApi extends BaseAPI { } /** - * - * @param {number} solutionId + * + * @param {number} solutionId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SolutionsApi @@ -4570,9 +4570,9 @@ export class SolutionsApi extends BaseAPI { } /** - * - * @param {number} taskId - * @param {SolutionViewModel} [model] + * + * @param {number} taskId + * @param {SolutionViewModel} [model] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SolutionsApi @@ -4582,8 +4582,8 @@ export class SolutionsApi extends BaseAPI { } /** - * - * @param {number} solutionId + * + * @param {number} solutionId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SolutionsApi @@ -4593,7 +4593,7 @@ export class SolutionsApi extends BaseAPI { } /** - * + * * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SolutionsApi @@ -4603,8 +4603,8 @@ export class SolutionsApi extends BaseAPI { } /** - * - * @param {number} solutionId + * + * @param {number} solutionId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SolutionsApi @@ -4614,10 +4614,10 @@ export class SolutionsApi extends BaseAPI { } /** - * - * @param {number} solutionId - * @param {number} newRating - * @param {string} [lecturerComment] + * + * @param {number} solutionId + * @param {number} newRating + * @param {string} [lecturerComment] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SolutionsApi @@ -4627,9 +4627,9 @@ export class SolutionsApi extends BaseAPI { } /** - * - * @param {number} taskId - * @param {string} studentId + * + * @param {number} taskId + * @param {string} studentId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SolutionsApi @@ -4647,8 +4647,8 @@ export class SolutionsApi extends BaseAPI { export const StatisticsApiFetchParamCreator = function (configuration?: Configuration) { return { /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4667,8 +4667,8 @@ export const StatisticsApiFetchParamCreator = function (configuration?: Configur // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -4692,8 +4692,8 @@ export const StatisticsApiFetchParamCreator = function (configuration?: Configur export const StatisticsApiFp = function(configuration?: Configuration) { return { /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4719,8 +4719,8 @@ export const StatisticsApiFp = function(configuration?: Configuration) { export const StatisticsApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) { return { /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4738,8 +4738,8 @@ export const StatisticsApiFactory = function (configuration?: Configuration, fet */ export class StatisticsApi extends BaseAPI { /** - * - * @param {number} courseId + * + * @param {number} courseId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StatisticsApi @@ -4757,9 +4757,9 @@ export class StatisticsApi extends BaseAPI { export const TasksApiFetchParamCreator = function (configuration?: Configuration) { return { /** - * - * @param {number} homeworkId - * @param {CreateTaskViewModel} [taskViewModel] + * + * @param {number} homeworkId + * @param {CreateTaskViewModel} [taskViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4778,8 +4778,8 @@ export const TasksApiFetchParamCreator = function (configuration?: Configuration // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -4798,8 +4798,8 @@ export const TasksApiFetchParamCreator = function (configuration?: Configuration }; }, /** - * - * @param {number} taskId + * + * @param {number} taskId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4818,8 +4818,8 @@ export const TasksApiFetchParamCreator = function (configuration?: Configuration // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -4834,8 +4834,8 @@ export const TasksApiFetchParamCreator = function (configuration?: Configuration }; }, /** - * - * @param {number} taskId + * + * @param {number} taskId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4854,8 +4854,8 @@ export const TasksApiFetchParamCreator = function (configuration?: Configuration // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -4870,9 +4870,9 @@ export const TasksApiFetchParamCreator = function (configuration?: Configuration }; }, /** - * - * @param {number} taskId - * @param {CreateTaskViewModel} [taskViewModel] + * + * @param {number} taskId + * @param {CreateTaskViewModel} [taskViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4891,8 +4891,8 @@ export const TasksApiFetchParamCreator = function (configuration?: Configuration // authentication Bearer required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("Authorization") - : configuration.apiKey; + ? configuration.apiKey("Authorization") + : configuration.apiKey; localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } @@ -4920,9 +4920,9 @@ export const TasksApiFetchParamCreator = function (configuration?: Configuration export const TasksApiFp = function(configuration?: Configuration) { return { /** - * - * @param {number} homeworkId - * @param {CreateTaskViewModel} [taskViewModel] + * + * @param {number} homeworkId + * @param {CreateTaskViewModel} [taskViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4939,8 +4939,8 @@ export const TasksApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} taskId + * + * @param {number} taskId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4957,8 +4957,8 @@ export const TasksApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} taskId + * + * @param {number} taskId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -4975,9 +4975,9 @@ export const TasksApiFp = function(configuration?: Configuration) { }; }, /** - * - * @param {number} taskId - * @param {CreateTaskViewModel} [taskViewModel] + * + * @param {number} taskId + * @param {CreateTaskViewModel} [taskViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -5003,9 +5003,9 @@ export const TasksApiFp = function(configuration?: Configuration) { export const TasksApiFactory = function (configuration?: Configuration, fetch?: FetchAPI, basePath?: string) { return { /** - * - * @param {number} homeworkId - * @param {CreateTaskViewModel} [taskViewModel] + * + * @param {number} homeworkId + * @param {CreateTaskViewModel} [taskViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -5013,8 +5013,8 @@ export const TasksApiFactory = function (configuration?: Configuration, fetch?: return TasksApiFp(configuration).apiTasksAddByHomeworkIdPost(homeworkId, taskViewModel, options)(fetch, basePath); }, /** - * - * @param {number} taskId + * + * @param {number} taskId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -5022,8 +5022,8 @@ export const TasksApiFactory = function (configuration?: Configuration, fetch?: return TasksApiFp(configuration).apiTasksDeleteByTaskIdDelete(taskId, options)(fetch, basePath); }, /** - * - * @param {number} taskId + * + * @param {number} taskId * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -5031,9 +5031,9 @@ export const TasksApiFactory = function (configuration?: Configuration, fetch?: return TasksApiFp(configuration).apiTasksGetByTaskIdGet(taskId, options)(fetch, basePath); }, /** - * - * @param {number} taskId - * @param {CreateTaskViewModel} [taskViewModel] + * + * @param {number} taskId + * @param {CreateTaskViewModel} [taskViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} */ @@ -5051,9 +5051,9 @@ export const TasksApiFactory = function (configuration?: Configuration, fetch?: */ export class TasksApi extends BaseAPI { /** - * - * @param {number} homeworkId - * @param {CreateTaskViewModel} [taskViewModel] + * + * @param {number} homeworkId + * @param {CreateTaskViewModel} [taskViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TasksApi @@ -5063,8 +5063,8 @@ export class TasksApi extends BaseAPI { } /** - * - * @param {number} taskId + * + * @param {number} taskId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TasksApi @@ -5074,8 +5074,8 @@ export class TasksApi extends BaseAPI { } /** - * - * @param {number} taskId + * + * @param {number} taskId * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TasksApi @@ -5085,9 +5085,9 @@ export class TasksApi extends BaseAPI { } /** - * - * @param {number} taskId - * @param {CreateTaskViewModel} [taskViewModel] + * + * @param {number} taskId + * @param {CreateTaskViewModel} [taskViewModel] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TasksApi diff --git a/hwproj.front/src/components/Auth/Login.tsx b/hwproj.front/src/components/Auth/Login.tsx index 0db4369d1..fe23ab841 100644 --- a/hwproj.front/src/components/Auth/Login.tsx +++ b/hwproj.front/src/components/Auth/Login.tsx @@ -209,4 +209,4 @@ const Login: FC = (props) => { ) } -export default Login +export default Login \ No newline at end of file diff --git a/hwproj.front/src/components/Profile.tsx b/hwproj.front/src/components/Profile.tsx index aad1d513d..c3e97e8d3 100644 --- a/hwproj.front/src/components/Profile.tsx +++ b/hwproj.front/src/components/Profile.tsx @@ -11,9 +11,14 @@ import ApiSingleton from "api/ApiSingleton"; import { AccountDataDto, NotificationViewModel } from "../api/"; import "./Styles/Profile.css"; import parse from 'html-react-parser'; -import {ChangeEvent, FC, useEffect, useState} from "react"; +import {ChangeEvent, Component, FC, useEffect, useState} from "react"; import {Redirect} from "react-router-dom"; import {makeStyles} from "@material-ui/styles"; +import Image from 'material-ui-image' +import telegramLogo from './tlgm.png' +import "./Styles/telegram.css"; +import {GoogleLoginButton} from "react-social-login-buttons"; +import {TelegramLoginButton} from "react-social-login-buttons"; interface IProfileState { isLoaded: boolean; @@ -116,6 +121,7 @@ const Profile: FC> = (props) => { } if (profileState.isLoaded) { + const hrefLink = "https://t.me/HwProjBot?start=>" + accountState.email; const fullName = accountState.middleName && accountState.surname ? accountState.name + ' ' + accountState.middleName + ' ' + accountState.surname : accountState.surname @@ -128,10 +134,24 @@ const Profile: FC> = (props) => { {fullName} + alert("Hello")}> + + Попробуйте бота + + {accountState.email} + + + + {!props.match.params.id &&
diff --git a/hwproj.front/src/components/Styles/telegram.css b/hwproj.front/src/components/Styles/telegram.css new file mode 100644 index 000000000..a90cf303d --- /dev/null +++ b/hwproj.front/src/components/Styles/telegram.css @@ -0,0 +1,4 @@ +.telegram { + height: 25px; + width: 25px; +} \ No newline at end of file From be3a522a994ce09c95f4840374edd242395bff16 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Tue, 23 Nov 2021 01:20:44 +0300 Subject: [PATCH 02/19] add new commands --- .../Controllers/HomeworksController.cs | 14 +--- .../Services/HomeworksService.cs | 2 +- .../Services/IHomeworksService.cs | 2 +- .../ConfirmTelegramBotEventHandler.cs | 1 + .../Commands/CommandNames.cs | 12 ++- .../Commands/GetCourses.cs | 3 +- .../Commands/GetHomeworks.cs | 22 ++++-- .../Commands/GetSolution.cs | 78 +++++++++++++++++++ .../Commands/GetSolutionInfo.cs | 68 ++++++++++++++++ .../Commands/GetTaskInfo.cs | 77 ++++++++++++++++++ .../Commands/GetTasks.cs | 74 ++++++++++++++++++ .../Commands/StartCommand.cs | 22 ++---- .../Controllers/TelegramBotController.cs | 1 - .../Events/ConfirmTelegramBotEvent.cs | 2 +- .../Models/TelegramUserModel.cs | 4 +- .../Repositories/ITelegramBotRepository.cs | 7 -- .../Repositories/TelegramBotRepository.cs | 10 --- .../Service/CommandService.cs | 27 +++++-- .../Service/UserService.cs | 5 -- 19 files changed, 354 insertions(+), 77 deletions(-) create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolution.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutionInfo.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTaskInfo.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTasks.cs delete mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/ITelegramBotRepository.cs delete mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/TelegramBotRepository.cs diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/HomeworksController.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/HomeworksController.cs index 0f67a4819..19bde6b6a 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/HomeworksController.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/HomeworksController.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; using AutoMapper; using HwProj.CoursesService.API.Models; @@ -40,17 +41,10 @@ public async Task GetHomework(long homeworkId) } [HttpGet("{courseId}/getAll")] - public async Task GetAllHomeworkFromCourse(long courseId) + public async Task GetAllHomeworkFromCourse(long courseId) { - var homeworkFromDb = await _homeworksService.GetAllHomeworkFromCourse(courseId); - List hwList = null; - foreach (var hw in homeworkFromDb) - { - var homework = _mapper.Map(hw); - homework.Tasks.ForEach(t => t.PutPossibilityForSendingSolution()); - hwList.Add(homework); - } - return hwList?.ToArray(); + var homeworkFromDb = await _homeworksService.GetAllHomeworkFromCourseAsync(courseId); + return homeworkFromDb.ToArray(); } [HttpDelete("delete/{homeworkId}")] diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs index 83f763948..8d41bee08 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs @@ -40,7 +40,7 @@ public async Task GetHomeworkAsync(long homeworkId) return await _homeworksRepository.GetWithTasksAsync(homeworkId); } - public async Task GetAllHomeworkFromCourse(long courseId) + public async Task GetAllHomeworkFromCourseAsync(long courseId) { return await _homeworksRepository.GetAllWithTasksByCourseAsync(courseId); } diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/IHomeworksService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/IHomeworksService.cs index 54a22f163..06f47f958 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/IHomeworksService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/IHomeworksService.cs @@ -9,7 +9,7 @@ public interface IHomeworksService Task GetHomeworkAsync(long homeworkId); - Task GetAllHomeworkFromCourse(long courseId); + Task GetAllHomeworkFromCourseAsync(long courseId); Task DeleteHomeworkAsync(long homeworkId); diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs index 8852468ff..de42414e9 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs @@ -4,6 +4,7 @@ using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; using HwProj.TelegramBotAPI; +using HwProj.TelegramBotAPI.Events; namespace HwProj.NotificationsService.API.EventHandlers { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs index 10bbf959d..8c36658c3 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs @@ -1,9 +1,13 @@ -namespace HwProj.TelegramBotAPI +namespace HwProj.TelegramBotAPI.Commands { - public class CommandNames + public static class CommandNames { public const string StartCommand = "/start"; - public const string GetCourses = "/courses"; - public const string GetHomeworks = "/homeworks"; + public const string GetCourses = "/courses"; // /courses {courseId} + public const string GetHomeworks = "/homeworks"; // /homeworks {homeworkId} + public const string GetTasks = "/task"; // /task {taskId} + public const string GetTaskInfo = "/taskinfo"; // /taskinfo + public const string GetSolutions = "/solutions"; // /solutions {taskId} + public const string GetSolutionInfo = "/solutioninfo"; // /solutioninfo {solutionId} } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetCourses.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetCourses.cs index 8d2bee8d5..f96f1a7c2 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetCourses.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetCourses.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.Threading.Tasks; -using HwProj.CoursesService.API.Services; using HwProj.CoursesService.Client; using HwProj.TelegramBotAPI.Service; using Telegram.Bot; @@ -35,7 +34,7 @@ public override async Task ExecuteAsync(Update update) { var k = new InlineKeyboardButton { - Text = $"/homeworks {courses[i - 1].Id}", + Text = courses[i - 1].Name, CallbackData = $"/homeworks {courses[i - 1].Id}" }; cols.Add(k); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetHomeworks.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetHomeworks.cs index 3bb19bd73..45c663874 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetHomeworks.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetHomeworks.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using HwProj.CoursesService.API.Repositories; using HwProj.CoursesService.Client; using HwProj.TelegramBotAPI.Service; using Telegram.Bot; @@ -31,28 +30,35 @@ public override async Task ExecuteAsync(Update update) var message = update.CallbackQuery.Data; var text = message.Split(' '); var homeworks = _coursesServiceClient.GetAllHomeworkByCourse(Int32.Parse(text[1])).Result; - + var rows = new List(); var cols = new List(); for (var i = 1; i < homeworks.Length + 1; i++) { - var k = new InlineKeyboardButton - { - Text = homeworks[i - 1].Title, - CallbackData = $"/homeworks " - }; + var k = GetButton(homeworks[i - 1].Title, $"/task {homeworks[i - 1].Id}"); cols.Add(k); if (i % 3 != 0) continue; rows.Add(cols.ToArray()); cols = new List(); } - if (homeworks.Length < 3) { rows.Add(cols.ToArray()); } + + var button = GetButton("Мои курсы", $"/courses"); + cols = new List(); + cols.Add(button); + rows.Add(cols.ToArray()); var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); await _botClient.SendTextMessageAsync(user.ChatId, "Выберите homework:", replyMarkup:keyboardMarkup); } + + private InlineKeyboardButton GetButton(string text, string callbackData) + => new InlineKeyboardButton + { + Text = text, + CallbackData = callbackData + }; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolution.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolution.cs new file mode 100644 index 000000000..feb1d3189 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolution.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Net.Mime; +using System.Threading.Tasks; +using HwProj.CoursesService.Client; +using HwProj.SolutionsService.Client; +using HwProj.TelegramBotAPI.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; +using Telegram.Bot.Types.ReplyMarkups; + +namespace HwProj.TelegramBotAPI.Commands +{ + public class GetSolution: Commands + { + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + private readonly SolutionsServiceClient _solutionsServiceClient; + private readonly CoursesServiceClient _coursesServiceClient; + + public GetSolution(TelegramBot telegramBot, IUserService userService, SolutionsServiceClient solutionsServiceClient, CoursesServiceClient coursesServiceClient) + { + _botClient = telegramBot.GetBot().Result; + _userService = userService; + _solutionsServiceClient = solutionsServiceClient; + _coursesServiceClient = coursesServiceClient; + } + + public override string Name => CommandNames.GetSolutions; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.GetOrCreateChatId(update); + var message = update.CallbackQuery.Data; + var text = message.Split(' '); + var solutions = _solutionsServiceClient.GetUserSolution(Int32.Parse(text[1]), user.StudentId).Result; + var task = _coursesServiceClient.GetTask(Int32.Parse(text[1])).Result; + var hw = _coursesServiceClient.GetHomework(task.HomeworkId).Result; + + var rows = new List(); + var cols = new List(); + for (var i = 1; i < solutions.Length + 1; i++) + { + var k = GetButton($"Попытка {i}", $"/solutioninfo {solutions[i - 1].Id}"); + cols.Add(k); + if (i % 3 != 0) continue; + rows.Add(cols.ToArray()); + cols = new List(); + } + + if (solutions.Length < 3) + { + rows.Add(cols.ToArray()); + } + var button = GetButton("Мои курсы", $"/courses"); + cols.Add(button); + button = GetButton("Мои домашки", $"/homeworks {hw.CourseId}"); + cols.Add(button); + rows.Add(cols.ToArray()); + cols = new List(); + button = GetButton("Мои задачи", $"/task {task.HomeworkId}"); + cols.Add(button); + rows.Add(cols.ToArray()); + + var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); + + await _botClient.SendTextMessageAsync(user.ChatId, "", ParseMode.Markdown, replyMarkup:keyboardMarkup); + } + + private InlineKeyboardButton GetButton(string text, string callbackData) + => new InlineKeyboardButton + { + Text = text, + CallbackData = callbackData + }; + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutionInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutionInfo.cs new file mode 100644 index 000000000..d4969952e --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutionInfo.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using HwProj.CoursesService.Client; +using HwProj.Models.CoursesService.ViewModels; +using HwProj.SolutionsService.Client; +using HwProj.TelegramBotAPI.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.ReplyMarkups; + +namespace HwProj.TelegramBotAPI.Commands +{ + public class GetSolutionInfo : Commands + { + private readonly ISolutionsServiceClient _solutionsServiceClient; + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + + public GetSolutionInfo(TelegramBot telegramBot, ISolutionsServiceClient solutionsServiceClient, + IUserService userService) + { + _botClient = telegramBot.GetBot().Result; + _solutionsServiceClient = solutionsServiceClient; + _userService = userService; + } + + public override string Name => CommandNames.GetSolutionInfo; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.GetOrCreateChatId(update); + var message = update.CallbackQuery.Data; + var text = message.Split(' '); + var solution = _solutionsServiceClient.GetSolutionById(Int32.Parse(text[1])).Result; + + + var rows = new List(); + var cols = new List(); + var button = GetButton("Мои курсы", $"/courses"); + cols.Add(button); + /*button = GetButton("Мои домашки", $"/homeworks {hw.CourseId}"); + cols.Add(button); + rows.Add(cols.ToArray()); + cols = new List(); + button = GetButton("Мои задачи", $"/task {task.HomeworkId}"); + cols.Add(button); + button = GetButton($"Решения {task.Title}", $"/solutions {task.Id}"); + cols.Add(button); + rows.Add(cols.ToArray());*/ + + var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); + + await _botClient.SendTextMessageAsync(user.ChatId, + $"Отзыв преподователя: {solution.LecturerComment}." + + $"\nОценка: {solution.Rating}." + + $"\nGithub: {solution.GithubUrl}.", + replyMarkup:keyboardMarkup); + } + + private InlineKeyboardButton GetButton(string text, string callbackData) + => new InlineKeyboardButton + { + Text = text, + CallbackData = callbackData + }; + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTaskInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTaskInfo.cs new file mode 100644 index 000000000..b94438182 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTaskInfo.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using HwProj.CoursesService.Client; +using HwProj.Models.CoursesService.ViewModels; +using HwProj.TelegramBotAPI.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.ReplyMarkups; + +namespace HwProj.TelegramBotAPI.Commands +{ + public class GetTaskInfo : Commands + { + private readonly ICoursesServiceClient _coursesServiceClient; + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + + public GetTaskInfo(TelegramBot telegramBot, ICoursesServiceClient coursesServiceClient, + IUserService userService) + { + _botClient = telegramBot.GetBot().Result; + _coursesServiceClient = coursesServiceClient; + _userService = userService; + } + + public override string Name => CommandNames.GetTaskInfo; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.GetOrCreateChatId(update); + var message = update.CallbackQuery.Data; + var text = message.Split(' '); + var hw = _coursesServiceClient.GetHomework(Int32.Parse(text[1])).Result; + var tasks = hw.Tasks.ToArray(); + HomeworkTaskViewModel task = null; + foreach (var t in tasks) + { + if (t.Id == Int32.Parse(text[1])) + { + task = t; + } + } + + var rows = new List(); + var cols = new List(); + var button = GetButton("Мои курсы", $"/courses"); + cols.Add(button); + button = GetButton("Мои домашки", $"/homeworks {hw.CourseId}"); + cols.Add(button); + rows.Add(cols.ToArray()); + cols = new List(); + button = GetButton("Мои задачи", $"/task {task.HomeworkId}"); + cols.Add(button); + button = GetButton($"Решения {task.Title}", $"/solutions {task.Id}"); + cols.Add(button); + rows.Add(cols.ToArray()); + + var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); + + await _botClient.SendTextMessageAsync(user.ChatId, + $"Название: {task.Title}." + + $"\nОписание: {task.Description}." + + $"\nДата публикации: {task.PublicationDate}." + + $"\nДедлайн: {task.DeadlineDate}." + + $"\nМаксимальный балл: {task.MaxRating}.", + replyMarkup:keyboardMarkup); + } + + private InlineKeyboardButton GetButton(string text, string callbackData) + => new InlineKeyboardButton + { + Text = text, + CallbackData = callbackData + }; + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTasks.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTasks.cs new file mode 100644 index 000000000..1e67e7081 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTasks.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using HwProj.CoursesService.Client; +using HwProj.TelegramBotAPI.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.ReplyMarkups; + +namespace HwProj.TelegramBotAPI.Commands +{ + public class GetTasks : Commands + { + private readonly ICoursesServiceClient _coursesServiceClient; + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + + public GetTasks(TelegramBot telegramBot, ICoursesServiceClient coursesServiceClient, + IUserService userService) + { + _botClient = telegramBot.GetBot().Result; + _coursesServiceClient = coursesServiceClient; + _userService = userService; + } + + public override string Name => CommandNames.GetTasks; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.GetOrCreateChatId(update); + var message = update.CallbackQuery.Data; + var text = message.Split(' '); + var hw = _coursesServiceClient.GetHomework(Int32.Parse(text[1])).Result; + var tasks = hw.Tasks.ToArray(); + var rows = new List(); + var cols = new List(); + for (var i = 1; i < tasks.Length + 1; i++) + { + var k = new InlineKeyboardButton + { + Text = tasks[i - 1].Title, + CallbackData = $"/tasks {tasks[i - 1].Id}" + }; + cols.Add(k); + if (i % 3 != 0) continue; + rows.Add(cols.ToArray()); + cols = new List(); + } + + if (tasks.Length < 3) + { + rows.Add(cols.ToArray()); + } + + var button = new InlineKeyboardButton + { + Text = "Мои курсы", + CallbackData = $"/courses" + }; + cols = new List(); + cols.Add(button); + button = new InlineKeyboardButton + { + Text = "Мои домашки", + CallbackData = $"/homeworks {hw.CourseId}" + }; + cols.Add(button); + rows.Add(cols.ToArray()); + + var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); + await _botClient.SendTextMessageAsync(user.ChatId, "Выберите task:", replyMarkup:keyboardMarkup); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/StartCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/StartCommand.cs index 02cffd533..c736dad91 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/StartCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/StartCommand.cs @@ -23,26 +23,14 @@ public StartCommand(TelegramBot telegramBot, IUserService userService) public override async Task ExecuteAsync(Update update) { var user = await _userService.GetOrCreateChatId(update); - - var inlineKeyboard = new InlineKeyboardMarkup(new[] + + var inlineKeyboard = new InlineKeyboardMarkup(new InlineKeyboardButton { - new[] - { - new InlineKeyboardButton() - { - Text = "Мои курсы", - CallbackData = "/courses" - }, - new InlineKeyboardButton() - { - Text = "/homeworks" - } - } + Text = "Мои курсы", + CallbackData = "/courses" }); - await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!", - ParseMode.Markdown, replyMarkup:inlineKeyboard); - + await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!", ParseMode.Markdown, replyMarkup:inlineKeyboard); } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Controllers/TelegramBotController.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Controllers/TelegramBotController.cs index 2d7259ea9..17293c4cb 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Controllers/TelegramBotController.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Controllers/TelegramBotController.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using HwProj.TelegramBotAPI.Service; using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; using Telegram.Bot.Types; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Events/ConfirmTelegramBotEvent.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Events/ConfirmTelegramBotEvent.cs index 44a9f16ad..69c1b1205 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Events/ConfirmTelegramBotEvent.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Events/ConfirmTelegramBotEvent.cs @@ -1,7 +1,7 @@ using HwProj.EventBus.Client; using HwProj.TelegramBotAPI.Models; -namespace HwProj.TelegramBotAPI +namespace HwProj.TelegramBotAPI.Events { public class ConfirmTelegramBotEvent : Event { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramUserModel.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramUserModel.cs index 9e6edd09d..1f51012b0 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramUserModel.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramUserModel.cs @@ -1,6 +1,4 @@ -using HwProj.Repositories; - -namespace HwProj.TelegramBotAPI.Models +namespace HwProj.TelegramBotAPI.Models { public class TelegramUserModel { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/ITelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/ITelegramBotRepository.cs deleted file mode 100644 index 924b4657a..000000000 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/ITelegramBotRepository.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace HwProj.TelegramBotAPI.Repositories -{ - public interface ITelegramBotRepository - { - - } -} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/TelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/TelegramBotRepository.cs deleted file mode 100644 index a4e4956e2..000000000 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Repositories/TelegramBotRepository.cs +++ /dev/null @@ -1,10 +0,0 @@ -using HwProj.Repositories; -using HwProj.TelegramBotAPI.Models; - -namespace HwProj.TelegramBotAPI.Repositories -{ - /*public class TelegramBotRepository: ICrudRepository - { - - }*/ -} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/CommandService.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/CommandService.cs index 7f3039651..ed6aed8ee 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/CommandService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/CommandService.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using HwProj.TelegramBotAPI.Commands; using Microsoft.Extensions.DependencyInjection; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; @@ -37,20 +38,32 @@ public async Task Execute(Update update) { case "/start": await ExecuteCommand(CommandNames.StartCommand, update); - break; - case "/courses": + break; + /*case "/courses": await ExecuteCommand(CommandNames.GetCourses, update); - break; + break; case "/homeworks": await ExecuteCommand(CommandNames.GetHomeworks, update); - break; + break;*/ } } - switch (update.CallbackQuery.Data.Split(' ')[0]) + else { - case "/homeworks": - await ExecuteCommand(CommandNames.GetHomeworks, update); + switch (update.CallbackQuery.Data.Split(' ')[0]) + { + case "/courses": + await ExecuteCommand(CommandNames.GetCourses, update); break; + case "/homeworks": + await ExecuteCommand(CommandNames.GetHomeworks, update); + break; + case "/task": + await ExecuteCommand(CommandNames.GetTasks, update); + break; + case "/taskinfo": + await ExecuteCommand(CommandNames.GetTaskInfo, update); + break; + } } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/UserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/UserService.cs index b339f53d0..551450aba 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/UserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/UserService.cs @@ -4,7 +4,6 @@ using HwProj.TelegramBotAPI.Models; using Microsoft.EntityFrameworkCore; using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; namespace HwProj.TelegramBotAPI.Service { @@ -31,10 +30,6 @@ public async Task GetOrCreateChatId(Update update) { studentId= _authClient.FindByEmailAsync(text[1]).Result; } - else if (text[0] == "/start" && text.Length == 1) - { - throw new Exception(); - } else { studentId = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result.StudentId; From 32a298017658c81e5aa39bc8103e2e707a010879 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Wed, 24 Nov 2021 00:58:50 +0300 Subject: [PATCH 03/19] add commands --- .../HwProj.TelegramBot.Client.csproj | 15 +++++ .../Commands/CommandNames.cs | 2 +- .../Commands/GetSolutionInfo.cs | 18 +++--- .../{GetSolution.cs => GetSolutions.cs} | 5 +- .../Commands/GetTaskInfo.cs | 2 +- .../Commands/GetTasks.cs | 2 +- .../HwProj.TelegramBotAPI.csproj | 26 +++++++++ .../HwProj.TelegramBotAPI/Program.cs | 17 ++++++ .../Properties/launchSettings.json | 31 ++++++++++ .../Service/TelegramBot.cs | 32 ++++++++++ .../HwProj.TelegramBotAPI/Startup.cs | 58 +++++++++++++++++++ .../appsettings.Development.json | 9 +++ .../HwProj.TelegramBotAPI/appsettings.json | 21 +++++++ 13 files changed, 225 insertions(+), 13 deletions(-) create mode 100644 HwProj.TelegramBot/HwProj.TelegramBot.Client/HwProj.TelegramBot.Client.csproj rename HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/{GetSolution.cs => GetSolutions.cs} (92%) create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/HwProj.TelegramBotAPI.csproj create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Program.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Properties/launchSettings.json create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/TelegramBot.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Startup.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/appsettings.Development.json create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/appsettings.json diff --git a/HwProj.TelegramBot/HwProj.TelegramBot.Client/HwProj.TelegramBot.Client.csproj b/HwProj.TelegramBot/HwProj.TelegramBot.Client/HwProj.TelegramBot.Client.csproj new file mode 100644 index 000000000..129f97004 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBot.Client/HwProj.TelegramBot.Client.csproj @@ -0,0 +1,15 @@ + + + + netcoreapp2.2 + + + + + + + + + + + diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs index 8c36658c3..1202cb106 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs @@ -6,7 +6,7 @@ public static class CommandNames public const string GetCourses = "/courses"; // /courses {courseId} public const string GetHomeworks = "/homeworks"; // /homeworks {homeworkId} public const string GetTasks = "/task"; // /task {taskId} - public const string GetTaskInfo = "/taskinfo"; // /taskinfo + public const string GetTaskInfo = "/taskinfo"; // /taskinfo {taskId} public const string GetSolutions = "/solutions"; // /solutions {taskId} public const string GetSolutionInfo = "/solutioninfo"; // /solutioninfo {solutionId} } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutionInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutionInfo.cs index d4969952e..6d93301bc 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutionInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutionInfo.cs @@ -14,18 +14,20 @@ namespace HwProj.TelegramBotAPI.Commands public class GetSolutionInfo : Commands { private readonly ISolutionsServiceClient _solutionsServiceClient; + private readonly ICoursesServiceClient _coursesServiceClient; private readonly TelegramBotClient _botClient; private readonly IUserService _userService; public GetSolutionInfo(TelegramBot telegramBot, ISolutionsServiceClient solutionsServiceClient, - IUserService userService) + IUserService userService, ICoursesServiceClient coursesServiceClient) { _botClient = telegramBot.GetBot().Result; _solutionsServiceClient = solutionsServiceClient; _userService = userService; + _coursesServiceClient = coursesServiceClient; } - public override string Name => CommandNames.GetSolutionInfo; + public override string Name => CommandNames.GetSolutionInfo; public override async Task ExecuteAsync(Update update) { @@ -33,13 +35,15 @@ public override async Task ExecuteAsync(Update update) var message = update.CallbackQuery.Data; var text = message.Split(' '); var solution = _solutionsServiceClient.GetSolutionById(Int32.Parse(text[1])).Result; - - + var task = _coursesServiceClient.GetTask(solution.TaskId).Result; + var hw = _coursesServiceClient.GetHomework(task.HomeworkId).Result; + var rows = new List(); var cols = new List(); + var button = GetButton("Мои курсы", $"/courses"); cols.Add(button); - /*button = GetButton("Мои домашки", $"/homeworks {hw.CourseId}"); + button = GetButton("Мои домашки", $"/homeworks {hw.CourseId}"); cols.Add(button); rows.Add(cols.ToArray()); cols = new List(); @@ -47,14 +51,14 @@ public override async Task ExecuteAsync(Update update) cols.Add(button); button = GetButton($"Решения {task.Title}", $"/solutions {task.Id}"); cols.Add(button); - rows.Add(cols.ToArray());*/ + rows.Add(cols.ToArray()); var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); await _botClient.SendTextMessageAsync(user.ChatId, $"Отзыв преподователя: {solution.LecturerComment}." + $"\nОценка: {solution.Rating}." + - $"\nGithub: {solution.GithubUrl}.", + $"\nGithub: ссылка", replyMarkup:keyboardMarkup); } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolution.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutions.cs similarity index 92% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolution.cs rename to HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutions.cs index feb1d3189..82a0e9c8a 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolution.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutions.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Net.Mime; using System.Threading.Tasks; using HwProj.CoursesService.Client; using HwProj.SolutionsService.Client; @@ -12,14 +11,14 @@ namespace HwProj.TelegramBotAPI.Commands { - public class GetSolution: Commands + public class GetSolutions: Commands { private readonly TelegramBotClient _botClient; private readonly IUserService _userService; private readonly SolutionsServiceClient _solutionsServiceClient; private readonly CoursesServiceClient _coursesServiceClient; - public GetSolution(TelegramBot telegramBot, IUserService userService, SolutionsServiceClient solutionsServiceClient, CoursesServiceClient coursesServiceClient) + public GetSolutions(TelegramBot telegramBot, IUserService userService, SolutionsServiceClient solutionsServiceClient, CoursesServiceClient coursesServiceClient) { _botClient = telegramBot.GetBot().Result; _userService = userService; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTaskInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTaskInfo.cs index b94438182..a6f605115 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTaskInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTaskInfo.cs @@ -31,7 +31,7 @@ public override async Task ExecuteAsync(Update update) var user = await _userService.GetOrCreateChatId(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); - var hw = _coursesServiceClient.GetHomework(Int32.Parse(text[1])).Result; + var hw = _coursesServiceClient.GetHomework(Int32.Parse(text[1])).Result; //// var tasks = hw.Tasks.ToArray(); HomeworkTaskViewModel task = null; foreach (var t in tasks) diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTasks.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTasks.cs index 1e67e7081..e60fefa22 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTasks.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTasks.cs @@ -39,7 +39,7 @@ public override async Task ExecuteAsync(Update update) var k = new InlineKeyboardButton { Text = tasks[i - 1].Title, - CallbackData = $"/tasks {tasks[i - 1].Id}" + CallbackData = $"/taskinfo {tasks[i - 1].Id}" }; cols.Add(k); if (i % 3 != 0) continue; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/HwProj.TelegramBotAPI.csproj b/HwProj.TelegramBot/HwProj.TelegramBotAPI/HwProj.TelegramBotAPI.csproj new file mode 100644 index 000000000..77660f465 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/HwProj.TelegramBotAPI.csproj @@ -0,0 +1,26 @@ + + + + netcoreapp2.2 + Windows + latest + + + + + + + + + + + + + + + + + + + + diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Program.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Program.cs new file mode 100644 index 000000000..491d0e831 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Program.cs @@ -0,0 +1,17 @@ +using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Hosting; + +namespace HwProj.TelegramBotAPI +{ + public class Program + { + public static void Main(string[] args) + { + CreateWebHostBuilder(args).Build().Run(); + } + + public static IWebHostBuilder CreateWebHostBuilder(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup(); + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Properties/launchSettings.json b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Properties/launchSettings.json new file mode 100644 index 000000000..40af5352c --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:1307", + "sslPort": 44300 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "HwProj.TelegramBotAPI": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + + "applicationUrl": "http://localhost:5009", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/TelegramBot.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/TelegramBot.cs new file mode 100644 index 000000000..79ae1ccba --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/TelegramBot.cs @@ -0,0 +1,32 @@ +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using Telegram.Bot; + +namespace HwProj.TelegramBotAPI.Service +{ + public class TelegramBot + { + private readonly IConfiguration _configuration; + private TelegramBotClient _botClient; + + public TelegramBot(IConfiguration configuration) + { + _configuration = configuration; + } + + public async Task GetBot() + { + if (_botClient != null) + { + return _botClient; + } + + _botClient = new TelegramBotClient(_configuration["Token"]); + + var hook = $"{_configuration["Url"]}api/message/update"; + await _botClient.SetWebhookAsync(hook); + + return _botClient; + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Startup.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Startup.cs new file mode 100644 index 000000000..1e95c3ce1 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Startup.cs @@ -0,0 +1,58 @@ +using System; +using System.Net.Http; +using HwProj.AuthService.Client; +using HwProj.CoursesService.Client; +using HwProj.SolutionsService.Client; +using HwProj.TelegramBotAPI.Commands; +using HwProj.TelegramBotAPI.Models; +using HwProj.TelegramBotAPI.Service; +using HwProj.Utils.Configuration; +using Microsoft.AspNetCore.Builder; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment; + +namespace HwProj.TelegramBotAPI +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + public void ConfigureServices(IServiceCollection services) + { + /*services.AddControllers();*/ + var connectionString = Configuration.GetConnectionString("DefaultConnection"); + services.AddDbContext(options => options.UseSqlServer(connectionString)); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + + var httpClient = new HttpClient(); + services.AddAuthServiceClient(httpClient, "http://localhost:5001"); + services.AddCoursesServiceClient(httpClient, "http://localhost:5002"); + services.AddSolutionServiceClient(httpClient, "http://localhost:5007"); + + services.AddEventBus(Configuration); + services.ConfigureHwProjServices("Telegram API"); + } + + public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) + { + app.ConfigureHwProj(env, "Telegram API"); + serviceProvider.GetRequiredService().GetBot().Wait(); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/appsettings.Development.json b/HwProj.TelegramBot/HwProj.TelegramBotAPI/appsettings.Development.json new file mode 100644 index 000000000..8983e0fc1 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/appsettings.json b/HwProj.TelegramBot/HwProj.TelegramBotAPI/appsettings.json new file mode 100644 index 000000000..304d460a5 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotAPI/appsettings.json @@ -0,0 +1,21 @@ +{ + "ConnectionStrings": { + "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=TelegramBotServiceDB;Trusted_Connection=True;" + }, + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*", + "EventBus": { + "EventBusHostName": "localhost", + "EventBusUserName": "guest", + "EventBusPassword": "guest", + "EventBusVirtualHost": "/", + "EventBusQueueName": "TelegramBot", + "EventBusRetryCount": "5" + }, + "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", + "Url" : "https://2c28-92-42-26-35.ngrok.io/" +} \ No newline at end of file From 2c674fe0c21f00a3ee26ab3d8724b4c6cdca9970 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Wed, 24 Nov 2021 14:16:41 +0300 Subject: [PATCH 04/19] add send Notification to telegram --- .../ConfirmTelegramBotEventHandler.cs | 4 +-- .../EventHandlers/EditProfileEventHandler.cs | 13 +++++--- .../InviteLecturerEventHandler.cs | 11 +++++-- .../LecturerAcceptToCourseEventHandler.cs | 12 ++++++-- .../LecturerRejectToCourseEventHandler.cs | 11 +++++-- .../EventHandlers/NewCourseMateHandler.cs | 14 ++++++--- .../EventHandlers/NewHomeworkEventHandler.cs | 19 +++++++----- .../EventHandlers/RateEventHandler.cs | 12 +++++--- .../EventHandlers/RegisterEventHandler.cs | 12 +++++--- .../StudentPassTaskEventHandler.cs | 16 ++++++---- .../UpdateHomeworkEventHandler.cs | 16 ++++++---- .../UpdateTaskMaxRatingEventHandler.cs | 13 ++++---- .../HwProj.NotificationsService.API.csproj | 4 +-- .../Services/INotificationsService.cs | 2 ++ .../Services/NotificationsService.cs | 21 ++++++++++++- .../Startup.cs | 18 ++++++----- .../appsettings.json | 3 ++ .../ITelegramBotClient.cs | 7 ----- .../TelegramBotClient.cs | 17 ----------- .../Commands/CommandNames.cs | 13 -------- .../Service/IUserService.cs | 11 ------- .../.dockerignore | 0 .../Commands/CommandNames.cs | 13 ++++++++ .../Commands/Commands.cs | 2 +- .../Commands/GetCourses.cs | 4 +-- .../Commands/GetHomeworks.cs | 4 +-- .../Commands/GetSolutionInfo.cs | 7 ++--- .../Commands/GetSolutionsFromTask.cs} | 29 +++++++++--------- .../Commands/GetTaskInfo.cs | 6 ++-- .../Commands/GetTasks.cs | 4 +-- .../Commands/StartCommand.cs | 4 +-- .../Controllers/TelegramBotController.cs | 21 +++++++++---- .../Dockerfile | 0 .../Events/ConfirmTelegramBotEvent.cs | 4 +-- .../HwProj.TelegramBotService.API.csproj} | 1 + .../Models/TelegramBotContext.cs | 2 +- .../Models/TelegramUserModel.cs | 2 +- .../Program.cs | 2 +- .../Properties/launchSettings.json | 0 .../Service/CommandService.cs | 10 +++++-- .../Service/ICommandService.cs | 2 +- .../Service/IUserService.cs | 15 ++++++++++ .../Service/TelegramBot.cs | 4 +-- .../Service/UserService.cs | 13 +++++--- .../Startup.cs | 11 ++++--- .../appsettings.Development.json | 0 .../appsettings.json | 2 +- .../ConfigurationExtensions.cs | 6 ++-- .../HwProj.TelegramBotService.Client.csproj} | 3 +- .../ITelegramBotServiceClient.cs | 10 +++++++ .../TelegramBotServiceClient.cs | 30 +++++++++++++++++++ HwProj.sln | 6 ++-- 52 files changed, 291 insertions(+), 175 deletions(-) delete mode 100644 HwProj.TelegramBot/HwProj.TelegramBot.Client/ITelegramBotClient.cs delete mode 100644 HwProj.TelegramBot/HwProj.TelegramBot.Client/TelegramBotClient.cs delete mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs delete mode 100644 HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/IUserService.cs rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/.dockerignore (100%) create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Commands/Commands.cs (81%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Commands/GetCourses.cs (95%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Commands/GetHomeworks.cs (96%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Commands/GetSolutionInfo.cs (93%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI/Commands/GetSolutions.cs => HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs} (72%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Commands/GetTaskInfo.cs (96%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Commands/GetTasks.cs (96%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Commands/StartCommand.cs (92%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Controllers/TelegramBotController.cs (59%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Dockerfile (100%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Events/ConfirmTelegramBotEvent.cs (70%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI/HwProj.TelegramBotAPI.csproj => HwProj.TelegramBotService.API/HwProj.TelegramBotService.API.csproj} (95%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Models/TelegramBotContext.cs (86%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Models/TelegramUserModel.cs (83%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Program.cs (90%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Properties/launchSettings.json (100%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Service/CommandService.cs (86%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Service/ICommandService.cs (75%) create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Service/TelegramBot.cs (85%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Service/UserService.cs (82%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/Startup.cs (89%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/appsettings.Development.json (100%) rename HwProj.TelegramBot/{HwProj.TelegramBotAPI => HwProj.TelegramBotService.API}/appsettings.json (91%) rename HwProj.TelegramBot/{HwProj.TelegramBot.Client => HwProj.TelegramBotService.Client}/ConfigurationExtensions.cs (59%) rename HwProj.TelegramBot/{HwProj.TelegramBot.Client/HwProj.TelegramBot.Client.csproj => HwProj.TelegramBotService.Client/HwProj.TelegramBotService.Client.csproj} (68%) create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs index de42414e9..de57e6f4d 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs @@ -3,8 +3,8 @@ using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; -using HwProj.TelegramBotAPI; -using HwProj.TelegramBotAPI.Events; +using HwProj.TelegramBotService.API; +using HwProj.TelegramBotService.API.Events; namespace HwProj.NotificationsService.API.EventHandlers { diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/EditProfileEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/EditProfileEventHandler.cs index 78b1494b6..d4c4aae54 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/EditProfileEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/EditProfileEventHandler.cs @@ -4,21 +4,24 @@ using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; +using HwProj.NotificationsService.API.Services; namespace HwProj.NotificationsService.API.EventHandlers { public class EditProfileEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; - - public EditProfileEventHandler(INotificationsRepository notificationRepository) + private readonly INotificationsService _notificationsService; + + public EditProfileEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService) { _notificationRepository = notificationRepository; + _notificationsService = notificationsService; } public async Task HandleAsync(EditProfileEvent @event) { - await _notificationRepository.AddAsync(new Notification + var notification = new Notification { Sender = "AuthService", Body = "Ваш профиль был успешно отредактирован.", @@ -26,7 +29,9 @@ await _notificationRepository.AddAsync(new Notification Date = DateTime.UtcNow, HasSeen = false, Owner = @event.UserId - }); + }; + await _notificationRepository.AddAsync(notification); + await _notificationsService.SendTelegramMessageAsync(notification); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs index fae880c09..995e4a618 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs @@ -4,21 +4,24 @@ using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; +using HwProj.NotificationsService.API.Services; namespace HwProj.NotificationsService.API.EventHandlers { public class InviteLecturerEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; + private readonly INotificationsService _notificationsService; - public InviteLecturerEventHandler(INotificationsRepository notificationRepository) + public InviteLecturerEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService) { _notificationRepository = notificationRepository; + _notificationsService = notificationsService; } public async Task HandleAsync(InviteLecturerEvent @event) { - await _notificationRepository.AddAsync(new Notification + var notification = new Notification { Sender = "AuthService", Body = "Вас добавили в список лекторов.", @@ -26,7 +29,9 @@ await _notificationRepository.AddAsync(new Notification Date = DateTime.UtcNow, HasSeen = false, Owner = @event.UserId - }); + }; + await _notificationRepository.AddAsync(notification); + await _notificationsService.SendTelegramMessageAsync(notification); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs index 5993b56ca..639b0d636 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs @@ -5,6 +5,8 @@ using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; +using HwProj.NotificationsService.API.Services; +using HwProj.TelegramBotService.Client; namespace HwProj.NotificationsService.API.EventHandlers { @@ -12,16 +14,18 @@ public class LecturerAcceptToCourseEventHandler : IEventHandler{@event.CourseName}.", @@ -29,7 +33,9 @@ await _notificationRepository.AddAsync(new Notification Date = DateTime.UtcNow, HasSeen = false, Owner = @event.StudentId - }); + }; + await _notificationRepository.AddAsync(notification); + await _notificationsService.SendTelegramMessageAsync(notification); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs index 94dfdf367..638d1f811 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs @@ -5,6 +5,7 @@ using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; +using HwProj.NotificationsService.API.Services; namespace HwProj.NotificationsService.API.EventHandlers { @@ -12,16 +13,18 @@ public class LecturerRejectToCourseEventHandler : IEventHandler{@event.CourseName}.", @@ -29,7 +32,9 @@ await _notificationRepository.AddAsync(new Notification Date = DateTime.UtcNow, HasSeen = false, Owner = @event.StudentId - }); + }; + await _notificationRepository.AddAsync(notification); + await _notificationsService.SendTelegramMessageAsync(notification); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs index e50718370..320b7b975 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs @@ -5,6 +5,7 @@ using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; +using HwProj.NotificationsService.API.Services; namespace HwProj.NotificationsService.API.EventHandlers { @@ -12,11 +13,13 @@ public class NewCourseMateHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; private readonly IAuthServiceClient _authClient; + private readonly INotificationsService _notificationsService; - public NewCourseMateHandler(INotificationsRepository notificationRepository, IAuthServiceClient authClient) + public NewCourseMateHandler(INotificationsRepository notificationRepository, IAuthServiceClient authClient, INotificationsService notificationsService) { _notificationRepository = notificationRepository; _authClient = authClient; + _notificationsService = notificationsService; } public async Task HandleAsync(NewCourseMateEvent @event) @@ -25,15 +28,18 @@ public async Task HandleAsync(NewCourseMateEvent @event) foreach (var m in @event.MentorIds.Split('/')) { - await _notificationRepository.AddAsync(new Notification + var notification = new Notification { Sender = "CourseService", - Body = $"Пользователь {user.Name} {user.Surname} подал заявку на вступление в курс {@event.CourseName}.", + Body = + $"Пользователь {user.Name} {user.Surname} подал заявку на вступление в курс {@event.CourseName}.", Category = "CourseService", Date = DateTime.UtcNow, HasSeen = false, Owner = m - }); + }; + await _notificationRepository.AddAsync(notification); + await _notificationsService.SendTelegramMessageAsync(notification); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs index 74889e16c..3d9c4b469 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs @@ -1,36 +1,41 @@ using System; using System.Threading.Tasks; -using HwProj.AuthService.API.Events; using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; using HwProj.CoursesService.API.Events; +using HwProj.NotificationsService.API.Services; namespace HwProj.NotificationsService.API.EventHandlers { - // ReSharper disable once UnusedType.Global public class NewHomeworkEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; + private readonly INotificationsService _notificationsService; - public NewHomeworkEventHandler(INotificationsRepository notificationRepository) + public NewHomeworkEventHandler(INotificationsRepository notificationRepository, + INotificationsService notificationsService) { _notificationRepository = notificationRepository; + _notificationsService = notificationsService; } public async Task HandleAsync(NewHomeworkEvent @event) { - foreach(var student in @event.Course.CourseMates) + foreach (var student in @event.Course.CourseMates) { - await _notificationRepository.AddAsync(new Notification + var notification = new Notification { Sender = "CourseService", - Body = $"В курсе {@event.Course.Name} опубликована новая домашка {@event.Homework}.", + Body = + $"В курсе {@event.Course.Name} опубликована новая домашка {@event.Homework}.", Category = "CourseService", Date = DateTime.UtcNow, HasSeen = false, Owner = student.StudentId - }); + }; + await _notificationRepository.AddAsync(notification); + await _notificationsService.SendTelegramMessageAsync(notification); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs index ec5d2ba66..688100bff 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs @@ -1,9 +1,9 @@ using System; using System.Threading.Tasks; -using HwProj.AuthService.API.Events; using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; +using HwProj.NotificationsService.API.Services; using HwProj.SolutionsService.API.Events; namespace HwProj.NotificationsService.API.EventHandlers @@ -12,15 +12,17 @@ namespace HwProj.NotificationsService.API.EventHandlers public class RateEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; + private readonly INotificationsService _notificationsService; - public RateEventHandler(INotificationsRepository notificationRepository) + public RateEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService) { _notificationRepository = notificationRepository; + _notificationsService = notificationsService; } public async Task HandleAsync(RateEvent @event) { - await _notificationRepository.AddAsync(new Notification + var notification = new Notification { Sender = "SolutionService", Body = $"Задача {@event.Task.Title} оценена.", @@ -28,7 +30,9 @@ await _notificationRepository.AddAsync(new Notification Date = DateTime.UtcNow, HasSeen = false, Owner = @event.Solution.StudentId - }); ; + }; + await _notificationRepository.AddAsync(notification); + await _notificationsService.SendTelegramMessageAsync(notification); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs index 27e20baa2..b8a1cbb2c 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs @@ -4,22 +4,24 @@ using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; +using HwProj.NotificationsService.API.Services; namespace HwProj.NotificationsService.API.EventHandlers { - // ReSharper disable once UnusedType.Global public class RegisterEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; + private readonly INotificationsService _notificationsService; - public RegisterEventHandler(INotificationsRepository notificationRepository) + public RegisterEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService) { _notificationRepository = notificationRepository; + _notificationsService = notificationsService; } public async Task HandleAsync(StudentRegisterEvent @event) { - await _notificationRepository.AddAsync(new Notification + var notification = new Notification { Sender = "AuthService", Body = $"{@event.Name} {@event.Surname}, Добро Пожаловать в HwProj2.", @@ -27,7 +29,9 @@ await _notificationRepository.AddAsync(new Notification Date = DateTime.UtcNow, HasSeen = false, Owner = @event.UserId - }); + }; + await _notificationRepository.AddAsync(notification); + await _notificationsService.SendTelegramMessageAsync(notification); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs index a86ada1ac..a65cf8bbf 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs @@ -1,36 +1,40 @@ using System; using System.Threading.Tasks; -using HwProj.AuthService.API.Events; using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; +using HwProj.NotificationsService.API.Services; using HwProj.SolutionsService.API.Events; namespace HwProj.NotificationsService.API.EventHandlers { - // ReSharper disable once UnusedType.Global public class StudentPassTaskEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; + private readonly INotificationsService _notificationsService; - public StudentPassTaskEventHandler(INotificationsRepository notificationRepository) + public StudentPassTaskEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService) { _notificationRepository = notificationRepository; + _notificationsService = notificationsService; } public async Task HandleAsync(StudentPassTaskEvent @event) { foreach (var m in @event.Course.MentorIds.Split('/')) { - await _notificationRepository.AddAsync(new Notification + var notification = new Notification { Sender = "SolutionService", - Body = $"{@event.Student.Name} {@event.Student.Surname} добавил новое решение задачи {@event.Task.Title} из курса {@event.Course.Name}.", + Body = + $"{@event.Student.Name} {@event.Student.Surname} добавил новое решение задачи {@event.Task.Title} из курса {@event.Course.Name}.", Category = "SolutionService", Date = DateTime.UtcNow, HasSeen = false, Owner = m, - }); + }; + await _notificationRepository.AddAsync(notification); + await _notificationsService.SendTelegramMessageAsync(notification); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs index 41eba9fea..7337a7b5b 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs @@ -1,36 +1,40 @@ using System; using System.Threading.Tasks; -using HwProj.AuthService.API.Events; using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; using HwProj.CoursesService.API.Events; +using HwProj.NotificationsService.API.Services; namespace HwProj.NotificationsService.API.EventHandlers { - // ReSharper disable once UnusedType.Global public class UpdateHomeworkEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; + private readonly INotificationsService _notificationsService; - public UpdateHomeworkEventHandler(INotificationsRepository notificationRepository) + public UpdateHomeworkEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService) { _notificationRepository = notificationRepository; + _notificationsService = notificationsService; } public async Task HandleAsync(UpdateHomeworkEvent @event) { foreach (var student in @event.Course.CourseMates) { - await _notificationRepository.AddAsync(new Notification + var notification = new Notification { Sender = "CourseService", - Body = $"В курсе {@event.Course.Name} домашнее задание {@event.Homework.Title} обновлено.", + Body = + $"В курсе {@event.Course.Name} домашнее задание {@event.Homework.Title} обновлено.", Category = "CourseService", Date = DateTime.UtcNow, HasSeen = false, Owner = student.StudentId - }); + }; + await _notificationRepository.AddAsync(notification); + await _notificationsService.SendTelegramMessageAsync(notification); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs index a23588839..6e95ed914 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs @@ -1,28 +1,29 @@ using System; using System.Threading.Tasks; -using HwProj.AuthService.API.Events; using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; using HwProj.CoursesService.API.Events; +using HwProj.NotificationsService.API.Services; namespace HwProj.NotificationsService.API.EventHandlers { - // ReSharper disable once UnusedType.Global public class UpdateTaskMaxRatingEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; + private readonly INotificationsService _notificationsService; - public UpdateTaskMaxRatingEventHandler(INotificationsRepository notificationRepository) + public UpdateTaskMaxRatingEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService) { _notificationRepository = notificationRepository; + _notificationsService = notificationsService; } public async Task HandleAsync(UpdateTaskMaxRatingEvent @event) { foreach (var student in @event.Course.CourseMates) { - await _notificationRepository.AddAsync(new Notification + var notification =new Notification { Sender = "CourseService", Body = $"Задача обновлена.", @@ -30,7 +31,9 @@ await _notificationRepository.AddAsync(new Notification Date = DateTime.UtcNow, HasSeen = false, Owner = student.StudentId - }); + }; + await _notificationRepository.AddAsync(notification); + await _notificationsService.SendTelegramMessageAsync(notification); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj b/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj index e61c18fa4..2d48b1194 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj @@ -23,8 +23,8 @@ - - + + diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs index 0d7492a5d..8e28aa82d 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs @@ -8,5 +8,7 @@ public interface INotificationsService Task AddNotificationAsync(Notification notification); Task GetAsync(string userId, NotificationFilter filter = null); Task MarkAsSeenAsync(string userId, long[] notificationIds); + + Task SendTelegramMessageAsync(Notification notification); } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs index e30953df2..a8a40944b 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs @@ -3,6 +3,10 @@ using AutoMapper; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; +using HwProj.TelegramBotService.Client; +using Microsoft.Extensions.Configuration; +using Telegram.Bot; +using Telegram.Bot.Types.Enums; namespace HwProj.NotificationsService.API.Services { @@ -10,11 +14,17 @@ public class NotificationsService : INotificationsService { private readonly INotificationsRepository _repository; private readonly IMapper _mapper; + private readonly TelegramBotClient _botClient; + private readonly IConfigurationSection _configuration; + private readonly ITelegramBotServiceClient _telegramBotServiceClient; - public NotificationsService(INotificationsRepository repository, IMapper mapper) + public NotificationsService(INotificationsRepository repository, IMapper mapper, IConfigurationSection configuration, ITelegramBotServiceClient telegramBotServiceClient) { _repository = repository; _mapper = mapper; + _telegramBotServiceClient = telegramBotServiceClient; + _configuration = configuration.GetSection("Telegram");; + _botClient = new TelegramBotClient(_configuration["Token"]); } public async Task AddNotificationAsync(Notification notification) @@ -38,5 +48,14 @@ public async Task MarkAsSeenAsync(string userId, long[] notificationIds) await _repository.UpdateBatchAsync(userId, notificationIds, t => new Notification {HasSeen = true}); } + + public async Task SendTelegramMessageAsync(Notification notification) + { + var user = await _telegramBotServiceClient.GetTelegramUser(notification.Owner); + if (user != null) + { + await _botClient.SendTextMessageAsync(user.ChatId, notification.Body, ParseMode.Markdown); + } + } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs index 54fb7ba52..8ef53cfee 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs @@ -1,21 +1,23 @@ -using HwProj.AuthService.API.Events; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using System.Net.Http; +using HwProj.AuthService.API.Events; using HwProj.AuthService.Client; using HwProj.EventBus.Client.Interfaces; using HwProj.NotificationsService.API.EventHandlers; using HwProj.NotificationsService.API.Models; + using HwProj.NotificationsService.API.Repositories; using HwProj.NotificationsService.API.Services; using HwProj.Utils.Configuration; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using System.Net.Http; using HwProj.CoursesService.API.Events; using HwProj.CoursesService.Client; using HwProj.SolutionsService.API.Events; using HwProj.SolutionsService.Client; +using HwProj.TelegramBotService.Client; using UpdateTaskMaxRatingEvent = HwProj.CoursesService.API.Events.UpdateTaskMaxRatingEvent; namespace HwProj.NotificationsService.API @@ -53,7 +55,7 @@ public void ConfigureServices(IServiceCollection services) services.AddAuthServiceClient(httpClient, "http://localhost:5001"); services.AddCoursesServiceClient(httpClient, "http://localhost:5002"); services.AddSolutionServiceClient(httpClient, "http://localhost:5007"); - /*services.AddTelegramBotClient(httpClient, "http://localhost:5009");*/ + services.AddTelegramBotClient(httpClient, "http://localhost:5009"); services.ConfigureHwProjServices("Notifications API"); diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json index 5c68d6ed3..254f36d45 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json @@ -15,5 +15,8 @@ "EventBusVirtualHost": "/", "EventBusQueueName": "NotificationService", "EventBusRetryCount": "5" + }, + "Telegram": { + "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU" } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBot.Client/ITelegramBotClient.cs b/HwProj.TelegramBot/HwProj.TelegramBot.Client/ITelegramBotClient.cs deleted file mode 100644 index 49d88b0a5..000000000 --- a/HwProj.TelegramBot/HwProj.TelegramBot.Client/ITelegramBotClient.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace HwProj.TelegramBot.Client -{ - public interface ITelegramBotClient - { - - } -} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBot.Client/TelegramBotClient.cs b/HwProj.TelegramBot/HwProj.TelegramBot.Client/TelegramBotClient.cs deleted file mode 100644 index 25c30b4f6..000000000 --- a/HwProj.TelegramBot/HwProj.TelegramBot.Client/TelegramBotClient.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Net.Http; - -namespace HwProj.TelegramBot.Client -{ - public class TelegramBotClient : ITelegramBotClient - { - private readonly HttpClient _httpClient; - private readonly Uri _telegramBotUri; - - public TelegramBotClient(HttpClient httpClient, Uri telegramBotUri) - { - _httpClient = httpClient; - _telegramBotUri = telegramBotUri; - } - } -} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs deleted file mode 100644 index 1202cb106..000000000 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/CommandNames.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace HwProj.TelegramBotAPI.Commands -{ - public static class CommandNames - { - public const string StartCommand = "/start"; - public const string GetCourses = "/courses"; // /courses {courseId} - public const string GetHomeworks = "/homeworks"; // /homeworks {homeworkId} - public const string GetTasks = "/task"; // /task {taskId} - public const string GetTaskInfo = "/taskinfo"; // /taskinfo {taskId} - public const string GetSolutions = "/solutions"; // /solutions {taskId} - public const string GetSolutionInfo = "/solutioninfo"; // /solutioninfo {solutionId} - } -} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/IUserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/IUserService.cs deleted file mode 100644 index a19f812cb..000000000 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/IUserService.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Threading.Tasks; -using HwProj.TelegramBotAPI.Models; -using Telegram.Bot.Types; - -namespace HwProj.TelegramBotAPI.Service -{ - public interface IUserService - { - Task GetOrCreateChatId(Update update); - } -} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/.dockerignore b/HwProj.TelegramBot/HwProj.TelegramBotService.API/.dockerignore similarity index 100% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/.dockerignore rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/.dockerignore diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs new file mode 100644 index 000000000..362d2278b --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs @@ -0,0 +1,13 @@ +namespace HwProj.TelegramBotService.API.Commands +{ + public static class CommandNames + { + public const string StartCommand = "/start"; + public const string GetCourses = "/courses"; // /courses {courseId} + public const string GetHomeworks = "/homeworks"; // /homeworks {homeworkId} + public const string GetTasks = "/task"; // /task {taskId} + public const string GetTaskInfo = "/taskinfo"; // /taskinfo {taskId} + public const string GetSolutionsFromTask = "/solutions"; // /solutions {taskId} + public const string GetSolutionInfo = "/solutioninfo"; // /solutioninfo {solutionId} + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/Commands.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/Commands.cs similarity index 81% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/Commands.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/Commands.cs index e3e9356fd..d44385a77 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/Commands.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/Commands.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; using Telegram.Bot.Types; -namespace HwProj.TelegramBotAPI.Commands +namespace HwProj.TelegramBotService.API.Commands { public abstract class Commands { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetCourses.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs similarity index 95% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetCourses.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs index f96f1a7c2..2ac354bc7 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetCourses.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs @@ -1,12 +1,12 @@ using System.Collections.Generic; using System.Threading.Tasks; using HwProj.CoursesService.Client; -using HwProj.TelegramBotAPI.Service; +using HwProj.TelegramBotService.API.Service; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; -namespace HwProj.TelegramBotAPI.Commands +namespace HwProj.TelegramBotService.API.Commands { public class GetCourses : Commands { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetHomeworks.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs similarity index 96% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetHomeworks.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs index 45c663874..083113bf0 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetHomeworks.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs @@ -2,12 +2,12 @@ using System.Collections.Generic; using System.Threading.Tasks; using HwProj.CoursesService.Client; -using HwProj.TelegramBotAPI.Service; +using HwProj.TelegramBotService.API.Service; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; -namespace HwProj.TelegramBotAPI.Commands +namespace HwProj.TelegramBotService.API.Commands { public class GetHomeworks : Commands { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutionInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs similarity index 93% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutionInfo.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs index 6d93301bc..c6a522ffa 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutionInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs @@ -2,14 +2,13 @@ using System.Collections.Generic; using System.Threading.Tasks; using HwProj.CoursesService.Client; -using HwProj.Models.CoursesService.ViewModels; using HwProj.SolutionsService.Client; -using HwProj.TelegramBotAPI.Service; +using HwProj.TelegramBotService.API.Service; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; -namespace HwProj.TelegramBotAPI.Commands +namespace HwProj.TelegramBotService.API.Commands { public class GetSolutionInfo : Commands { @@ -58,7 +57,7 @@ public override async Task ExecuteAsync(Update update) await _botClient.SendTextMessageAsync(user.ChatId, $"Отзыв преподователя: {solution.LecturerComment}." + $"\nОценка: {solution.Rating}." + - $"\nGithub: ссылка", + $"\nGithub: {solution.GithubUrl}", replyMarkup:keyboardMarkup); } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutions.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs similarity index 72% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutions.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs index 82a0e9c8a..d16fbb838 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetSolutions.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs @@ -1,32 +1,31 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using HwProj.CoursesService.Client; using HwProj.SolutionsService.Client; -using HwProj.TelegramBotAPI.Service; +using HwProj.TelegramBotService.API.Service; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -using Telegram.Bot.Types.ReplyMarkups; +using Telegram.Bot.Types.ReplyMarkups; /*using HwProj.CoursesService.Client;*/ -namespace HwProj.TelegramBotAPI.Commands +namespace HwProj.TelegramBotService.API.Commands { - public class GetSolutions: Commands + public class GetSolutionsFromTask: Commands { private readonly TelegramBotClient _botClient; private readonly IUserService _userService; private readonly SolutionsServiceClient _solutionsServiceClient; - private readonly CoursesServiceClient _coursesServiceClient; + /*private readonly CoursesServiceClient _coursesServiceClient;*/ - public GetSolutions(TelegramBot telegramBot, IUserService userService, SolutionsServiceClient solutionsServiceClient, CoursesServiceClient coursesServiceClient) + public GetSolutionsFromTask(TelegramBot telegramBot, IUserService userService, SolutionsServiceClient solutionsServiceClient/*, CoursesServiceClient coursesServiceClient*/) { _botClient = telegramBot.GetBot().Result; _userService = userService; _solutionsServiceClient = solutionsServiceClient; - _coursesServiceClient = coursesServiceClient; + /*_coursesServiceClient = coursesServiceClient;*/ } - public override string Name => CommandNames.GetSolutions; + public override string Name => CommandNames.GetSolutionsFromTask; public override async Task ExecuteAsync(Update update) { @@ -34,8 +33,8 @@ public override async Task ExecuteAsync(Update update) var message = update.CallbackQuery.Data; var text = message.Split(' '); var solutions = _solutionsServiceClient.GetUserSolution(Int32.Parse(text[1]), user.StudentId).Result; - var task = _coursesServiceClient.GetTask(Int32.Parse(text[1])).Result; - var hw = _coursesServiceClient.GetHomework(task.HomeworkId).Result; + /*var task = _coursesServiceClient.GetTask(Int32.Parse(text[1])).Result; + var hw = _coursesServiceClient.GetHomework(task.HomeworkId).Result;*/ var rows = new List(); var cols = new List(); @@ -54,12 +53,12 @@ public override async Task ExecuteAsync(Update update) } var button = GetButton("Мои курсы", $"/courses"); cols.Add(button); - button = GetButton("Мои домашки", $"/homeworks {hw.CourseId}"); - cols.Add(button); + /*button = GetButton("Мои домашки", $"/homeworks {hw.CourseId}"); + cols.Add(button);*/ rows.Add(cols.ToArray()); cols = new List(); - button = GetButton("Мои задачи", $"/task {task.HomeworkId}"); - cols.Add(button); + /*button = GetButton("Мои задачи", $"/task {task.HomeworkId}"); + cols.Add(button);*/ rows.Add(cols.ToArray()); var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTaskInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs similarity index 96% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTaskInfo.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs index a6f605115..5db7ef90d 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTaskInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs @@ -3,12 +3,12 @@ using System.Threading.Tasks; using HwProj.CoursesService.Client; using HwProj.Models.CoursesService.ViewModels; -using HwProj.TelegramBotAPI.Service; +using HwProj.TelegramBotService.API.Service; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; -namespace HwProj.TelegramBotAPI.Commands +namespace HwProj.TelegramBotService.API.Commands { public class GetTaskInfo : Commands { @@ -52,7 +52,7 @@ public override async Task ExecuteAsync(Update update) cols = new List(); button = GetButton("Мои задачи", $"/task {task.HomeworkId}"); cols.Add(button); - button = GetButton($"Решения {task.Title}", $"/solutions {task.Id}"); + button = GetButton($"Решения {task.Title}", $"/solutioninfo {task.Id}"); cols.Add(button); rows.Add(cols.ToArray()); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTasks.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs similarity index 96% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTasks.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs index e60fefa22..37f112d89 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/GetTasks.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs @@ -2,12 +2,12 @@ using System.Collections.Generic; using System.Threading.Tasks; using HwProj.CoursesService.Client; -using HwProj.TelegramBotAPI.Service; +using HwProj.TelegramBotService.API.Service; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; -namespace HwProj.TelegramBotAPI.Commands +namespace HwProj.TelegramBotService.API.Commands { public class GetTasks : Commands { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/StartCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs similarity index 92% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/StartCommand.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs index c736dad91..922d9e60e 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Commands/StartCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs @@ -1,11 +1,11 @@ using System.Threading.Tasks; -using HwProj.TelegramBotAPI.Service; +using HwProj.TelegramBotService.API.Service; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; -namespace HwProj.TelegramBotAPI.Commands +namespace HwProj.TelegramBotService.API.Commands { public class StartCommand : Commands { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Controllers/TelegramBotController.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs similarity index 59% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Controllers/TelegramBotController.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs index 17293c4cb..62f8e906c 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Controllers/TelegramBotController.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs @@ -1,24 +1,26 @@ using System; using System.Threading.Tasks; -using HwProj.TelegramBotAPI.Service; +using HwProj.TelegramBotService.API.Models; +using HwProj.TelegramBotService.API.Service; using Microsoft.AspNetCore.Mvc; using Telegram.Bot.Types; - -namespace HwProj.TelegramBotAPI.Controllers +namespace HwProj.TelegramBotService.API.Controllers { + [Route("api/[controller]")] [ApiController] - [Route("api/message/update")] public class TelegramBotController : Controller { private readonly ICommandService _commandService; + private readonly IUserService _userService; - public TelegramBotController(ICommandService commandService) + public TelegramBotController(ICommandService commandService, IUserService userService) { _commandService = commandService; + _userService = userService; } - [HttpPost] + [HttpPost("/update")] public async Task Update(Update update) { @@ -38,5 +40,12 @@ public async Task Update(Update update) return Ok(); } + + [HttpGet("/get/{studentId}")] + public async Task GetUser(string studentId) + { + var userMoodel = await _userService.GetTelegramUserModelByStudentId(studentId); + return userMoodel; + } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Dockerfile b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Dockerfile similarity index 100% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Dockerfile rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Dockerfile diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Events/ConfirmTelegramBotEvent.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs similarity index 70% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Events/ConfirmTelegramBotEvent.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs index 69c1b1205..0585d50b1 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Events/ConfirmTelegramBotEvent.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs @@ -1,7 +1,7 @@ using HwProj.EventBus.Client; -using HwProj.TelegramBotAPI.Models; +using HwProj.TelegramBotService.API.Models; -namespace HwProj.TelegramBotAPI.Events +namespace HwProj.TelegramBotService.API.Events { public class ConfirmTelegramBotEvent : Event { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/HwProj.TelegramBotAPI.csproj b/HwProj.TelegramBot/HwProj.TelegramBotService.API/HwProj.TelegramBotService.API.csproj similarity index 95% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/HwProj.TelegramBotAPI.csproj rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/HwProj.TelegramBotService.API.csproj index 77660f465..b8fa61a22 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/HwProj.TelegramBotAPI.csproj +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/HwProj.TelegramBotService.API.csproj @@ -4,6 +4,7 @@ netcoreapp2.2 Windows latest + HwProj.TelegramBotService.API diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramBotContext.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramBotContext.cs similarity index 86% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramBotContext.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramBotContext.cs index dbef30995..c147fd5c3 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramBotContext.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramBotContext.cs @@ -1,6 +1,6 @@ using Microsoft.EntityFrameworkCore; -namespace HwProj.TelegramBotAPI.Models +namespace HwProj.TelegramBotService.API.Models { public class TelegramBotContext : DbContext { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramUserModel.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs similarity index 83% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramUserModel.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs index 1f51012b0..0e4f89c54 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Models/TelegramUserModel.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs @@ -1,4 +1,4 @@ -namespace HwProj.TelegramBotAPI.Models +namespace HwProj.TelegramBotService.API.Models { public class TelegramUserModel { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Program.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Program.cs similarity index 90% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Program.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Program.cs index 491d0e831..adf41576c 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Program.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Program.cs @@ -1,7 +1,7 @@ using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; -namespace HwProj.TelegramBotAPI +namespace HwProj.TelegramBotService.API { public class Program { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Properties/launchSettings.json b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Properties/launchSettings.json similarity index 100% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Properties/launchSettings.json rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Properties/launchSettings.json diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/CommandService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs similarity index 86% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/CommandService.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs index ed6aed8ee..db814dc5e 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/CommandService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs @@ -2,12 +2,12 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using HwProj.TelegramBotAPI.Commands; +using HwProj.TelegramBotService.API.Commands; using Microsoft.Extensions.DependencyInjection; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -namespace HwProj.TelegramBotAPI.Service +namespace HwProj.TelegramBotService.API.Service { public class CommandService : ICommandService { @@ -63,6 +63,12 @@ public async Task Execute(Update update) case "/taskinfo": await ExecuteCommand(CommandNames.GetTaskInfo, update); break; + case "/solutions": + await ExecuteCommand(CommandNames.GetSolutionsFromTask, update); + break; + case "/solutioninfo": + await ExecuteCommand(CommandNames.GetSolutionInfo, update); + break; } } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/ICommandService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/ICommandService.cs similarity index 75% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/ICommandService.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/ICommandService.cs index bc172b7af..162d1d85d 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/ICommandService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/ICommandService.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; using Telegram.Bot.Types; -namespace HwProj.TelegramBotAPI.Service +namespace HwProj.TelegramBotService.API.Service { public interface ICommandService { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs new file mode 100644 index 000000000..f6c4b1021 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs @@ -0,0 +1,15 @@ +using System.Threading.Tasks; +using HwProj.TelegramBotService.API.Models; +using Telegram.Bot.Types; + +namespace HwProj.TelegramBotService.API.Service +{ + public interface IUserService + { + Task GetOrCreateChatId(Update update); + + Task GetTelegramUserModelByStudentId(string studentId); + + Task GetTelegramUserModelByChatId(long ChatId); + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/TelegramBot.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/TelegramBot.cs similarity index 85% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/TelegramBot.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/TelegramBot.cs index 79ae1ccba..846cdf37f 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/TelegramBot.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/TelegramBot.cs @@ -2,7 +2,7 @@ using Microsoft.Extensions.Configuration; using Telegram.Bot; -namespace HwProj.TelegramBotAPI.Service +namespace HwProj.TelegramBotService.API.Service { public class TelegramBot { @@ -23,7 +23,7 @@ public async Task GetBot() _botClient = new TelegramBotClient(_configuration["Token"]); - var hook = $"{_configuration["Url"]}api/message/update"; + var hook = $"{_configuration["Url"]}api/Telegram/update"; await _botClient.SetWebhookAsync(hook); return _botClient; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/UserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs similarity index 82% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/UserService.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs index 551450aba..df225ba7f 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Service/UserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs @@ -1,11 +1,10 @@ -using System; -using System.Threading.Tasks; +using System.Threading.Tasks; using HwProj.AuthService.Client; -using HwProj.TelegramBotAPI.Models; +using HwProj.TelegramBotService.API.Models; using Microsoft.EntityFrameworkCore; using Telegram.Bot.Types; -namespace HwProj.TelegramBotAPI.Service +namespace HwProj.TelegramBotService.API.Service { public class UserService : IUserService { @@ -69,5 +68,11 @@ public async Task GetOrCreateChatId(Update update) return result.Entity; } + + public async Task GetTelegramUserModelByStudentId(string studentId) + => _context.TelegramUser.FirstOrDefaultAsync(x => x.StudentId == studentId).Result; + + public async Task GetTelegramUserModelByChatId(long ChatId) + => _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == ChatId).Result; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Startup.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs similarity index 89% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/Startup.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs index 1e95c3ce1..229e33855 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/Startup.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs @@ -3,9 +3,9 @@ using HwProj.AuthService.Client; using HwProj.CoursesService.Client; using HwProj.SolutionsService.Client; -using HwProj.TelegramBotAPI.Commands; -using HwProj.TelegramBotAPI.Models; -using HwProj.TelegramBotAPI.Service; +using HwProj.TelegramBotService.API.Commands; +using HwProj.TelegramBotService.API.Models; +using HwProj.TelegramBotService.API.Service; using HwProj.Utils.Configuration; using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; @@ -13,7 +13,7 @@ using Microsoft.Extensions.DependencyInjection; using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment; -namespace HwProj.TelegramBotAPI +namespace HwProj.TelegramBotService.API { public class Startup { @@ -26,7 +26,6 @@ public Startup(IConfiguration configuration) public void ConfigureServices(IServiceCollection services) { - /*services.AddControllers();*/ var connectionString = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext(options => options.UseSqlServer(connectionString)); services.AddScoped(); @@ -37,8 +36,8 @@ public void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); services.AddScoped(); - services.AddScoped(); services.AddScoped(); + /*services.AddScoped();*/ var httpClient = new HttpClient(); services.AddAuthServiceClient(httpClient, "http://localhost:5001"); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/appsettings.Development.json b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.Development.json similarity index 100% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/appsettings.Development.json rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.Development.json diff --git a/HwProj.TelegramBot/HwProj.TelegramBotAPI/appsettings.json b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json similarity index 91% rename from HwProj.TelegramBot/HwProj.TelegramBotAPI/appsettings.json rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json index 304d460a5..6de43841e 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotAPI/appsettings.json +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json @@ -17,5 +17,5 @@ "EventBusRetryCount": "5" }, "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://2c28-92-42-26-35.ngrok.io/" + "Url" : "https://fad1-92-42-26-35.ngrok.io/" } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBot.Client/ConfigurationExtensions.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ConfigurationExtensions.cs similarity index 59% rename from HwProj.TelegramBot/HwProj.TelegramBot.Client/ConfigurationExtensions.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.Client/ConfigurationExtensions.cs index 1a72e95a4..40b6abbcc 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBot.Client/ConfigurationExtensions.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ConfigurationExtensions.cs @@ -2,15 +2,15 @@ using System.Net.Http; using Microsoft.Extensions.DependencyInjection; -namespace HwProj.TelegramBot.Client +namespace HwProj.TelegramBotService.Client { public static class ConfigurationExtensions { public static IServiceCollection AddTelegramBotClient(this IServiceCollection services, HttpClient httpClient, string baseUri) { - var solutionServiceClient = new TelegramBotClient(httpClient, new Uri(baseUri)); - services.AddSingleton(solutionServiceClient); + var telegramBotServiceClient = new TelegramBotServiceClient(httpClient, new Uri(baseUri)); + services.AddSingleton(telegramBotServiceClient); return services; } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBot.Client/HwProj.TelegramBot.Client.csproj b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/HwProj.TelegramBotService.Client.csproj similarity index 68% rename from HwProj.TelegramBot/HwProj.TelegramBot.Client/HwProj.TelegramBot.Client.csproj rename to HwProj.TelegramBot/HwProj.TelegramBotService.Client/HwProj.TelegramBotService.Client.csproj index 129f97004..3aca46f48 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBot.Client/HwProj.TelegramBot.Client.csproj +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/HwProj.TelegramBotService.Client.csproj @@ -2,6 +2,7 @@ netcoreapp2.2 + latest @@ -9,7 +10,7 @@ - + diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs new file mode 100644 index 000000000..0372470d6 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs @@ -0,0 +1,10 @@ +using System.Threading.Tasks; +using HwProj.TelegramBotService.API.Models; + +namespace HwProj.TelegramBotService.Client +{ + public interface ITelegramBotServiceClient + { + Task GetTelegramUser(string studentId); + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs new file mode 100644 index 000000000..535eabbcf --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs @@ -0,0 +1,30 @@ +using System; +using System.Net.Http; +using System.Threading.Tasks; +using HwProj.HttpUtils; +using HwProj.TelegramBotService.API.Models; + +namespace HwProj.TelegramBotService.Client +{ + public class TelegramBotServiceClient : ITelegramBotServiceClient + { + private readonly HttpClient _httpClient; + private readonly Uri _telegramBotUri; + + public TelegramBotServiceClient(HttpClient httpClient, Uri telegramBotUri) + { + _httpClient = httpClient; + _telegramBotUri = telegramBotUri; + } + + public async Task GetTelegramUser(string studentId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _telegramBotUri + $"api/Telegram/get/{studentId}"); + + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } + } +} \ No newline at end of file diff --git a/HwProj.sln b/HwProj.sln index 5a8066027..d28fce41e 100644 --- a/HwProj.sln +++ b/HwProj.sln @@ -69,11 +69,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HwProj.SolutionsService.Cli EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HwProj.Exceptions", "HwProj.Common\HwProj.Exceptions\HwProj.Exceptions.csproj", "{51463655-7668-4C7D-9FDE-D4D7CDAA82B8}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "HwProj.TelegramBot", "HwProj.TelegramBot", "{42822186-2040-4216-9C1D-9849EA5D3CB5}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "HwProj.TelegramBotService", "HwProj.TelegramBotService", "{42822186-2040-4216-9C1D-9849EA5D3CB5}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HwProj.TelegramBot.Client", "HwProj.TelegramBot\HwProj.TelegramBot.Client\HwProj.TelegramBot.Client.csproj", "{00F850B0-419E-44EA-9AFC-CBF3CBA26C91}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HwProj.TelegramBotService.Client", "HwProj.TelegramBot\HwProj.TelegramBotService.Client\HwProj.TelegramBotService.Client.csproj", "{00F850B0-419E-44EA-9AFC-CBF3CBA26C91}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HwProj.TelegramBotAPI", "HwProj.TelegramBot\HwProj.TelegramBotAPI\HwProj.TelegramBotAPI.csproj", "{677D77E8-ACFA-49FE-A752-F787B5F7A3EE}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HwProj.TelegramBotService.API", "HwProj.TelegramBot\HwProj.TelegramBotService.API\HwProj.TelegramBotService.API.csproj", "{677D77E8-ACFA-49FE-A752-F787B5F7A3EE}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution From e63299d1b285103746db016b005bc53b7ea22f10 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Sat, 27 Nov 2021 00:45:57 +0300 Subject: [PATCH 05/19] add send notification to telegram --- .../Events/NewHomeworkEvent.cs | 5 +++- .../Services/HomeworksService.cs | 2 +- .../EventHandlers/EditProfileEventHandler.cs | 2 +- .../InviteLecturerEventHandler.cs | 2 +- .../LecturerAcceptToCourseEventHandler.cs | 3 +- .../LecturerRejectToCourseEventHandler.cs | 3 +- .../EventHandlers/NewCourseMateHandler.cs | 6 ++-- .../EventHandlers/NewHomeworkEventHandler.cs | 13 +++++++-- .../EventHandlers/RateEventHandler.cs | 9 +++++- .../EventHandlers/RegisterEventHandler.cs | 2 +- .../StudentPassTaskEventHandler.cs | 9 ++++-- .../UpdateHomeworkEventHandler.cs | 13 +++++++-- .../UpdateTaskMaxRatingEventHandler.cs | 11 ++++++-- .../Services/INotificationsService.cs | 3 +- .../Services/NotificationsService.cs | 18 ++++++++---- .../appsettings.json | 3 +- .../Events/RateEvent.cs | 5 +++- .../Services/SolutionsService.cs | 2 +- .../Commands/CommandNames.cs | 4 +-- .../Commands/GetHomeworks.cs | 3 +- .../Commands/GetSolutionsFromTask.cs | 28 ++++++++++--------- .../Commands/GetTaskInfo.cs | 14 ++-------- .../Commands/GetTasks.cs | 9 +++++- .../Controllers/TelegramBotController.cs | 9 +++--- .../Service/TelegramBot.cs | 2 +- .../HwProj.TelegramBotService.API/Startup.cs | 2 +- .../appsettings.json | 2 +- .../TelegramBotServiceClient.cs | 2 +- 28 files changed, 119 insertions(+), 67 deletions(-) diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkEvent.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkEvent.cs index e4b47482b..50ff3693a 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkEvent.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkEvent.cs @@ -6,11 +6,14 @@ namespace HwProj.CoursesService.API.Events public class NewHomeworkEvent : Event { public string Homework { get; set; } + + public long HomeworkId { get; set; } public CourseViewModel Course { get; set; } - public NewHomeworkEvent(string homework, CourseViewModel course) + public NewHomeworkEvent(string homework, long homeworkId, CourseViewModel course) { Homework = homework; + homeworkId = homeworkId; Course = course; } } diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs index 8d41bee08..6218dd464 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs @@ -30,7 +30,7 @@ public async Task AddHomeworkAsync(long courseId, Homework homework) var course = await _coursesRepository.GetWithCourseMatesAsync(courseId); var courseModel = _mapper.Map(course); - _eventBus.Publish(new NewHomeworkEvent(homework.Title, courseModel)); + _eventBus.Publish(new NewHomeworkEvent(homework.Title, homework.Id, courseModel)); return await _homeworksRepository.AddAsync(homework); } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/EditProfileEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/EditProfileEventHandler.cs index d4c4aae54..93c515449 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/EditProfileEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/EditProfileEventHandler.cs @@ -31,7 +31,7 @@ public async Task HandleAsync(EditProfileEvent @event) Owner = @event.UserId }; await _notificationRepository.AddAsync(notification); - await _notificationsService.SendTelegramMessageAsync(notification); + await _notificationsService.SendTelegramMessageAsync(notification, null); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs index 995e4a618..5fec1f74c 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs @@ -31,7 +31,7 @@ public async Task HandleAsync(InviteLecturerEvent @event) Owner = @event.UserId }; await _notificationRepository.AddAsync(notification); - await _notificationsService.SendTelegramMessageAsync(notification); + await _notificationsService.SendTelegramMessageAsync(notification, null); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs index 639b0d636..23e77c17c 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs @@ -35,7 +35,8 @@ public async Task HandleAsync(LecturerAcceptToCourseEvent @event) Owner = @event.StudentId }; await _notificationRepository.AddAsync(notification); - await _notificationsService.SendTelegramMessageAsync(notification); + notification.Body = $"Вас приняли на курс {@event.CourseName}."; + await _notificationsService.SendTelegramMessageAsync(notification, null); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs index 638d1f811..41947c706 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs @@ -34,7 +34,8 @@ public async Task HandleAsync(LecturerRejectToCourseEvent @event) Owner = @event.StudentId }; await _notificationRepository.AddAsync(notification); - await _notificationsService.SendTelegramMessageAsync(notification); + notification.Body = $"Вас не приняли на курс {@event.CourseName}."; + await _notificationsService.SendTelegramMessageAsync(notification, null); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs index 320b7b975..75cb02b2b 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs @@ -32,14 +32,16 @@ public async Task HandleAsync(NewCourseMateEvent @event) { Sender = "CourseService", Body = - $"Пользователь {user.Name} {user.Surname} подал заявку на вступление в курс {@event.CourseName}.", + $"Пользователь {user.Name} {user.Surname}" + + $" подал заявку на вступление в курс {@event.CourseName}.", Category = "CourseService", Date = DateTime.UtcNow, HasSeen = false, Owner = m }; await _notificationRepository.AddAsync(notification); - await _notificationsService.SendTelegramMessageAsync(notification); + notification.Body = $"Пользователь {user.Name} {user.Surname} подал заявку на вступление в курс {@event.CourseName}."; + await _notificationsService.SendTelegramMessageAsync(notification, null); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs index 3d9c4b469..cab315803 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs @@ -5,6 +5,7 @@ using HwProj.NotificationsService.API.Repositories; using HwProj.CoursesService.API.Events; using HwProj.NotificationsService.API.Services; +using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.NotificationsService.API.EventHandlers { @@ -27,15 +28,21 @@ public async Task HandleAsync(NewHomeworkEvent @event) var notification = new Notification { Sender = "CourseService", - Body = - $"В курсе {@event.Course.Name} опубликована новая домашка {@event.Homework}.", + Body = $"В курсе {@event.Course.Name}" + + $" опубликована новая домашка {@event.Homework}.", Category = "CourseService", Date = DateTime.UtcNow, HasSeen = false, Owner = student.StudentId }; await _notificationRepository.AddAsync(notification); - await _notificationsService.SendTelegramMessageAsync(notification); + notification.Body = $"В курсе {@event.Course.Name} опубликована новая домашка {@event.Homework}."; // + var inlineKeyboard = new InlineKeyboardMarkup(new InlineKeyboardButton + { + Text = $"{@event.Homework}", + CallbackData = $"/homeworks {@event.HomeworkId}" + }); + await _notificationsService.SendTelegramMessageAsync(notification, inlineKeyboard); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs index 688100bff..c02fc93be 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs @@ -5,6 +5,7 @@ using HwProj.NotificationsService.API.Repositories; using HwProj.NotificationsService.API.Services; using HwProj.SolutionsService.API.Events; +using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.NotificationsService.API.EventHandlers { @@ -32,7 +33,13 @@ public async Task HandleAsync(RateEvent @event) Owner = @event.Solution.StudentId }; await _notificationRepository.AddAsync(notification); - await _notificationsService.SendTelegramMessageAsync(notification); + notification.Body = $"Задача {@event.Task.Title} оценена."; ///клава + var inlineKeyboard = new InlineKeyboardMarkup(new InlineKeyboardButton + { + Text = $"{@event.Task.Title}", + CallbackData = $"/solutioninfo {@event.SolutionId}" + }); + await _notificationsService.SendTelegramMessageAsync(notification, inlineKeyboard); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs index b8a1cbb2c..f59eaaa0f 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs @@ -31,7 +31,7 @@ public async Task HandleAsync(StudentRegisterEvent @event) Owner = @event.UserId }; await _notificationRepository.AddAsync(notification); - await _notificationsService.SendTelegramMessageAsync(notification); + await _notificationsService.SendTelegramMessageAsync(notification, null); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs index a65cf8bbf..5859bf120 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs @@ -26,15 +26,18 @@ public async Task HandleAsync(StudentPassTaskEvent @event) var notification = new Notification { Sender = "SolutionService", - Body = - $"{@event.Student.Name} {@event.Student.Surname} добавил новое решение задачи {@event.Task.Title} из курса {@event.Course.Name}.", + Body = $"{@event.Student.Name} {@event.Student.Surname} добавил новое " + + $"решение " + + $"задачи {@event.Task.Title}" + + $" из курса {@event.Course.Name}.", Category = "SolutionService", Date = DateTime.UtcNow, HasSeen = false, Owner = m, }; await _notificationRepository.AddAsync(notification); - await _notificationsService.SendTelegramMessageAsync(notification); + notification.Body = $"{@event.Student.Name} {@event.Student.Surname} добавил новое решение задачи {@event.Task.Title} из курса {@event.Course.Name}."; + await _notificationsService.SendTelegramMessageAsync(notification, null); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs index 7337a7b5b..d5f1e33b9 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs @@ -5,6 +5,7 @@ using HwProj.NotificationsService.API.Repositories; using HwProj.CoursesService.API.Events; using HwProj.NotificationsService.API.Services; +using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.NotificationsService.API.EventHandlers { @@ -26,15 +27,21 @@ public async Task HandleAsync(UpdateHomeworkEvent @event) var notification = new Notification { Sender = "CourseService", - Body = - $"В курсе {@event.Course.Name} домашнее задание {@event.Homework.Title} обновлено.", + Body = $"В курсе {@event.Course.Name}" + + $" домашнее задание {@event.Homework.Title} обновлено.", Category = "CourseService", Date = DateTime.UtcNow, HasSeen = false, Owner = student.StudentId }; await _notificationRepository.AddAsync(notification); - await _notificationsService.SendTelegramMessageAsync(notification); + notification.Body = $"В курсе {@event.Course.Name} домашнее задание {@event.Homework.Title} обновлено.";// клава + var inlineKeyboard = new InlineKeyboardMarkup(new InlineKeyboardButton + { + Text = $"{@event.Homework.Title}", + CallbackData = $"/task {@event.Homework.Id}" + }); + await _notificationsService.SendTelegramMessageAsync(notification, inlineKeyboard); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs index 6e95ed914..292809002 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs @@ -5,6 +5,7 @@ using HwProj.NotificationsService.API.Repositories; using HwProj.CoursesService.API.Events; using HwProj.NotificationsService.API.Services; +using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.NotificationsService.API.EventHandlers { @@ -26,14 +27,20 @@ public async Task HandleAsync(UpdateTaskMaxRatingEvent @event) var notification =new Notification { Sender = "CourseService", - Body = $"Задача обновлена.", + Body = $"Задача из {@event.Course.Name} обновлена.", Category = "CourseService", Date = DateTime.UtcNow, HasSeen = false, Owner = student.StudentId }; await _notificationRepository.AddAsync(notification); - await _notificationsService.SendTelegramMessageAsync(notification); + notification.Body = $"Задача {@event.Task.Title} из {@event.Course.Name} обновлена.";// клава + var inlineKeyboard = new InlineKeyboardMarkup(new InlineKeyboardButton + { + Text = $"{@event.Task.Title}", + CallbackData = $"/taskinfo {@event.Task.Id}" + }); + await _notificationsService.SendTelegramMessageAsync(notification, inlineKeyboard); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs index 8e28aa82d..a83be0990 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs @@ -1,5 +1,6 @@ using HwProj.Models.NotificationsService; using System.Threading.Tasks; +using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.NotificationsService.API.Services { @@ -9,6 +10,6 @@ public interface INotificationsService Task GetAsync(string userId, NotificationFilter filter = null); Task MarkAsSeenAsync(string userId, long[] notificationIds); - Task SendTelegramMessageAsync(Notification notification); + Task SendTelegramMessageAsync(Notification notification, InlineKeyboardMarkup inlineKeyboard); } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs index a8a40944b..c5453a72e 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs @@ -7,6 +7,7 @@ using Microsoft.Extensions.Configuration; using Telegram.Bot; using Telegram.Bot.Types.Enums; +using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.NotificationsService.API.Services { @@ -14,16 +15,16 @@ public class NotificationsService : INotificationsService { private readonly INotificationsRepository _repository; private readonly IMapper _mapper; - private readonly TelegramBotClient _botClient; private readonly IConfigurationSection _configuration; + private readonly TelegramBotClient _botClient; private readonly ITelegramBotServiceClient _telegramBotServiceClient; - public NotificationsService(INotificationsRepository repository, IMapper mapper, IConfigurationSection configuration, ITelegramBotServiceClient telegramBotServiceClient) + public NotificationsService(INotificationsRepository repository, IMapper mapper, IConfiguration configuration, ITelegramBotServiceClient telegramBotServiceClient) { _repository = repository; _mapper = mapper; + _configuration = configuration.GetSection("Telegram"); _telegramBotServiceClient = telegramBotServiceClient; - _configuration = configuration.GetSection("Telegram");; _botClient = new TelegramBotClient(_configuration["Token"]); } @@ -49,12 +50,19 @@ await _repository.UpdateBatchAsync(userId, notificationIds, t => new Notification {HasSeen = true}); } - public async Task SendTelegramMessageAsync(Notification notification) + public async Task SendTelegramMessageAsync(Notification notification, InlineKeyboardMarkup inlineKeyboard) { var user = await _telegramBotServiceClient.GetTelegramUser(notification.Owner); if (user != null) { - await _botClient.SendTextMessageAsync(user.ChatId, notification.Body, ParseMode.Markdown); + if (inlineKeyboard == null) + { + await _botClient.SendTextMessageAsync(user.ChatId, notification.Body, ParseMode.Markdown); + } + else + { + await _botClient.SendTextMessageAsync(user.ChatId, notification.Body, ParseMode.Markdown, replyMarkup:inlineKeyboard); + } } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json index 254f36d45..4470ef61c 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json @@ -17,6 +17,7 @@ "EventBusRetryCount": "5" }, "Telegram": { - "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU" + "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", + "Url" : "https://70ae-92-42-26-35.ngrok.io/" } } diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs index 9a1d88091..5d5e5c0a3 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs @@ -8,11 +8,14 @@ public class RateEvent : Event { public HomeworkTaskViewModel Task { get; set; } public SolutionViewModel Solution { get; set; } + + public long SolutionId { get; set; } - public RateEvent(HomeworkTaskViewModel task, SolutionViewModel solution) + public RateEvent(HomeworkTaskViewModel task, SolutionViewModel solution, long solutionId) { Task = task; Solution = solution; + SolutionId = solutionId; } } } diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs index 93ca02b1d..5605e6b26 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs @@ -90,7 +90,7 @@ public async Task RateSolutionAsync(long solutionId, int newRating, string lectu { var solutionModel = _mapper.Map(solution); var taskModel = _mapper.Map(task); - _eventBus.Publish(new RateEvent(taskModel, solutionModel)); + _eventBus.Publish(new RateEvent(taskModel, solutionModel, solution.Id)); SolutionState state = newRating >= task.MaxRating ? SolutionState.Final : SolutionState.Rated; await _solutionsRepository.RateSolutionAsync(solutionId, state, newRating, lecturerComment); } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs index 362d2278b..2bbf760cc 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs @@ -4,8 +4,8 @@ public static class CommandNames { public const string StartCommand = "/start"; public const string GetCourses = "/courses"; // /courses {courseId} - public const string GetHomeworks = "/homeworks"; // /homeworks {homeworkId} - public const string GetTasks = "/task"; // /task {taskId} + public const string GetHomeworks = "/homeworks"; // /homeworks {courseId} + public const string GetTasks = "/task"; // /task {homeworksId} public const string GetTaskInfo = "/taskinfo"; // /taskinfo {taskId} public const string GetSolutionsFromTask = "/solutions"; // /solutions {taskId} public const string GetSolutionInfo = "/solutioninfo"; // /solutioninfo {solutionId} diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs index 083113bf0..2807eaf05 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs @@ -30,6 +30,7 @@ public override async Task ExecuteAsync(Update update) var message = update.CallbackQuery.Data; var text = message.Split(' '); var homeworks = _coursesServiceClient.GetAllHomeworkByCourse(Int32.Parse(text[1])).Result; + var course = _coursesServiceClient.GetCourseById(Int32.Parse(text[1]), user.StudentId).Result; var rows = new List(); var cols = new List(); @@ -51,7 +52,7 @@ public override async Task ExecuteAsync(Update update) cols.Add(button); rows.Add(cols.ToArray()); var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); - await _botClient.SendTextMessageAsync(user.ChatId, "Выберите homework:", replyMarkup:keyboardMarkup); + await _botClient.SendTextMessageAsync(user.ChatId, $"Выберите homework из курса {course.Name}", replyMarkup:keyboardMarkup); } private InlineKeyboardButton GetButton(string text, string callbackData) diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs index d16fbb838..ecfe5abdf 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs @@ -6,7 +6,8 @@ using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -using Telegram.Bot.Types.ReplyMarkups; /*using HwProj.CoursesService.Client;*/ +using Telegram.Bot.Types.ReplyMarkups; +using HwProj.CoursesService.Client; namespace HwProj.TelegramBotService.API.Commands { @@ -14,15 +15,15 @@ public class GetSolutionsFromTask: Commands { private readonly TelegramBotClient _botClient; private readonly IUserService _userService; - private readonly SolutionsServiceClient _solutionsServiceClient; - /*private readonly CoursesServiceClient _coursesServiceClient;*/ + private readonly ISolutionsServiceClient _solutionsServiceClient; + private readonly ICoursesServiceClient _coursesServiceClient; - public GetSolutionsFromTask(TelegramBot telegramBot, IUserService userService, SolutionsServiceClient solutionsServiceClient/*, CoursesServiceClient coursesServiceClient*/) + public GetSolutionsFromTask(TelegramBot telegramBot, IUserService userService, ISolutionsServiceClient solutionsServiceClient, ICoursesServiceClient coursesServiceClient) { _botClient = telegramBot.GetBot().Result; - _userService = userService; _solutionsServiceClient = solutionsServiceClient; - /*_coursesServiceClient = coursesServiceClient;*/ + _userService = userService; + _coursesServiceClient = coursesServiceClient; } public override string Name => CommandNames.GetSolutionsFromTask; @@ -33,8 +34,8 @@ public override async Task ExecuteAsync(Update update) var message = update.CallbackQuery.Data; var text = message.Split(' '); var solutions = _solutionsServiceClient.GetUserSolution(Int32.Parse(text[1]), user.StudentId).Result; - /*var task = _coursesServiceClient.GetTask(Int32.Parse(text[1])).Result; - var hw = _coursesServiceClient.GetHomework(task.HomeworkId).Result;*/ + var task = _coursesServiceClient.GetTask(Int32.Parse(text[1])).Result; + var hw = _coursesServiceClient.GetHomework(task.HomeworkId).Result; var rows = new List(); var cols = new List(); @@ -51,19 +52,20 @@ public override async Task ExecuteAsync(Update update) { rows.Add(cols.ToArray()); } + cols = new List(); var button = GetButton("Мои курсы", $"/courses"); cols.Add(button); - /*button = GetButton("Мои домашки", $"/homeworks {hw.CourseId}"); - cols.Add(button);*/ + button = GetButton("Мои домашки", $"/homeworks {hw.CourseId}"); + cols.Add(button); rows.Add(cols.ToArray()); cols = new List(); - /*button = GetButton("Мои задачи", $"/task {task.HomeworkId}"); - cols.Add(button);*/ + button = GetButton("Мои задачи", $"/task {task.HomeworkId}"); + cols.Add(button); rows.Add(cols.ToArray()); var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); - await _botClient.SendTextMessageAsync(user.ChatId, "", ParseMode.Markdown, replyMarkup:keyboardMarkup); + await _botClient.SendTextMessageAsync(user.ChatId, "123", ParseMode.Markdown, replyMarkup:keyboardMarkup);/// } private InlineKeyboardButton GetButton(string text, string callbackData) diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs index 5db7ef90d..1131bba06 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs @@ -31,16 +31,8 @@ public override async Task ExecuteAsync(Update update) var user = await _userService.GetOrCreateChatId(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); - var hw = _coursesServiceClient.GetHomework(Int32.Parse(text[1])).Result; //// - var tasks = hw.Tasks.ToArray(); - HomeworkTaskViewModel task = null; - foreach (var t in tasks) - { - if (t.Id == Int32.Parse(text[1])) - { - task = t; - } - } + var task = _coursesServiceClient.GetTask(Int64.Parse(text[1])).Result; //// + var hw = _coursesServiceClient.GetHomework(task.HomeworkId).Result; var rows = new List(); var cols = new List(); @@ -52,7 +44,7 @@ public override async Task ExecuteAsync(Update update) cols = new List(); button = GetButton("Мои задачи", $"/task {task.HomeworkId}"); cols.Add(button); - button = GetButton($"Решения {task.Title}", $"/solutioninfo {task.Id}"); + button = GetButton($"Решения {task.Title}", $"/solutions {task.Id}"); cols.Add(button); rows.Add(cols.ToArray()); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs index 37f112d89..bd46b0435 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs @@ -31,6 +31,7 @@ public override async Task ExecuteAsync(Update update) var message = update.CallbackQuery.Data; var text = message.Split(' '); var hw = _coursesServiceClient.GetHomework(Int32.Parse(text[1])).Result; + var course = _coursesServiceClient.GetCourseById(hw.CourseId, user.StudentId).Result; var tasks = hw.Tasks.ToArray(); var rows = new List(); var cols = new List(); @@ -68,7 +69,13 @@ public override async Task ExecuteAsync(Update update) rows.Add(cols.ToArray()); var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); - await _botClient.SendTextMessageAsync(user.ChatId, "Выберите task:", replyMarkup:keyboardMarkup); + await _botClient.SendTextMessageAsync( + user.ChatId, + $"Курс: {course.Name}\n" + + $"Homework: {hw.Title}" + + $"Описание: {hw.Description}" + + "\nВыберите task: ", + replyMarkup:keyboardMarkup); } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs index 62f8e906c..e30fa374f 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs @@ -7,8 +7,8 @@ namespace HwProj.TelegramBotService.API.Controllers { - [Route("api/[controller]")] [ApiController] + [Route("api/[controller]")] public class TelegramBotController : Controller { private readonly ICommandService _commandService; @@ -20,7 +20,7 @@ public TelegramBotController(ICommandService commandService, IUserService userSe _userService = userService; } - [HttpPost("/update")] + [HttpPost] public async Task Update(Update update) { @@ -41,11 +41,10 @@ public async Task Update(Update update) return Ok(); } - [HttpGet("/get/{studentId}")] + [HttpGet("get/{studentId}")] public async Task GetUser(string studentId) { - var userMoodel = await _userService.GetTelegramUserModelByStudentId(studentId); - return userMoodel; + return await _userService.GetTelegramUserModelByStudentId(studentId); } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/TelegramBot.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/TelegramBot.cs index 846cdf37f..b7f36f094 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/TelegramBot.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/TelegramBot.cs @@ -23,7 +23,7 @@ public async Task GetBot() _botClient = new TelegramBotClient(_configuration["Token"]); - var hook = $"{_configuration["Url"]}api/Telegram/update"; + var hook = $"{_configuration["Url"]}api/TelegramBot"; await _botClient.SetWebhookAsync(hook); return _botClient; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs index 229e33855..86c6e4497 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs @@ -37,7 +37,7 @@ public void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); services.AddScoped(); - /*services.AddScoped();*/ + services.AddScoped(); var httpClient = new HttpClient(); services.AddAuthServiceClient(httpClient, "http://localhost:5001"); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json index 6de43841e..a89d34a9e 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json @@ -17,5 +17,5 @@ "EventBusRetryCount": "5" }, "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://fad1-92-42-26-35.ngrok.io/" + "Url" : "https://70ae-92-42-26-35.ngrok.io/" } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs index 535eabbcf..6acfd82d8 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs @@ -21,7 +21,7 @@ public async Task GetTelegramUser(string studentId) { using var httpRequest = new HttpRequestMessage( HttpMethod.Get, - _telegramBotUri + $"api/Telegram/get/{studentId}"); + _telegramBotUri + $"api/TelegramBot/get/{studentId}"); var response = await _httpClient.SendAsync(httpRequest); return await response.DeserializeAsync(); From 026119196579d29af6d74b53541036c2b9364381 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Sat, 27 Nov 2021 01:02:35 +0300 Subject: [PATCH 06/19] wip --- .../EventHandlers/NewCourseMateHandler.cs | 2 +- .../HwProj.NotificationsService.API/Startup.cs | 2 +- .../HwProj.NotificationsService.API/appsettings.json | 3 ++- HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs | 6 +++--- .../ConfigurationExtensions.cs | 6 ++---- 5 files changed, 9 insertions(+), 10 deletions(-) diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs index d6e13b450..75cb02b2b 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs @@ -28,7 +28,7 @@ public async Task HandleAsync(NewCourseMateEvent @event) foreach (var m in @event.MentorIds.Split('/')) { - await _notificationRepository.AddAsync(new Notification + var notification = new Notification { Sender = "CourseService", Body = diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs index 72aea5110..527e739d6 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs @@ -60,7 +60,7 @@ public void ConfigureServices(IServiceCollection services) services.AddAuthServiceClient(); services.AddCoursesServiceClient(); services.AddSolutionServiceClient(); - services.AddTelegramBotClient(httpClient, "http://localhost:5009"); + services.AddTelegramBotClient(); services.ConfigureHwProjServices("Notifications API"); } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json index b976c11e1..f365f8ed7 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json @@ -21,7 +21,8 @@ "Auth": "http://localhost:5001", "Courses": "http://localhost:5002", "Notifications": "http://localhost:5006", - "Solutions": "http://localhost:5007" + "Solutions": "http://localhost:5007", + "TelegramBot" : "http://localhost:5009" }, "Telegram": { "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs index 86c6e4497..060bf56cb 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs @@ -40,9 +40,9 @@ public void ConfigureServices(IServiceCollection services) services.AddScoped(); var httpClient = new HttpClient(); - services.AddAuthServiceClient(httpClient, "http://localhost:5001"); - services.AddCoursesServiceClient(httpClient, "http://localhost:5002"); - services.AddSolutionServiceClient(httpClient, "http://localhost:5007"); + services.AddAuthServiceClient(); + services.AddCoursesServiceClient(); + services.AddSolutionServiceClient(); services.AddEventBus(Configuration); services.ConfigureHwProjServices("Telegram API"); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ConfigurationExtensions.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ConfigurationExtensions.cs index 40b6abbcc..27bf046e3 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ConfigurationExtensions.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ConfigurationExtensions.cs @@ -6,11 +6,9 @@ namespace HwProj.TelegramBotService.Client { public static class ConfigurationExtensions { - public static IServiceCollection AddTelegramBotClient(this IServiceCollection services, HttpClient httpClient, - string baseUri) + public static IServiceCollection AddTelegramBotClient(this IServiceCollection services) { - var telegramBotServiceClient = new TelegramBotServiceClient(httpClient, new Uri(baseUri)); - services.AddSingleton(telegramBotServiceClient); + services.AddScoped(); return services; } } From a9d6267f86f404710fcfa2d0c4d73fdcc8c10b51 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Mon, 29 Nov 2021 14:53:16 +0300 Subject: [PATCH 07/19] wip --- .../ConfigurationExtensions.cs | 5 +- .../LecturerAcceptToCourseEventHandler.cs | 1 - .../StudentPassTaskEventHandler.cs | 1 - .../Startup.cs | 2 +- .../appsettings.json | 2 +- .../Services/ISolutionsService.cs | 2 + .../Services/SolutionsService.cs | 52 ++++++++++++-- .../Commands/CommandNames.cs | 3 + .../Commands/Commands.cs | 8 +++ .../Commands/GetAllCourses.cs | 35 ++++++++++ .../Commands/GetCourses.cs | 31 +++------ .../Commands/GetHomeworks.cs | 24 +++---- .../Commands/GetSolutionInfo.cs | 31 ++++----- .../Commands/GetSolutionsFromTask.cs | 37 ++++------ .../Commands/GetStatistics.cs | 69 +++++++++++++++++++ .../Commands/GetTaskInfo.cs | 35 ++++------ .../Commands/GetTasks.cs | 33 +++------ .../Commands/SendSolution.cs | 36 ++++++++++ .../Commands/StartCommand.cs | 6 +- .../Models/TelegramUserModel.cs | 8 ++- .../Service/CommandService.cs | 7 +- .../Service/IUserService.cs | 3 + .../Service/UserService.cs | 55 ++++++++++++--- .../HwProj.TelegramBotService.API/Startup.cs | 7 +- .../appsettings.json | 9 ++- .../ConfigurationExtensions.cs | 4 +- .../TelegramBotServiceClient.cs | 9 +-- hwproj.front/package-lock.json | 39 +++++++++++ hwproj.front/package.json | 8 ++- hwproj.front/src/components/Profile.tsx | 32 ++++++--- 30 files changed, 422 insertions(+), 172 deletions(-) create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs diff --git a/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs b/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs index 34c6839bf..82d58102d 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs @@ -1,6 +1,6 @@ -using System; -using System.Net.Http; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; namespace HwProj.CoursesService.Client { @@ -9,6 +9,7 @@ public static class ConfigurationExtensions public static IServiceCollection AddCoursesServiceClient(this IServiceCollection services) { services.AddScoped(); + services.TryAddSingleton(); return services; } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs index 23e77c17c..789dc89a1 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs @@ -6,7 +6,6 @@ using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; using HwProj.NotificationsService.API.Services; -using HwProj.TelegramBotService.Client; namespace HwProj.NotificationsService.API.EventHandlers { diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs index 21c4fc334..3c303e316 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs @@ -1,6 +1,5 @@ using System; using System.Threading.Tasks; -using HwProj.AuthService.API.Events; using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs index 527e739d6..72885ddd6 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs @@ -38,7 +38,7 @@ public Startup(IConfiguration configuration) public void ConfigureServices(IServiceCollection services) { - var connectionString = Configuration.GetConnectionString("DefaultConnection"); + var connectionString = ConnectionString.GetConnectionString(Configuration); services.AddDbContext(options => options.UseSqlServer(connectionString)); services.AddScoped(); services.AddScoped(); diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json index f365f8ed7..c1d3b63a2 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json @@ -26,6 +26,6 @@ }, "Telegram": { "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://70ae-92-42-26-35.ngrok.io/" + "Url" : "https://aa14-92-42-26-35.ngrok.io/" } } diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs index 137c88d3f..c58b7f31f 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs @@ -16,6 +16,8 @@ public interface ISolutionsService Task PostOrUpdateAsync(long taskId, Solution solution); + /*Task PostOrUpdateFromTelegramAsync(long taskId, string githubUrl, string comment);*/ + Task RateSolutionAsync(long solutionId, int newRating, string lecturerComment); Task DeleteSolutionAsync(long solutionId); diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs index 5605e6b26..79d8d4fba 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs @@ -22,7 +22,9 @@ public class SolutionsService : ISolutionsService private readonly IMapper _mapper; private readonly ICoursesServiceClient _coursesServiceClient; private readonly IAuthServiceClient _authServiceClient; - public SolutionsService(ISolutionsRepository solutionsRepository, IEventBus eventBus, IMapper mapper, ICoursesServiceClient coursesServiceClient, IAuthServiceClient authServiceClient) + + public SolutionsService(ISolutionsRepository solutionsRepository, IEventBus eventBus, IMapper mapper, + ICoursesServiceClient coursesServiceClient, IAuthServiceClient authServiceClient) { _solutionsRepository = solutionsRepository; _eventBus = eventBus; @@ -47,11 +49,53 @@ public async Task GetTaskSolutionsFromStudentAsync(long taskId, stri .FindAll(solution => solution.TaskId == taskId && solution.StudentId == studentId) .ToArrayAsync(); } - - + + public async Task PostOrUpdateAsync(long taskId, Solution solution) { solution.PublicationDate = DateTime.UtcNow; + var allSolutionsForTask = await GetTaskSolutionsFromStudentAsync(taskId, solution.StudentId); + var currentSolution = allSolutionsForTask.FirstOrDefault(s => s.Id == solution.Id); + var solutionModel = _mapper.Map(solution); + var task = await _coursesServiceClient.GetTask(solution.TaskId); + var taskModel = _mapper.Map(task); + var homework = await _coursesServiceClient.GetHomework(task.HomeworkId); + var courses = await _coursesServiceClient.GetCourseById(homework.CourseId, solution.StudentId); + var student = await _authServiceClient.GetAccountData((solutionModel.StudentId)); + var studentModel = _mapper.Map(student); + _eventBus.Publish(new StudentPassTaskEvent(courses, solutionModel, studentModel, taskModel)); + + if (currentSolution == null) + { + solution.TaskId = taskId; + var id = await _solutionsRepository.AddAsync(solution); + return id; + } + + await _solutionsRepository.UpdateAsync(currentSolution.Id, s => new Solution() + { + State = SolutionState.Rated, + Comment = solution.Comment, + GithubUrl = solution.GithubUrl, + PublicationDate = solution.PublicationDate, + } + ); + + return solution.Id; + } + + /*public async Task PostOrUpdateFromTelegramAsync(long taskId, string githubUrl, string comment, string studentId) + { + var solution = new Solution { + Id = , + GithubUrl = githubUrl, + Comment = comment, + State = SolutionState.Rated, + StudentId = studentId, + GroupId = , + TaskId = taskId, + PublicationDate = DateTime.Now, + LecturerComment = null}; var allSolutionsForTask= await GetTaskSolutionsFromStudentAsync(taskId, solution.StudentId); var currentSolution = allSolutionsForTask.FirstOrDefault(s => s.Id == solution.Id); var solutionModel = _mapper.Map(solution); @@ -80,7 +124,7 @@ public async Task PostOrUpdateAsync(long taskId, Solution solution) ); return solution.Id; - } + }*/ public async Task RateSolutionAsync(long solutionId, int newRating, string lecturerComment) { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs index 2bbf760cc..95cfc1e6c 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs @@ -4,10 +4,13 @@ public static class CommandNames { public const string StartCommand = "/start"; public const string GetCourses = "/courses"; // /courses {courseId} + public const string GetAllCourses = "/courses_all"; // /courses_all {courseId} public const string GetHomeworks = "/homeworks"; // /homeworks {courseId} public const string GetTasks = "/task"; // /task {homeworksId} public const string GetTaskInfo = "/taskinfo"; // /taskinfo {taskId} public const string GetSolutionsFromTask = "/solutions"; // /solutions {taskId} public const string GetSolutionInfo = "/solutioninfo"; // /solutioninfo {solutionId} + public const string GetStatistics = "/statistics"; // /statistics {courseId} + public const string SendSolution = "/send_solution"; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/Commands.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/Commands.cs index d44385a77..fb42457e7 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/Commands.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/Commands.cs @@ -1,5 +1,6 @@ using System.Threading.Tasks; using Telegram.Bot.Types; +using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.TelegramBotService.API.Commands { @@ -8,5 +9,12 @@ public abstract class Commands public abstract string Name { get; } public abstract Task ExecuteAsync(Update update); + + protected InlineKeyboardButton GetButton(string text, string callbackData) + => new InlineKeyboardButton + { + Text = text, + CallbackData = callbackData + }; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs new file mode 100644 index 000000000..a6fca71b6 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs @@ -0,0 +1,35 @@ +using System.Threading.Tasks; +using HwProj.CoursesService.Client; +using HwProj.TelegramBotService.API.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; +using Telegram.Bot.Types.ReplyMarkups; + +namespace HwProj.TelegramBotService.API.Commands +{ + public class GetAllCourses : Commands + { + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + private readonly ICoursesServiceClient _coursesServiceClient; + + public GetAllCourses(TelegramBot telegramBot, IUserService userService, ICoursesServiceClient coursesServiceClient) + { + _botClient = telegramBot.GetBot().Result; + _userService = userService; + _coursesServiceClient = coursesServiceClient; + } + + public override string Name => CommandNames.GetAllCourses; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.GetOrCreateChatId(update); + + var courses = _coursesServiceClient.GetAllCourses().Result; + + await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!", ParseMode.Markdown/*, replyMarkup:inlineKeyboard*/); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs index 2ac354bc7..6b4978440 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs @@ -4,6 +4,7 @@ using HwProj.TelegramBotService.API.Service; using Telegram.Bot; using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.TelegramBotService.API.Commands @@ -26,30 +27,20 @@ public GetCourses(TelegramBot telegramBot, ICoursesServiceClient coursesServiceC public override async Task ExecuteAsync(Update update) { var user = await _userService.GetOrCreateChatId(update); - var courses = _coursesServiceClient.GetAllUserCourses(user.StudentId).Result; + var courses = _coursesServiceClient.GetAllUserCourses(user.AccountId).Result; - var rows = new List(); - var cols = new List(); - for (var i = 1; i < courses.Length + 1; i++) - { - var k = new InlineKeyboardButton - { - Text = courses[i - 1].Name, - CallbackData = $"/homeworks {courses[i - 1].Id}" - }; - cols.Add(k); - if (i % 3 != 0) continue; - rows.Add(cols.ToArray()); - cols = new List(); - } - - if (courses.Length < 3) + await _botClient.SendTextMessageAsync(user.ChatId, "*Выберите курс для просмотра домашних работ или статистики:*", ParseMode.Markdown); + + foreach (var course in courses) { + var rows = new List(); + var cols = new List(); + cols.Add(GetButton("Домашние работы", $"/homeworks {course.Id}")); + cols.Add(GetButton("Cтатистика", $"/statistics {course.Id}")); rows.Add(cols.ToArray()); + var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); + await _botClient.SendTextMessageAsync(user.ChatId, "Курс:" + $" {course.Name}", parseMode: ParseMode.Html, replyMarkup:keyboardMarkup); } - var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); - - await _botClient.SendTextMessageAsync(user.ChatId, "Выберите курс:", replyMarkup:keyboardMarkup); } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs index 2807eaf05..095b4306d 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs @@ -5,6 +5,7 @@ using HwProj.TelegramBotService.API.Service; using Telegram.Bot; using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.TelegramBotService.API.Commands @@ -30,14 +31,13 @@ public override async Task ExecuteAsync(Update update) var message = update.CallbackQuery.Data; var text = message.Split(' '); var homeworks = _coursesServiceClient.GetAllHomeworkByCourse(Int32.Parse(text[1])).Result; - var course = _coursesServiceClient.GetCourseById(Int32.Parse(text[1]), user.StudentId).Result; + var course = _coursesServiceClient.GetCourseById(Int32.Parse(text[1]), user.AccountId).Result; var rows = new List(); var cols = new List(); for (var i = 1; i < homeworks.Length + 1; i++) { - var k = GetButton(homeworks[i - 1].Title, $"/task {homeworks[i - 1].Id}"); - cols.Add(k); + cols.Add(GetButton(homeworks[i - 1].Title, $"/task {homeworks[i - 1].Id}")); if (i % 3 != 0) continue; rows.Add(cols.ToArray()); cols = new List(); @@ -46,20 +46,16 @@ public override async Task ExecuteAsync(Update update) { rows.Add(cols.ToArray()); } - - var button = GetButton("Мои курсы", $"/courses"); + cols = new List(); - cols.Add(button); + cols.Add(GetButton("Мои курсы", $"/courses")); rows.Add(cols.ToArray()); var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); - await _botClient.SendTextMessageAsync(user.ChatId, $"Выберите homework из курса {course.Name}", replyMarkup:keyboardMarkup); + await _botClient.SendTextMessageAsync( + user.ChatId, + $"Курс: {course.Name}\nВыберите домашнюю работу", + parseMode: ParseMode.Html, + replyMarkup:keyboardMarkup); } - - private InlineKeyboardButton GetButton(string text, string callbackData) - => new InlineKeyboardButton - { - Text = text, - CallbackData = callbackData - }; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs index c6a522ffa..40d33874a 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs @@ -6,6 +6,7 @@ using HwProj.TelegramBotService.API.Service; using Telegram.Bot; using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.TelegramBotService.API.Commands @@ -33,39 +34,31 @@ public override async Task ExecuteAsync(Update update) var user = await _userService.GetOrCreateChatId(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); - var solution = _solutionsServiceClient.GetSolutionById(Int32.Parse(text[1])).Result; + var solution =_solutionsServiceClient.GetSolutionById(Int32.Parse(text[1])).Result; var task = _coursesServiceClient.GetTask(solution.TaskId).Result; var hw = _coursesServiceClient.GetHomework(task.HomeworkId).Result; var rows = new List(); var cols = new List(); - var button = GetButton("Мои курсы", $"/courses"); - cols.Add(button); - button = GetButton("Мои домашки", $"/homeworks {hw.CourseId}"); - cols.Add(button); + cols.Add(GetButton($"Решения {task.Title}", $"/solutions {task.Id}")); + cols.Add(GetButton("Мои курсы", $"/courses")); rows.Add(cols.ToArray()); cols = new List(); - button = GetButton("Мои задачи", $"/task {task.HomeworkId}"); - cols.Add(button); - button = GetButton($"Решения {task.Title}", $"/solutions {task.Id}"); - cols.Add(button); + cols.Add(GetButton("Мои домашки", $"/homeworks {hw.CourseId}")); + cols.Add(GetButton("Мои задачи", $"/task {task.HomeworkId}")); + rows.Add(cols.ToArray()); + cols = new List(); + cols.Add(new InlineKeyboardButton {Text = "Github", Url = solution.GithubUrl}); rows.Add(cols.ToArray()); var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); await _botClient.SendTextMessageAsync(user.ChatId, - $"Отзыв преподователя: {solution.LecturerComment}." + - $"\nОценка: {solution.Rating}." + - $"\nGithub: {solution.GithubUrl}", + $"Отзыв преподователя: {solution.LecturerComment}." + + $"\nОценка: {solution.Rating}/{task.MaxRating}.", + parseMode: ParseMode.Html, replyMarkup:keyboardMarkup); } - - private InlineKeyboardButton GetButton(string text, string callbackData) - => new InlineKeyboardButton - { - Text = text, - CallbackData = callbackData - }; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs index ecfe5abdf..bbf98cb00 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs @@ -33,46 +33,37 @@ public override async Task ExecuteAsync(Update update) var user = await _userService.GetOrCreateChatId(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); - var solutions = _solutionsServiceClient.GetUserSolution(Int32.Parse(text[1]), user.StudentId).Result; + var solutions = _solutionsServiceClient.GetUserSolution(Int32.Parse(text[1]), user.AccountId).Result; var task = _coursesServiceClient.GetTask(Int32.Parse(text[1])).Result; var hw = _coursesServiceClient.GetHomework(task.HomeworkId).Result; + var course = _coursesServiceClient.GetCourseById(hw.CourseId, user.AccountId).Result; var rows = new List(); var cols = new List(); for (var i = 1; i < solutions.Length + 1; i++) { - var k = GetButton($"Попытка {i}", $"/solutioninfo {solutions[i - 1].Id}"); - cols.Add(k); + cols.Add(GetButton($"Попытка {i}", $"/solutioninfo {solutions[i - 1].Id}")); if (i % 3 != 0) continue; rows.Add(cols.ToArray()); cols = new List(); } - - if (solutions.Length < 3) - { - rows.Add(cols.ToArray()); - } - cols = new List(); - var button = GetButton("Мои курсы", $"/courses"); - cols.Add(button); - button = GetButton("Мои домашки", $"/homeworks {hw.CourseId}"); - cols.Add(button); + rows.Add(cols.ToArray()); cols = new List(); - button = GetButton("Мои задачи", $"/task {task.HomeworkId}"); - cols.Add(button); + cols.Add(GetButton("Мои курсы", $"/courses")); + cols.Add(GetButton("Мои домашки", $"/homeworks {hw.CourseId}")); + cols.Add(GetButton("Мои задачи", $"/task {task.HomeworkId}")); rows.Add(cols.ToArray()); var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); - await _botClient.SendTextMessageAsync(user.ChatId, "123", ParseMode.Markdown, replyMarkup:keyboardMarkup);/// + await _botClient.SendTextMessageAsync(user.ChatId, + $"Курс: {course.Name}" + + $"\nДомашнаяя работа: {hw.Title}" + + $"\nЗадача: {task.Title}" + + "\nВыберите решение:", + parseMode: ParseMode.Html, + replyMarkup : keyboardMarkup); } - - private InlineKeyboardButton GetButton(string text, string callbackData) - => new InlineKeyboardButton - { - Text = text, - CallbackData = callbackData - }; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs new file mode 100644 index 000000000..6aa3d08fe --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs @@ -0,0 +1,69 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using HwProj.CoursesService.Client; +using HwProj.SolutionsService.Client; +using HwProj.TelegramBotService.API.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; +using Telegram.Bot.Types.ReplyMarkups; + +namespace HwProj.TelegramBotService.API.Commands +{ + public class GetStatistics: Commands + { + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + private readonly ISolutionsServiceClient _solutionsServiceClient; + private readonly ICoursesServiceClient _coursesServiceClient; + + public GetStatistics(TelegramBot telegramBot, IUserService userService, ICoursesServiceClient coursesServiceClient, ISolutionsServiceClient solutionsServiceClient) + { + _botClient = telegramBot.GetBot().Result; + _userService = userService; + _coursesServiceClient = coursesServiceClient; + _solutionsServiceClient = solutionsServiceClient; + } + + public override string Name => CommandNames.GetStatistics; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.GetOrCreateChatId(update); + var message = update.CallbackQuery.Data; + var text = message.Split(' '); + var course = _coursesServiceClient.GetCourseById(Int64.Parse(text[1]), user.AccountId).Result; + var statistics = _solutionsServiceClient.GetCourseStatistics(course.Id, course.MentorIds.Split("/")[0]).Result; + var statistic = statistics.First(cm => cm.Id == user.AccountId); + int maxRating = 0; + int? studentRating = 0; + foreach (var hw in statistic.Homeworks) + { + foreach (var task in hw.Tasks) + { + studentRating += task.Solution.Max(cm => cm.Rating); + } + } + + var hwModel = _coursesServiceClient.GetAllHomeworkByCourse(course.Id).Result; + foreach (var hw in hwModel) + { + maxRating += hw.Tasks.Max(cm => cm.MaxRating); + } + + if (studentRating == null) + { + studentRating = 0; + } + + var inlineKeyboard = new InlineKeyboardMarkup(GetButton("Мои курсы", "/courses")); + + await _botClient.SendTextMessageAsync(user.ChatId, + $"Курс: {course.Name}." + + $"\nБаллы: {studentRating}/{maxRating}", + parseMode: ParseMode.Html, + replyMarkup:inlineKeyboard); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs index 1131bba06..d6caa3906 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs @@ -6,6 +6,7 @@ using HwProj.TelegramBotService.API.Service; using Telegram.Bot; using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.TelegramBotService.API.Commands @@ -31,39 +32,29 @@ public override async Task ExecuteAsync(Update update) var user = await _userService.GetOrCreateChatId(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); - var task = _coursesServiceClient.GetTask(Int64.Parse(text[1])).Result; //// + var task = _coursesServiceClient.GetTask(Int64.Parse(text[1])).Result; var hw = _coursesServiceClient.GetHomework(task.HomeworkId).Result; var rows = new List(); var cols = new List(); - var button = GetButton("Мои курсы", $"/courses"); - cols.Add(button); - button = GetButton("Мои домашки", $"/homeworks {hw.CourseId}"); - cols.Add(button); + cols.Add(GetButton($"Решения {task.Title}", $"/solutions {task.Id}")); rows.Add(cols.ToArray()); cols = new List(); - button = GetButton("Мои задачи", $"/task {task.HomeworkId}"); - cols.Add(button); - button = GetButton($"Решения {task.Title}", $"/solutions {task.Id}"); - cols.Add(button); + cols.Add(GetButton("Мои курсы", $"/courses")); + cols.Add(GetButton("Мои домашки", $"/homeworks {hw.CourseId}")); + cols.Add(GetButton("Мои задачи", $"/task {task.HomeworkId}")); rows.Add(cols.ToArray()); var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); - + await _botClient.SendTextMessageAsync(user.ChatId, - $"Название: {task.Title}." + - $"\nОписание: {task.Description}." + - $"\nДата публикации: {task.PublicationDate}." + - $"\nДедлайн: {task.DeadlineDate}." + - $"\nМаксимальный балл: {task.MaxRating}.", + $"Название {task.Title}." + + $"\nОписание: {task.Description}." + + $"\nДата публикации: {task.PublicationDate.Date}." + + $"\nДедлайн: {task.DeadlineDate}." + + $"\nМаксимальный балл: {task.MaxRating}.", + parseMode: ParseMode.Html, replyMarkup:keyboardMarkup); } - - private InlineKeyboardButton GetButton(string text, string callbackData) - => new InlineKeyboardButton - { - Text = text, - CallbackData = callbackData - }; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs index bd46b0435..24e35775e 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs @@ -5,6 +5,7 @@ using HwProj.TelegramBotService.API.Service; using Telegram.Bot; using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.TelegramBotService.API.Commands @@ -31,18 +32,13 @@ public override async Task ExecuteAsync(Update update) var message = update.CallbackQuery.Data; var text = message.Split(' '); var hw = _coursesServiceClient.GetHomework(Int32.Parse(text[1])).Result; - var course = _coursesServiceClient.GetCourseById(hw.CourseId, user.StudentId).Result; + var course = _coursesServiceClient.GetCourseById(hw.CourseId, user.AccountId).Result; var tasks = hw.Tasks.ToArray(); var rows = new List(); var cols = new List(); for (var i = 1; i < tasks.Length + 1; i++) { - var k = new InlineKeyboardButton - { - Text = tasks[i - 1].Title, - CallbackData = $"/taskinfo {tasks[i - 1].Id}" - }; - cols.Add(k); + cols.Add(GetButton(tasks[i - 1].Title, $"/taskinfo {tasks[i - 1].Id}")); if (i % 3 != 0) continue; rows.Add(cols.ToArray()); cols = new List(); @@ -53,28 +49,19 @@ public override async Task ExecuteAsync(Update update) rows.Add(cols.ToArray()); } - var button = new InlineKeyboardButton - { - Text = "Мои курсы", - CallbackData = $"/courses" - }; cols = new List(); - cols.Add(button); - button = new InlineKeyboardButton - { - Text = "Мои домашки", - CallbackData = $"/homeworks {hw.CourseId}" - }; - cols.Add(button); + cols.Add(GetButton("Мои курсы", $"/courses")); + cols.Add(GetButton("Мои домашки", $"/homeworks {hw.CourseId}")); rows.Add(cols.ToArray()); var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); await _botClient.SendTextMessageAsync( user.ChatId, - $"Курс: {course.Name}\n" + - $"Homework: {hw.Title}" + - $"Описание: {hw.Description}" + - "\nВыберите task: ", + $"Курс: {course.Name}" + + $"\nHomework: {hw.Title}" + + $"\nОписание: {hw.Description}" + + "\nВыберите задачу:", + parseMode: ParseMode.Html, replyMarkup:keyboardMarkup); } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs new file mode 100644 index 000000000..b86c9b005 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs @@ -0,0 +1,36 @@ +using System.Threading.Tasks; +using HwProj.SolutionsService.Client; +using HwProj.TelegramBotService.API.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + +namespace HwProj.TelegramBotService.API.Commands +{ + public class SendSolution : Commands + { + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + private readonly ISolutionsServiceClient _solutionsServiceClient; + + public SendSolution(TelegramBot telegramBot, IUserService userService, + ISolutionsServiceClient solutionsServiceClient) + { + _botClient = telegramBot.GetBot().Result; + _userService = userService; + _solutionsServiceClient = solutionsServiceClient; + } + + public override string Name => CommandNames.SendSolution; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.GetOrCreateChatId(update); + + /*await _solutionsServiceClient.PostSolution();*/ + + await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!", + ParseMode.Markdown /*, replyMarkup:inlineKeyboard*/); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs index 922d9e60e..73f486c47 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs @@ -24,11 +24,7 @@ public override async Task ExecuteAsync(Update update) { var user = await _userService.GetOrCreateChatId(update); - var inlineKeyboard = new InlineKeyboardMarkup(new InlineKeyboardButton - { - Text = "Мои курсы", - CallbackData = "/courses" - }); + var inlineKeyboard = new InlineKeyboardMarkup(GetButton("Мои курсы", "/courses")); await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!", ParseMode.Markdown, replyMarkup:inlineKeyboard); } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs index 0e4f89c54..51f1a958d 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs @@ -4,10 +4,12 @@ public class TelegramUserModel { public long Id { get; set; } - public string StudentId { get; set; } - public long ChatId { get; set; } + + public string AccountId { get; set; } + + public bool IsLecture { get; set; } - public bool IsRegister { get; set; } + public bool IsRegistered { get; set; } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs index db814dc5e..2a3401116 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs @@ -39,10 +39,10 @@ public async Task Execute(Update update) case "/start": await ExecuteCommand(CommandNames.StartCommand, update); break; - /*case "/courses": + case "/courses": await ExecuteCommand(CommandNames.GetCourses, update); break; - case "/homeworks": + /*case "/homeworks": await ExecuteCommand(CommandNames.GetHomeworks, update); break;*/ } @@ -57,6 +57,9 @@ public async Task Execute(Update update) case "/homeworks": await ExecuteCommand(CommandNames.GetHomeworks, update); break; + case "/statistics": + await ExecuteCommand(CommandNames.GetStatistics, update); + break; case "/task": await ExecuteCommand(CommandNames.GetTasks, update); break; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs index f6c4b1021..4d86738c6 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs @@ -7,6 +7,9 @@ namespace HwProj.TelegramBotService.API.Service public interface IUserService { Task GetOrCreateChatId(Update update); + + /*Task CreateChatId(Update update); + */ Task GetTelegramUserModelByStudentId(string studentId); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs index df225ba7f..213204bb3 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs @@ -1,5 +1,6 @@ using System.Threading.Tasks; using HwProj.AuthService.Client; +using HwProj.Models.AuthService.DTO; using HwProj.TelegramBotService.API.Models; using Microsoft.EntityFrameworkCore; using Telegram.Bot.Types; @@ -20,6 +21,7 @@ public UserService(TelegramBotContext context, IAuthServiceClient authClient) public async Task GetOrCreateChatId(Update update) { string studentId; + AccountDataDto studentModel = null; TelegramUserModel newUser; if (update.CallbackQuery == null) { @@ -27,33 +29,37 @@ public async Task GetOrCreateChatId(Update update) var text = message.Split(' '); if (text[0] == "/start" && text.Length > 1) { - studentId= _authClient.FindByEmailAsync(text[1]).Result; + studentId = _authClient.FindByEmailAsync(text[1]).Result; + studentModel = _authClient.GetAccountData(studentId).Result; } else { - studentId = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result.StudentId; + return await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id); } newUser = new TelegramUserModel { Id = update.Message.Chat.Id, - StudentId = studentId, ChatId = update.Message.Chat.Id, - IsRegister = true + AccountId = studentId, + IsLecture = studentModel.Role == "Lecture", + IsRegistered = true }; } else { var message = update.CallbackQuery.Data; var text = message.Split(' '); - studentId = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id).Result.StudentId; - + studentId = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id).Result.AccountId; + studentModel = _authClient.GetAccountData(studentId).Result; + newUser = new TelegramUserModel { Id = update.CallbackQuery.Message.Chat.Id, - StudentId = studentId, ChatId = update.CallbackQuery.Message.Chat.Id, - IsRegister = true + AccountId = studentId, + IsLecture = studentModel.Role == "Lecture", + IsRegistered = true }; } var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == newUser.ChatId); @@ -68,9 +74,40 @@ public async Task GetOrCreateChatId(Update update) return result.Entity; } + + /*public async Task CreateChatId(Update update) + { + string studentId; + AccountDataDto studentModel = null; + TelegramUserModel newUser; + if (update.CallbackQuery == null) + { + newUser = new TelegramUserModel + { + Id = update.Message.Chat.Id, + ChatId = update.Message.Chat.Id, + AccountId = studentId, + IsLecture = studentModel.Role == "Lecture", + IsRegistered = true + }; + } + + var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == newUser.ChatId); + + if (user != null) + { + return user; + } + + var result = await _context.TelegramUser.AddAsync(newUser); + await _context.SaveChangesAsync(); + + return result.Entity; + }*/ + public async Task GetTelegramUserModelByStudentId(string studentId) - => _context.TelegramUser.FirstOrDefaultAsync(x => x.StudentId == studentId).Result; + => _context.TelegramUser.FirstOrDefaultAsync(x => x.AccountId == studentId).Result; public async Task GetTelegramUserModelByChatId(long ChatId) => _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == ChatId).Result; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs index 060bf56cb..096aca69d 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs @@ -1,5 +1,4 @@ using System; -using System.Net.Http; using HwProj.AuthService.Client; using HwProj.CoursesService.Client; using HwProj.SolutionsService.Client; @@ -38,11 +37,13 @@ public void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + /*services.AddScoped();*/ - var httpClient = new HttpClient(); + services.AddHttpClient(); services.AddAuthServiceClient(); - services.AddCoursesServiceClient(); services.AddSolutionServiceClient(); + services.AddCoursesServiceClient(); services.AddEventBus(Configuration); services.ConfigureHwProjServices("Telegram API"); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json index a89d34a9e..42173e101 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json @@ -16,6 +16,13 @@ "EventBusQueueName": "TelegramBot", "EventBusRetryCount": "5" }, + "Services": { + "Auth": "http://localhost:5001", + "Courses": "http://localhost:5002", + "Notifications": "http://localhost:5006", + "Solutions": "http://localhost:5007", + "TelegramBot" : "http://localhost:5009" + }, "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://70ae-92-42-26-35.ngrok.io/" + "Url" : "https://aa14-92-42-26-35.ngrok.io/" } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ConfigurationExtensions.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ConfigurationExtensions.cs index 27bf046e3..7dad352c8 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ConfigurationExtensions.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ConfigurationExtensions.cs @@ -1,6 +1,4 @@ -using System; -using System.Net.Http; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; namespace HwProj.TelegramBotService.Client { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs index 6acfd82d8..ad324c862 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using HwProj.HttpUtils; using HwProj.TelegramBotService.API.Models; +using Microsoft.Extensions.Configuration; namespace HwProj.TelegramBotService.Client { @@ -11,12 +12,12 @@ public class TelegramBotServiceClient : ITelegramBotServiceClient private readonly HttpClient _httpClient; private readonly Uri _telegramBotUri; - public TelegramBotServiceClient(HttpClient httpClient, Uri telegramBotUri) + public TelegramBotServiceClient(IHttpClientFactory clientFactory, IConfiguration configuration) { - _httpClient = httpClient; - _telegramBotUri = telegramBotUri; + _httpClient = clientFactory.CreateClient(); + _telegramBotUri = new Uri(configuration.GetSection("Services")["TelegramBot"]); } - + public async Task GetTelegramUser(string studentId) { using var httpRequest = new HttpRequestMessage( diff --git a/hwproj.front/package-lock.json b/hwproj.front/package-lock.json index 0cfda625e..95ec1ccb2 100644 --- a/hwproj.front/package-lock.json +++ b/hwproj.front/package-lock.json @@ -6569,6 +6569,14 @@ "eslint-visitor-keys": "^2.0.0" } }, + "@v9v/ts-react-telegram-login": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@v9v/ts-react-telegram-login/-/ts-react-telegram-login-1.1.1.tgz", + "integrity": "sha512-aWzELPBBfZET5L7Ud3IPApCz2qzJUXF1lBDFIpaKnG6vehe4F9GT7Ss+A/buOTYh1VgraQ03oh3f/ncNy1AdhA==", + "requires": { + "react": "^16.13.1" + } + }, "@webassemblyjs/ast": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.9.0.tgz", @@ -6774,6 +6782,11 @@ "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-7.2.0.tgz", "integrity": "sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA==" }, + "add": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/add/-/add-2.0.6.tgz", + "integrity": "sha1-JI8Kn25aUo7yKV2+7DBTITCuIjU=" + }, "address": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/address/-/address-1.1.2.tgz", @@ -17293,6 +17306,11 @@ "word-wrap": "^1.2.3" } }, + "or": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/or/-/or-0.2.0.tgz", + "integrity": "sha1-mQTqYeJZQ/k14g9PR0ngoUGoK2o=" + }, "original": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/original/-/original-1.0.2.tgz", @@ -19658,6 +19676,22 @@ "refractor": "^3.1.0" } }, + "react-telegram-auth": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/react-telegram-auth/-/react-telegram-auth-1.0.3.tgz", + "integrity": "sha512-0OXTscv1rEfC//UzO9pO2Pxlkqw7t4tOBIOOwfRw+F4VxgQy5f0Z8bw9wa7CrUEKm7Xcs/bNhe8PGas5jg6GhA==", + "requires": { + "react": "^16.13.1" + } + }, + "react-telegram-login": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/react-telegram-login/-/react-telegram-login-1.1.2.tgz", + "integrity": "sha512-pDP+bvfaklWgnK5O6yvZnIwgky0nnYUU6Zhk0EjdMSkPsLQoOzZRsXIoZnbxyBXhi7346bsxMH+EwwJPTxClDw==", + "requires": { + "react": "^16.13.1" + } + }, "react-textarea-autosize": { "version": "8.3.3", "resolved": "https://registry.npmjs.org/react-textarea-autosize/-/react-textarea-autosize-8.3.3.tgz", @@ -24584,6 +24618,11 @@ } } }, + "yarn": { + "version": "1.22.17", + "resolved": "https://registry.npmjs.org/yarn/-/yarn-1.22.17.tgz", + "integrity": "sha512-H0p241BXaH0UN9IeH//RT82tl5PfNraVpSpEoW+ET7lmopNC61eZ+A+IDvU8FM6Go5vx162SncDL8J1ZjRBriQ==" + }, "yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/hwproj.front/package.json b/hwproj.front/package.json index 1fef04187..053bb40d5 100644 --- a/hwproj.front/package.json +++ b/hwproj.front/package.json @@ -18,6 +18,8 @@ "@types/react-syntax-highlighter": "^10.2.1", "@types/remarkable": "^1.7.4", "@types/request": "^2.48.7", + "@v9v/ts-react-telegram-login": "^1.1.1", + "add": "^2.0.6", "axios": "^0.21.1", "bootstrap": "^4.3.1", "classnames": "^2.3.1", @@ -29,6 +31,7 @@ "jwt-decode": "^3.1.2", "lowdb": "^1.0.0", "material-ui-image": "^3.3.2", + "or": "^0.2.0", "portable-fetch": "^3.0.0", "prop-types": "^15.7.2", "react": "^16.12.0", @@ -38,7 +41,10 @@ "react-query": "^3.21.1", "react-router-dom": "^5.2.1", "react-scripts": "^4.0.3", - "react-social-login-buttons": "^3.6.0" + "react-social-login-buttons": "^3.6.0", + "react-telegram-auth": "^1.0.3", + "react-telegram-login": "^1.1.2", + "yarn": "^1.22.17" }, "scripts": { "start": "react-scripts start", diff --git a/hwproj.front/src/components/Profile.tsx b/hwproj.front/src/components/Profile.tsx index 73614e34b..df7edbb83 100644 --- a/hwproj.front/src/components/Profile.tsx +++ b/hwproj.front/src/components/Profile.tsx @@ -17,8 +17,7 @@ import {makeStyles} from "@material-ui/styles"; import Image from 'material-ui-image' import telegramLogo from './tlgm.png' import "./Styles/telegram.css"; -import {GoogleLoginButton} from "react-social-login-buttons"; -import {TelegramLoginButton} from "react-social-login-buttons"; +import TelegramLoginButton, { TelegramUser } from '@v9v/ts-react-telegram-login'; interface IProfileState { isLoaded: boolean; @@ -114,6 +113,13 @@ const Profile: FC> = (props) => { ) } + const handleTelegramResponse = (user: TelegramUser) => { + console.log(user); + debugger + }; + + + const classes = useStyles() if (!ApiSingleton.authService.isLoggedIn()) { @@ -134,13 +140,19 @@ const Profile: FC> = (props) => { {fullName} - alert("Hello")}> - - Попробуйте бота - - +
+ Shalom! +
+ +
{accountState.email} @@ -192,4 +204,4 @@ const Profile: FC> = (props) => { ) } -export default Profile +export default Profile; \ No newline at end of file From 908eca0eb07c2fdd1975ff39dee5c4b2b153eb16 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Tue, 30 Nov 2021 23:35:58 +0300 Subject: [PATCH 08/19] add commands and event --- .../ConfigurationExtensions.cs | 3 +- .../ConfirmTelegramBotEventHandler.cs | 13 +- .../Startup.cs | 5 +- .../appsettings.json | 2 +- .../Commands/CheckCodeCommand.cs | 32 ++++ .../Commands/CommandNames.cs | 5 +- .../Commands/ErrorCommand.cs | 29 ++++ .../Commands/GetAllCourses.cs | 6 +- .../Commands/GetCourses.cs | 2 +- .../Commands/GetHomeworks.cs | 2 +- .../Commands/GetSolutionInfo.cs | 2 +- .../Commands/GetSolutionsFromTask.cs | 2 +- .../Commands/GetStatistics.cs | 2 +- .../Commands/GetTaskInfo.cs | 2 +- .../Commands/GetTasks.cs | 2 +- .../Commands/SendSolution.cs | 2 +- .../Commands/StartCommand.cs | 8 +- .../Commands/WaitCodeCommand.cs | 34 ++++ .../Events/ConfirmTelegramBotEvent.cs | 7 +- .../Models/TelegramBotContext.cs | 6 +- .../Models/TelegramUserModel.cs | 12 +- .../Models/TelegramUserResponse.cs | 11 ++ .../Repositories/ITelegramBotRepository.cs | 10 ++ .../Repositories/TelegramBotRepository.cs | 13 ++ .../Service/CommandService.cs | 46 ++++-- .../Service/IUserService.cs | 13 +- .../Service/UserService.cs | 150 +++++++++--------- .../HwProj.TelegramBotService.API/Startup.cs | 3 + .../appsettings.json | 2 +- .../ITelegramBotServiceClient.cs | 1 + .../TelegramBotServiceClient.cs | 1 + hwproj.front/src/components/Profile.tsx | 34 +--- hwproj.front/src/components/tlgm.png | Bin 0 -> 1248 bytes 33 files changed, 304 insertions(+), 158 deletions(-) create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserResponse.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs create mode 100644 hwproj.front/src/components/tlgm.png diff --git a/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs b/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs index 82d58102d..5ae6cd0e0 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs @@ -9,7 +9,8 @@ public static class ConfigurationExtensions public static IServiceCollection AddCoursesServiceClient(this IServiceCollection services) { services.AddScoped(); - services.TryAddSingleton(); + services.AddHttpContextAccessor(); + /*services.TryAddSingleton();*/ return services; } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs index de57e6f4d..2b4dc22ff 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs @@ -19,15 +19,16 @@ public ConfirmTelegramBotEventHandler(INotificationsRepository notificationRepos public async Task HandleAsync(ConfirmTelegramBotEvent @event) { - /*await _notificationRepository.AddAsync(new Notification + var notification = new Notification { - Sender = "TelegramBot", - Body = "Ваш профиль был успешно отредактирован.", - Category = "AuthService", + Sender = "TelegramBotService", + Body = $"Ваш код для телеграмма - {@event.TelegramUserModel.Code}.", + Category = "TelegramBotService", Date = DateTime.UtcNow, HasSeen = false, - Owner = @event.UserId - });*/ + Owner = @event.TelegramUserModel.AccountId + }; + await _notificationRepository.AddAsync(notification); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs index 72885ddd6..04ae3d4ab 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs @@ -22,6 +22,7 @@ using HwProj.CoursesService.Client; using HwProj.SolutionsService.API.Events; using HwProj.SolutionsService.Client; +using HwProj.TelegramBotService.API.Events; using HwProj.TelegramBotService.Client; using UpdateTaskMaxRatingEvent = HwProj.CoursesService.API.Events.UpdateTaskMaxRatingEvent; @@ -43,7 +44,7 @@ public void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); services.AddEventBus(Configuration); - /*services.AddTransient, ConfirmTelegramBotEventHandler>();*/ + services.AddTransient, ConfirmTelegramBotEventHandler>(); services.AddTransient, RegisterEventHandler>(); services.AddTransient, RateEventHandler>(); services.AddTransient, EditProfileEventHandler>(); @@ -67,7 +68,7 @@ public void ConfigureServices(IServiceCollection services) public void Configure(IApplicationBuilder app, IHostingEnvironment env, IEventBus eventBus) { - /*eventBus.Subscribe();*/ + eventBus.Subscribe(); eventBus.Subscribe(); eventBus.Subscribe(); eventBus.Subscribe(); diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json index c1d3b63a2..46a4b5921 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json @@ -26,6 +26,6 @@ }, "Telegram": { "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://aa14-92-42-26-35.ngrok.io/" + "Url" : "https://9afa-92-42-26-35.ngrok.io/" } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs new file mode 100644 index 000000000..17a79b164 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs @@ -0,0 +1,32 @@ +using System.Threading.Tasks; +using HwProj.TelegramBotService.API.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; +using Telegram.Bot.Types.ReplyMarkups; + +namespace HwProj.TelegramBotService.API.Commands +{ + public class CheckCodeCommand : Commands + { + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + + public CheckCodeCommand(TelegramBot telegramBot, IUserService userService) + { + _botClient = telegramBot.GetBot().Result; + _userService = userService; + } + + public override string Name => CommandNames.CheckCodeCommand; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.AddFinishUser(update); + + var inlineKeyboard = new InlineKeyboardMarkup(GetButton("Мои курсы", "/courses")); + + await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать в Hw-ProjBot!", replyMarkup: inlineKeyboard); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs index 95cfc1e6c..df694b467 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs @@ -11,6 +11,9 @@ public static class CommandNames public const string GetSolutionsFromTask = "/solutions"; // /solutions {taskId} public const string GetSolutionInfo = "/solutioninfo"; // /solutioninfo {solutionId} public const string GetStatistics = "/statistics"; // /statistics {courseId} - public const string SendSolution = "/send_solution"; + public const string SendSolution = "/send_solution"; + public const string WaitCodeCommand = "wait_code"; + public const string CheckCodeCommand = "check_code"; + public const string ErrorCommand = "error_response"; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs new file mode 100644 index 000000000..02cb2e6e6 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs @@ -0,0 +1,29 @@ +using System.Threading.Tasks; +using HwProj.TelegramBotService.API.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + +namespace HwProj.TelegramBotService.API.Commands +{ + public class ErrorCommand : Commands + { + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + + public ErrorCommand(TelegramBot telegramBot, IUserService userService) + { + _botClient = telegramBot.GetBot().Result; + _userService = userService; + } + + public override string Name => CommandNames.ErrorCommand; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.GetUserByUpdate(update); + + await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!\n Введите ваш e-mail на Hw-Proj2.0.1", ParseMode.Markdown); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs index a6fca71b6..86227ca2b 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs @@ -25,11 +25,9 @@ public GetAllCourses(TelegramBot telegramBot, IUserService userService, ICourses public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetOrCreateChatId(update); + var user = await _userService.GetUserByUpdate(update); - var courses = _coursesServiceClient.GetAllCourses().Result; - - await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!", ParseMode.Markdown/*, replyMarkup:inlineKeyboard*/); + await _botClient.SendTextMessageAsync(user.ChatId, "Повторите запрос снова!", ParseMode.Markdown/*, replyMarkup:inlineKeyboard*/); } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs index 6b4978440..ba49ab0f0 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs @@ -26,7 +26,7 @@ public GetCourses(TelegramBot telegramBot, ICoursesServiceClient coursesServiceC public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetOrCreateChatId(update); + var user = await _userService.GetUserByUpdate(update); var courses = _coursesServiceClient.GetAllUserCourses(user.AccountId).Result; await _botClient.SendTextMessageAsync(user.ChatId, "*Выберите курс для просмотра домашних работ или статистики:*", ParseMode.Markdown); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs index 095b4306d..5a85fd212 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs @@ -27,7 +27,7 @@ public GetHomeworks(TelegramBot telegramBot, ICoursesServiceClient coursesServic public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetOrCreateChatId(update); + var user = await _userService.GetUserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var homeworks = _coursesServiceClient.GetAllHomeworkByCourse(Int32.Parse(text[1])).Result; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs index 40d33874a..e6d4a87a3 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs @@ -31,7 +31,7 @@ public GetSolutionInfo(TelegramBot telegramBot, ISolutionsServiceClient solution public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetOrCreateChatId(update); + var user = await _userService.GetUserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var solution =_solutionsServiceClient.GetSolutionById(Int32.Parse(text[1])).Result; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs index bbf98cb00..4717814bd 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs @@ -30,7 +30,7 @@ public GetSolutionsFromTask(TelegramBot telegramBot, IUserService userService, I public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetOrCreateChatId(update); + var user = await _userService.GetUserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var solutions = _solutionsServiceClient.GetUserSolution(Int32.Parse(text[1]), user.AccountId).Result; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs index 6aa3d08fe..b2aa41f19 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs @@ -30,7 +30,7 @@ public GetStatistics(TelegramBot telegramBot, IUserService userService, ICourses public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetOrCreateChatId(update); + var user = await _userService.GetUserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var course = _coursesServiceClient.GetCourseById(Int64.Parse(text[1]), user.AccountId).Result; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs index d6caa3906..44f220c49 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs @@ -29,7 +29,7 @@ public GetTaskInfo(TelegramBot telegramBot, ICoursesServiceClient coursesService public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetOrCreateChatId(update); + var user = await _userService.GetUserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var task = _coursesServiceClient.GetTask(Int64.Parse(text[1])).Result; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs index 24e35775e..1ea88a4fa 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs @@ -28,7 +28,7 @@ public GetTasks(TelegramBot telegramBot, ICoursesServiceClient coursesServiceCli public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetOrCreateChatId(update); + var user = await _userService.GetUserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var hw = _coursesServiceClient.GetHomework(Int32.Parse(text[1])).Result; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs index b86c9b005..274ad6f98 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs @@ -25,7 +25,7 @@ public SendSolution(TelegramBot telegramBot, IUserService userService, public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetOrCreateChatId(update); + var user = await _userService.GetUserByUpdate(update); /*await _solutionsServiceClient.PostSolution();*/ diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs index 73f486c47..f103dd1b1 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs @@ -22,11 +22,11 @@ public StartCommand(TelegramBot telegramBot, IUserService userService) public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetOrCreateChatId(update); + await _userService.DeleteUser(update); + + var user = await _userService.CreateUser(update); - var inlineKeyboard = new InlineKeyboardMarkup(GetButton("Мои курсы", "/courses")); - - await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!", ParseMode.Markdown, replyMarkup:inlineKeyboard); + await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!\n Введите ваш e-mail на Hw-Proj2.0.1", ParseMode.Markdown); } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs new file mode 100644 index 000000000..75a96b635 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs @@ -0,0 +1,34 @@ +using System.Threading.Tasks; +using HwProj.TelegramBotService.API.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + +namespace HwProj.TelegramBotService.API.Commands +{ + public class WaitCodeCommand : Commands + { + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + + public WaitCodeCommand(TelegramBot telegramBot, IUserService userService) + { + _botClient = telegramBot.GetBot().Result; + _userService = userService; + } + + public override string Name => CommandNames.WaitCodeCommand; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.AddEmailToUser(update); + + if (user == null) + { + await _botClient.SendTextMessageAsync(update.Message.Chat.Id, "E-mail не зарегистрирован на Hw-Proj.\nВведите /start", ParseMode.Markdown); + } + + await _botClient.SendTextMessageAsync(user.ChatId, "Ваш код отправлен.\nВведите его:", ParseMode.Markdown); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs index 0585d50b1..876834388 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs @@ -6,7 +6,10 @@ namespace HwProj.TelegramBotService.API.Events public class ConfirmTelegramBotEvent : Event { public TelegramUserModel TelegramUserModel { get; set; } - - public string Code { get; set; } + + public ConfirmTelegramBotEvent(TelegramUserModel userModel) + { + TelegramUserModel = userModel; + } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramBotContext.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramBotContext.cs index c147fd5c3..eb9d74d21 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramBotContext.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramBotContext.cs @@ -4,10 +4,12 @@ namespace HwProj.TelegramBotService.API.Models { public class TelegramBotContext : DbContext { - public TelegramBotContext(DbContextOptions options) : base(options) + public DbSet TelegramUser { get; set; } + + public TelegramBotContext(DbContextOptions options) + : base(options) { } - public DbSet TelegramUser { get; set; } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs index 51f1a958d..c824f5bd6 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs @@ -1,15 +1,21 @@ -namespace HwProj.TelegramBotService.API.Models +using HwProj.Repositories; + +namespace HwProj.TelegramBotService.API.Models { - public class TelegramUserModel + public class TelegramUserModel /*: IEntity*/ { public long Id { get; set; } public long ChatId { get; set; } - + public string AccountId { get; set; } public bool IsLecture { get; set; } public bool IsRegistered { get; set; } + + public string Code { get; set; } + + public string Operation { get; set; } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserResponse.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserResponse.cs new file mode 100644 index 000000000..a8c1ef4fc --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserResponse.cs @@ -0,0 +1,11 @@ +namespace HwProj.TelegramBotService.API.Models +{ + public class TelegramUserResponse + { + public long AuthDate { get; set; } + public string FirstName { get; set; } + public string Hash { get; set; } + public long ChatId { get; set; } + public string LastName { get; set; } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs new file mode 100644 index 000000000..bfe4da7b1 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs @@ -0,0 +1,10 @@ +using HwProj.Repositories; +using HwProj.TelegramBotService.API.Models; + +namespace HwProj.TelegramBotService.API.Repositories +{ + /*public interface ITelegramBotRepository : ICrudRepository + { + + }*/ +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs new file mode 100644 index 000000000..451cc06db --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs @@ -0,0 +1,13 @@ +using HwProj.Repositories; +using HwProj.TelegramBotService.API.Models; + +namespace HwProj.TelegramBotService.API.Repositories +{ + /*public class TelegramBotRepository : CrudRepository, ITelegramBotRepository + { + public TelegramBotRepository(TelegramBotContext context) + : base(context) + { + } + }*/ +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs index 2a3401116..f2d8a8d13 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs @@ -3,6 +3,8 @@ using System.Linq; using System.Threading.Tasks; using HwProj.TelegramBotService.API.Commands; +using HwProj.TelegramBotService.API.Models; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; @@ -11,11 +13,13 @@ namespace HwProj.TelegramBotService.API.Service { public class CommandService : ICommandService { + private readonly TelegramBotContext _context; private readonly List _commands; private Commands.Commands _lastCommand; - public CommandService(IServiceProvider serviceProvider) + public CommandService(IServiceProvider serviceProvider, TelegramBotContext context) { + _context = context; _commands = serviceProvider.GetServices().ToList(); } @@ -23,28 +27,39 @@ public async Task Execute(Update update) { if(update?.Message?.Chat == null && update?.CallbackQuery == null) return; - + if (update.Type == UpdateType.Message) { var message = update.Message?.Text; - var text = message.Split(' '); - - if (text[0] == "/start" && text.Length > 1) - { - await ExecuteCommand(CommandNames.StartCommand, update); - return; - } - switch (text[0]) + switch (message) { case "/start": await ExecuteCommand(CommandNames.StartCommand, update); - break; + return; case "/courses": await ExecuteCommand(CommandNames.GetCourses, update); - break; - /*case "/homeworks": - await ExecuteCommand(CommandNames.GetHomeworks, update); - break;*/ + return; + } + var user = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result; + if (user.Operation == "wait_code" || user.Operation == "check_code") + { + switch (user.Operation) + { + case "wait_code": + await ExecuteCommand(CommandNames.WaitCodeCommand, update); + break; + case "check_code": + await ExecuteCommand(CommandNames.CheckCodeCommand, update); + break; + } + } + if (user == null) + { + await ExecuteCommand(CommandNames.StartCommand, update); + } + if (user.Operation == null) + { + } } else @@ -74,6 +89,7 @@ public async Task Execute(Update update) break; } } + } private async Task ExecuteCommand(string commandName, Update update) diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs index 4d86738c6..41fbe8cb5 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs @@ -6,13 +6,18 @@ namespace HwProj.TelegramBotService.API.Service { public interface IUserService { - Task GetOrCreateChatId(Update update); + Task CreateUser(Update update); - /*Task CreateChatId(Update update); - */ + Task AddEmailToUser(Update update); + + Task AddFinishUser(Update update); + + Task GetUserByUpdate(Update update); Task GetTelegramUserModelByStudentId(string studentId); - Task GetTelegramUserModelByChatId(long ChatId); + Task DeleteUser(Update update); + + Task GetTelegramUserModelByChatId(long chatId); } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs index 213204bb3..32158ac44 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs @@ -1,6 +1,10 @@ -using System.Threading.Tasks; +using System; +using System.Linq; +using System.Threading.Tasks; using HwProj.AuthService.Client; +using HwProj.EventBus.Client.Interfaces; using HwProj.Models.AuthService.DTO; +using HwProj.TelegramBotService.API.Events; using HwProj.TelegramBotService.API.Models; using Microsoft.EntityFrameworkCore; using Telegram.Bot.Types; @@ -11,59 +15,34 @@ public class UserService : IUserService { private readonly TelegramBotContext _context; private readonly IAuthServiceClient _authClient; + private readonly IEventBus _eventBus; - public UserService(TelegramBotContext context, IAuthServiceClient authClient) + public UserService(TelegramBotContext context, IAuthServiceClient authClient, IEventBus eventBus) { _context = context; _authClient = authClient; + _eventBus = eventBus; } - - public async Task GetOrCreateChatId(Update update) + + public async Task CreateUser(Update update) { - string studentId; - AccountDataDto studentModel = null; - TelegramUserModel newUser; - if (update.CallbackQuery == null) - { - var message = update.Message?.Text; - var text = message.Split(' '); - if (text[0] == "/start" && text.Length > 1) - { - studentId = _authClient.FindByEmailAsync(text[1]).Result; - studentModel = _authClient.GetAccountData(studentId).Result; - } - else - { - return await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id); - } - - newUser = new TelegramUserModel - { - Id = update.Message.Chat.Id, - ChatId = update.Message.Chat.Id, - AccountId = studentId, - IsLecture = studentModel.Role == "Lecture", - IsRegistered = true - }; - } - else + /*var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id); + _context.Remove(user); + await _context.SaveChangesAsync();*/ + var random = new Random(); + var code = random.Next(10) * 1000 + random.Next(10) * 100 + random.Next(10) * 10 + random.Next(10); + var newUser = new TelegramUserModel { - var message = update.CallbackQuery.Data; - var text = message.Split(' '); - studentId = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id).Result.AccountId; - studentModel = _authClient.GetAccountData(studentId).Result; - - newUser = new TelegramUserModel - { - Id = update.CallbackQuery.Message.Chat.Id, - ChatId = update.CallbackQuery.Message.Chat.Id, - AccountId = studentId, - IsLecture = studentModel.Role == "Lecture", - IsRegistered = true - }; - } + Id = update.Message.Chat.Id, + ChatId = update.Message.Chat.Id, + AccountId = null, + IsLecture = false, + IsRegistered = false, + Code = code.ToString(), + Operation = "wait_code" + }; var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == newUser.ChatId); - + if (user != null) { return user; @@ -74,42 +53,61 @@ public async Task GetOrCreateChatId(Update update) return result.Entity; } - - /*public async Task CreateChatId(Update update) + + public async Task AddEmailToUser(Update update) { - string studentId; - AccountDataDto studentModel = null; - TelegramUserModel newUser; - if (update.CallbackQuery == null) - { - newUser = new TelegramUserModel - { - Id = update.Message.Chat.Id, - ChatId = update.Message.Chat.Id, - AccountId = studentId, - IsLecture = studentModel.Role == "Lecture", - IsRegistered = true - }; + var message = update.Message?.Text; + var user = await _context.TelegramUser.FindAsync(update.Message.Chat.Id); + if (user.Operation != "wait_code" || user == null) + { + _context.Remove(user); + await _context.SaveChangesAsync(); + return null; } - - var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == newUser.ChatId); - - if (user != null) - { - return user; + var accountId = _authClient.FindByEmailAsync(message).Result; + var studentModel = _authClient.GetAccountData(accountId).Result; + user.Operation = "check_code"; + user.AccountId = accountId; + user.IsLecture = studentModel.Role == "Lecture"; + await _context.SaveChangesAsync(); + _eventBus.Publish(new ConfirmTelegramBotEvent(user)); + return user; + } + + public async Task AddFinishUser(Update update) + { + var message = update.Message?.Text; + var user = await _context.TelegramUser.FindAsync(update.Message.Chat.Id); + if (user.Operation != "check_code" || user.Code != message || user == null) + { + _context.Remove(user); + await _context.SaveChangesAsync(); + return null; } - - var result = await _context.TelegramUser.AddAsync(newUser); + user.Operation = "finish"; + user.IsRegistered = true; await _context.SaveChangesAsync(); - - return result.Entity; - }*/ + return user; + } + + public async Task GetUserByUpdate(Update update) + => await _context.TelegramUser.FindAsync(update.CallbackQuery == null ? update.Message.Chat.Id : update.CallbackQuery.Message.Chat.Id); - public async Task GetTelegramUserModelByStudentId(string studentId) - => _context.TelegramUser.FirstOrDefaultAsync(x => x.AccountId == studentId).Result; + => _context.TelegramUser.First(x => x.AccountId == studentId); + + public async Task DeleteUser(Update update) + { + var user1 = await _context.TelegramUser.FindAsync(update.Message.Chat.Id); + if (user1 != null) + { + var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id); + _context.Remove(user); + await _context.SaveChangesAsync(); + } + } - public async Task GetTelegramUserModelByChatId(long ChatId) - => _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == ChatId).Result; + public async Task GetTelegramUserModelByChatId(long chatId) + => _context.TelegramUser.FindAsync(chatId).Result; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs index 096aca69d..e3a04cbc1 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs @@ -38,6 +38,9 @@ public void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); /*services.AddScoped();*/ services.AddHttpClient(); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json index 42173e101..6c9b5a59a 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json @@ -24,5 +24,5 @@ "TelegramBot" : "http://localhost:5009" }, "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://aa14-92-42-26-35.ngrok.io/" + "Url" : "https://9afa-92-42-26-35.ngrok.io/" } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs index 0372470d6..a8895c19d 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs @@ -1,4 +1,5 @@ using System.Threading.Tasks; +using HwProj.Models.Result; using HwProj.TelegramBotService.API.Models; namespace HwProj.TelegramBotService.Client diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs index ad324c862..7f1f6f733 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs @@ -2,6 +2,7 @@ using System.Net.Http; using System.Threading.Tasks; using HwProj.HttpUtils; +using HwProj.Models.Result; using HwProj.TelegramBotService.API.Models; using Microsoft.Extensions.Configuration; diff --git a/hwproj.front/src/components/Profile.tsx b/hwproj.front/src/components/Profile.tsx index df7edbb83..e79400d3f 100644 --- a/hwproj.front/src/components/Profile.tsx +++ b/hwproj.front/src/components/Profile.tsx @@ -17,7 +17,6 @@ import {makeStyles} from "@material-ui/styles"; import Image from 'material-ui-image' import telegramLogo from './tlgm.png' import "./Styles/telegram.css"; -import TelegramLoginButton, { TelegramUser } from '@v9v/ts-react-telegram-login'; interface IProfileState { isLoaded: boolean; @@ -113,13 +112,6 @@ const Profile: FC> = (props) => { ) } - const handleTelegramResponse = (user: TelegramUser) => { - console.log(user); - debugger - }; - - - const classes = useStyles() if (!ApiSingleton.authService.isLoggedIn()) { @@ -140,30 +132,16 @@ const Profile: FC> = (props) => { {fullName} -
- Shalom! -
- -
+ + + {accountState.email} - - - - {!props.match.params.id &&
diff --git a/hwproj.front/src/components/tlgm.png b/hwproj.front/src/components/tlgm.png new file mode 100644 index 0000000000000000000000000000000000000000..c73e64b2ed0ee6f2a149647c99a029cfcc332f5f GIT binary patch literal 1248 zcmV<61Rwi}P)r)0J+fs zKx`8sP#8rB#5Mx}g|bcix9wZ$iKVKI`Zv{q^v1}>Vo(@a3^Lwgf19V$Be_u(gV<(< zz|v-hKyH*FklD--SW;EyUu#3@os{WA{{3hny;Bk)^$%(&2E>E~-X8|BS>+Tl^X(LmIXx-F6T8XtGdaY})l~zW&6-#xj0X%M9yCi)0 z0X%Mx(Nya$JnoFqP#1o%lXg<1lnTFt$H-}@njY{h(w)-*@2*RTkkf%G{9u1d;FfgP zF+?bY1vfpeAwt7W7h7;fw_AUaEbh1{52oHU|!p=otNUZDl5J?IFUg6nAz-4Xv&M!-`HiZCRaC=NA5?K*M17cD^C614{fUO~7%4@J zxS&3{goymSzhXTu$ldUYZ4^s(i{(gqJYqKjAGt<>tw3>PO@@fysB5T3QSfITUf4## zy1b%7G~%~=D=I{pV#E4KJ#D~(HDTlSFyKvCb4wQ91Zk)hh28|h0@8$)bBIda39ri8 z<5+q8r*ZW-&AtAQp^E?vjVuNW8;e0?RK;LnGXM}8WfUYfZ3u)$ z0|1H506=6EA+WHC5EvR2F}O15LcKNBJa8fOj;NW>rO}_U{NJ&m)dV3)MhOCmxj(%aVMQz2Hr$7X=UOy zJ@9%g|78q!eYwFXaQF8?pUm&R4P$&c4|->K^Kkyj!+je39R33S3D{Zj Date: Sun, 19 Dec 2021 02:36:07 +0300 Subject: [PATCH 09/19] wip --- .../Configuration/StartupExtensions.cs | 3 ++- .../HwProj.CoursesService.API/Startup.cs | 2 +- .../ConfigurationExtensions.cs | 2 +- .../ConfirmTelegramBotEventHandler.cs | 2 +- .../EventHandlers/EditProfileEventHandler.cs | 14 ++++++++++- .../InviteLecturerEventHandler.cs | 14 ++++++++++- .../LecturerAcceptToCourseEventHandler.cs | 10 +++++--- .../LecturerRejectToCourseEventHandler.cs | 10 +++++--- .../EventHandlers/NewCourseMateHandler.cs | 4 ++++ .../EventHandlers/NewHomeworkEventHandler.cs | 13 ++++++++++- .../EventHandlers/RateEventHandler.cs | 12 +++++++--- .../EventHandlers/RegisterEventHandler.cs | 1 + .../StudentPassTaskEventHandler.cs | 10 ++++++-- .../UpdateHomeworkEventHandler.cs | 9 +++++++- .../UpdateTaskMaxRatingEventHandler.cs | 14 ++++++++++- .../HwProj.NotificationsService.API.csproj | 1 + .../Services/INotificationsService.cs | 2 +- .../Services/NotificationsService.cs | 23 +++++++++++++++++++ .../appsettings.json | 2 +- .../Events/RateEvent.cs | 6 ++--- .../Commands/Commands.cs | 2 +- .../Commands/ErrorCommand.cs | 2 +- .../Commands/GetAllCourses.cs | 2 +- .../Commands/GetCourses.cs | 4 ++-- .../Commands/GetHomeworks.cs | 4 ++-- .../Commands/GetSolutionInfo.cs | 4 ++-- .../Commands/GetSolutionsFromTask.cs | 4 ++-- .../Commands/GetStatistics.cs | 4 ++-- .../Commands/GetTaskInfo.cs | 4 ++-- .../Commands/GetTasks.cs | 4 ++-- .../Commands/SendSolution.cs | 5 ++-- .../Commands/WaitCodeCommand.cs | 2 +- .../Controllers/TelegramBotController.cs | 2 +- .../Events/ConfirmTelegramBotEvent.cs | 2 +- .../Models/TelegramUserModel.cs | 2 +- .../Models/TelegramUserResponse.cs | 11 --------- .../Repositories/ITelegramBotRepository.cs | 10 -------- .../Repositories/TelegramBotRepository.cs | 13 ----------- .../Service/CommandService.cs | 17 +++++--------- .../Service/IUserService.cs | 6 ++--- .../Service/UserService.cs | 19 ++++++++------- .../appsettings.json | 2 +- 42 files changed, 171 insertions(+), 108 deletions(-) delete mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserResponse.cs delete mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs delete mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs diff --git a/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs b/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs index 9dea3441c..a172a6b73 100644 --- a/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs +++ b/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs @@ -77,7 +77,8 @@ public static IServiceCollection ConfigureHwProjServices(this IServiceCollection } services.AddTransient(); - + services.AddHttpContextAccessor(); + return services; } diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Startup.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Startup.cs index 400395eb7..09de9ccb9 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Startup.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Startup.cs @@ -42,7 +42,7 @@ public void ConfigureServices(IServiceCollection services) services.AddEventBus(Configuration); - services.AddHttpContextAccessor(); + /*services.AddHttpContextAccessor();*/ services.AddHttpClient(); services.AddAuthServiceClient(); diff --git a/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs b/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs index 5ae6cd0e0..5c896b3cf 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs @@ -9,7 +9,7 @@ public static class ConfigurationExtensions public static IServiceCollection AddCoursesServiceClient(this IServiceCollection services) { services.AddScoped(); - services.AddHttpContextAccessor(); + /*services.AddHttpContextAccessor();*/ /*services.TryAddSingleton();*/ return services; } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs index 2b4dc22ff..622046862 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs @@ -3,7 +3,6 @@ using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; -using HwProj.TelegramBotService.API; using HwProj.TelegramBotService.API.Events; namespace HwProj.NotificationsService.API.EventHandlers @@ -12,6 +11,7 @@ public class ConfirmTelegramBotEventHandler: IEventHandler { private readonly INotificationsRepository _notificationRepository; private readonly INotificationsService _notificationsService; + private readonly IAuthServiceClient _authServiceClient; + private readonly IMapper _mapper; + - public EditProfileEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService) + public EditProfileEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService, IMapper mapper, IAuthServiceClient authServiceClient) { _notificationRepository = notificationRepository; _notificationsService = notificationsService; + _mapper = mapper; + _authServiceClient = authServiceClient; } public async Task HandleAsync(EditProfileEvent @event) @@ -31,6 +39,10 @@ public async Task HandleAsync(EditProfileEvent @event) Owner = @event.UserId }; await _notificationRepository.AddAsync(notification); + var studentAccount = await _authServiceClient.GetAccountData(notification.Owner); + var studentModel = _mapper.Map(studentAccount); + + await _notificationsService.SendEmailAsync(notification, studentModel.Email, "Редактирование профиля"); await _notificationsService.SendTelegramMessageAsync(notification, null); } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs index 5fec1f74c..5ffbc28df 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs @@ -1,7 +1,10 @@ using System; using System.Threading.Tasks; +using AutoMapper; using HwProj.AuthService.API.Events; +using HwProj.AuthService.Client; using HwProj.EventBus.Client.Interfaces; +using HwProj.Models.AuthService.DTO; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; using HwProj.NotificationsService.API.Services; @@ -12,11 +15,15 @@ public class InviteLecturerEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; private readonly INotificationsService _notificationsService; + private readonly IAuthServiceClient _authServiceClient; + private readonly IMapper _mapper; - public InviteLecturerEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService) + public InviteLecturerEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService, IAuthServiceClient authServiceClient, IMapper mapper) { _notificationRepository = notificationRepository; _notificationsService = notificationsService; + _authServiceClient = authServiceClient; + _mapper = mapper; } public async Task HandleAsync(InviteLecturerEvent @event) @@ -31,6 +38,11 @@ public async Task HandleAsync(InviteLecturerEvent @event) Owner = @event.UserId }; await _notificationRepository.AddAsync(notification); + + var studentAccount = await _authServiceClient.GetAccountData(notification.Owner); + var studentModel = _mapper.Map(studentAccount); + + await _notificationsService.SendEmailAsync(notification, studentModel.Email, "HwProj"); await _notificationsService.SendTelegramMessageAsync(notification, null); } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs index 789dc89a1..797264275 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs @@ -12,14 +12,15 @@ namespace HwProj.NotificationsService.API.EventHandlers public class LecturerAcceptToCourseEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; - private readonly IAuthServiceClient _authClient; private readonly INotificationsService _notificationsService; + private readonly IAuthServiceClient _authServiceClient; - public LecturerAcceptToCourseEventHandler(INotificationsRepository notificationRepository, IAuthServiceClient authClient, INotificationsService notificationsService) + + public LecturerAcceptToCourseEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService, IAuthServiceClient authServiceClient) { _notificationRepository = notificationRepository; - _authClient = authClient; _notificationsService = notificationsService; + _authServiceClient = authServiceClient; } public async Task HandleAsync(LecturerAcceptToCourseEvent @event) @@ -34,6 +35,9 @@ public async Task HandleAsync(LecturerAcceptToCourseEvent @event) Owner = @event.StudentId }; await _notificationRepository.AddAsync(notification); + var student = await _authServiceClient.GetAccountData(notification.Owner); + await _notificationsService.SendEmailAsync(notification, student.Email, "HwProj"); + notification.Body = $"Вас приняли на курс {@event.CourseName}."; await _notificationsService.SendTelegramMessageAsync(notification, null); } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs index 41947c706..b6ee37f02 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs @@ -12,14 +12,15 @@ namespace HwProj.NotificationsService.API.EventHandlers public class LecturerRejectToCourseEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; - private readonly IAuthServiceClient _authClient; private readonly INotificationsService _notificationsService; + private readonly IAuthServiceClient _authServiceClient; - public LecturerRejectToCourseEventHandler(INotificationsRepository notificationRepository, IAuthServiceClient authClient, INotificationsService notificationsService) + + public LecturerRejectToCourseEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService, IAuthServiceClient authServiceClient) { _notificationRepository = notificationRepository; - _authClient = authClient; _notificationsService = notificationsService; + _authServiceClient = authServiceClient; } public async Task HandleAsync(LecturerRejectToCourseEvent @event) @@ -34,6 +35,9 @@ public async Task HandleAsync(LecturerRejectToCourseEvent @event) Owner = @event.StudentId }; await _notificationRepository.AddAsync(notification); + var student = await _authServiceClient.GetAccountData(notification.Owner); + await _notificationsService.SendEmailAsync(notification, student.Email, "HwProj"); + notification.Body = $"Вас не приняли на курс {@event.CourseName}."; await _notificationsService.SendTelegramMessageAsync(notification, null); } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs index 75cb02b2b..c927c04b6 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs @@ -15,6 +15,7 @@ public class NewCourseMateHandler : IEventHandler private readonly IAuthServiceClient _authClient; private readonly INotificationsService _notificationsService; + public NewCourseMateHandler(INotificationsRepository notificationRepository, IAuthServiceClient authClient, INotificationsService notificationsService) { _notificationRepository = notificationRepository; @@ -40,6 +41,9 @@ public async Task HandleAsync(NewCourseMateEvent @event) Owner = m }; await _notificationRepository.AddAsync(notification); + var mentor = await _authClient.GetAccountData(notification.Owner); + await _notificationsService.SendEmailAsync(notification, mentor.Email, "HwProj"); + notification.Body = $"Пользователь {user.Name} {user.Surname} подал заявку на вступление в курс {@event.CourseName}."; await _notificationsService.SendTelegramMessageAsync(notification, null); } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs index cab315803..acadd851d 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs @@ -1,9 +1,12 @@ using System; using System.Threading.Tasks; +using AutoMapper; +using HwProj.AuthService.Client; using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; using HwProj.CoursesService.API.Events; +using HwProj.Models.AuthService.DTO; using HwProj.NotificationsService.API.Services; using Telegram.Bot.Types.ReplyMarkups; @@ -13,18 +16,25 @@ public class NewHomeworkEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; private readonly INotificationsService _notificationsService; + private readonly IAuthServiceClient _authServiceClient; + private readonly IMapper _mapper; + public NewHomeworkEventHandler(INotificationsRepository notificationRepository, - INotificationsService notificationsService) + INotificationsService notificationsService, IAuthServiceClient authServiceClient, IMapper mapper) { _notificationRepository = notificationRepository; _notificationsService = notificationsService; + _authServiceClient = authServiceClient; + _mapper = mapper; } public async Task HandleAsync(NewHomeworkEvent @event) { foreach (var student in @event.Course.CourseMates) { + var studentAccount = await _authServiceClient.GetAccountData(student.StudentId); + var studentModel = _mapper.Map(studentAccount); var notification = new Notification { Sender = "CourseService", @@ -36,6 +46,7 @@ public async Task HandleAsync(NewHomeworkEvent @event) Owner = student.StudentId }; await _notificationRepository.AddAsync(notification); + await _notificationsService.SendEmailAsync(notification, studentModel.Email, "Домашняя работа"); notification.Body = $"В курсе {@event.Course.Name} опубликована новая домашка {@event.Homework}."; // var inlineKeyboard = new InlineKeyboardMarkup(new InlineKeyboardButton { diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs index c02fc93be..c45af840a 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs @@ -1,5 +1,6 @@ using System; using System.Threading.Tasks; +using HwProj.AuthService.Client; using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; @@ -9,16 +10,18 @@ namespace HwProj.NotificationsService.API.EventHandlers { - // ReSharper disable once UnusedType.Global public class RateEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; private readonly INotificationsService _notificationsService; + private readonly IAuthServiceClient _authServiceClient; - public RateEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService) + + public RateEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService, IAuthServiceClient authServiceClient) { _notificationRepository = notificationRepository; _notificationsService = notificationsService; + _authServiceClient = authServiceClient; } public async Task HandleAsync(RateEvent @event) @@ -33,7 +36,10 @@ public async Task HandleAsync(RateEvent @event) Owner = @event.Solution.StudentId }; await _notificationRepository.AddAsync(notification); - notification.Body = $"Задача {@event.Task.Title} оценена."; ///клава + var studentModel = await _authServiceClient.GetAccountData(notification.Owner); + await _notificationsService.SendEmailAsync(notification, studentModel.Email, "Оценка"); + + notification.Body = $"Задача {@event.Task.Title} оценена."; var inlineKeyboard = new InlineKeyboardMarkup(new InlineKeyboardButton { Text = $"{@event.Task.Title}", diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs index f59eaaa0f..9cf6477dd 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs @@ -31,6 +31,7 @@ public async Task HandleAsync(StudentRegisterEvent @event) Owner = @event.UserId }; await _notificationRepository.AddAsync(notification); + await _notificationsService.SendEmailAsync(notification, @event.Email, "HwProj"); await _notificationsService.SendTelegramMessageAsync(notification, null); } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs index 3c303e316..0beaf3985 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs @@ -1,5 +1,6 @@ using System; using System.Threading.Tasks; +using HwProj.AuthService.Client; using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; @@ -8,16 +9,18 @@ namespace HwProj.NotificationsService.API.EventHandlers { - // ReSharper disable once UnusedType.Global public class StudentPassTaskEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; private readonly INotificationsService _notificationsService; + private readonly IAuthServiceClient _authServiceClient; - public StudentPassTaskEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService) + + public StudentPassTaskEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService, IAuthServiceClient authServiceClient) { _notificationRepository = notificationRepository; _notificationsService = notificationsService; + _authServiceClient = authServiceClient; } public async Task HandleAsync(StudentPassTaskEvent @event) @@ -37,6 +40,9 @@ public async Task HandleAsync(StudentPassTaskEvent @event) Owner = m, }; await _notificationRepository.AddAsync(notification); + var mentor = await _authServiceClient.GetAccountData(notification.Owner); + await _notificationsService.SendEmailAsync(notification, mentor.Email, "HwProj"); + notification.Body = $"{@event.Student.Name} {@event.Student.Surname} добавил новое решение задачи {@event.Task.Title} из курса {@event.Course.Name}."; await _notificationsService.SendTelegramMessageAsync(notification, null); } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs index d5f1e33b9..0f8512f0a 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs @@ -1,5 +1,6 @@ using System; using System.Threading.Tasks; +using HwProj.AuthService.Client; using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; @@ -13,11 +14,14 @@ public class UpdateHomeworkEventHandler : IEventHandler { private readonly INotificationsRepository _notificationRepository; private readonly INotificationsService _notificationsService; + private readonly IAuthServiceClient _authServiceClient; - public UpdateHomeworkEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService) + + public UpdateHomeworkEventHandler(INotificationsRepository notificationRepository, INotificationsService notificationsService, IAuthServiceClient authServiceClient) { _notificationRepository = notificationRepository; _notificationsService = notificationsService; + _authServiceClient = authServiceClient; } public async Task HandleAsync(UpdateHomeworkEvent @event) @@ -35,6 +39,9 @@ public async Task HandleAsync(UpdateHomeworkEvent @event) Owner = student.StudentId }; await _notificationRepository.AddAsync(notification); + var studentModel = await _authServiceClient.GetAccountData(student.StudentId); + await _notificationsService.SendEmailAsync(notification, studentModel.Email, "Домашняя работа"); + notification.Body = $"В курсе {@event.Course.Name} домашнее задание {@event.Homework.Title} обновлено.";// клава var inlineKeyboard = new InlineKeyboardMarkup(new InlineKeyboardButton { diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs index 292809002..822de9399 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs @@ -1,9 +1,12 @@ using System; using System.Threading.Tasks; +using AutoMapper; +using HwProj.AuthService.Client; using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; using HwProj.CoursesService.API.Events; +using HwProj.Models.AuthService.DTO; using HwProj.NotificationsService.API.Services; using Telegram.Bot.Types.ReplyMarkups; @@ -13,11 +16,16 @@ public class UpdateTaskMaxRatingEventHandler : IEventHandler(studentAccount); + await _notificationsService.SendEmailAsync(notification, studentModel.Email, "Домашняя работа"); + notification.Body = $"Задача {@event.Task.Title} из {@event.Course.Name} обновлена.";// клава var inlineKeyboard = new InlineKeyboardMarkup(new InlineKeyboardButton { diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj b/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj index ccdf23498..d24a089f3 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj @@ -11,6 +11,7 @@ + diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs index a83be0990..3502a77cc 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs @@ -9,7 +9,7 @@ public interface INotificationsService Task AddNotificationAsync(Notification notification); Task GetAsync(string userId, NotificationFilter filter = null); Task MarkAsSeenAsync(string userId, long[] notificationIds); - + Task SendEmailAsync(Notification notification, string email, string topic); Task SendTelegramMessageAsync(Notification notification, InlineKeyboardMarkup inlineKeyboard); } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs index c5453a72e..9922c9d6e 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs @@ -5,6 +5,7 @@ using HwProj.NotificationsService.API.Repositories; using HwProj.TelegramBotService.Client; using Microsoft.Extensions.Configuration; +using MimeKit; using Telegram.Bot; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; @@ -18,6 +19,7 @@ public class NotificationsService : INotificationsService private readonly IConfigurationSection _configuration; private readonly TelegramBotClient _botClient; private readonly ITelegramBotServiceClient _telegramBotServiceClient; + private readonly MailKit.Net.Smtp.SmtpClient _client; public NotificationsService(INotificationsRepository repository, IMapper mapper, IConfiguration configuration, ITelegramBotServiceClient telegramBotServiceClient) { @@ -26,6 +28,7 @@ public NotificationsService(INotificationsRepository repository, IMapper mapper, _configuration = configuration.GetSection("Telegram"); _telegramBotServiceClient = telegramBotServiceClient; _botClient = new TelegramBotClient(_configuration["Token"]); + _client = new MailKit.Net.Smtp.SmtpClient(); } public async Task AddNotificationAsync(Notification notification) @@ -50,6 +53,26 @@ await _repository.UpdateBatchAsync(userId, notificationIds, t => new Notification {HasSeen = true}); } + public async Task SendEmailAsync(Notification notification, string email, string topic) + { + var emailMessage = new MimeMessage(); + + emailMessage.From.Add(new MailboxAddress("HwProj-2.0.1", _configuration["Mail"])); + emailMessage.To.Add(new MailboxAddress("", email)); + emailMessage.Subject = topic; + emailMessage.Body = new TextPart(MimeKit.Text.TextFormat.Html) + { + Text = notification.Body + }; + + await _client.ConnectAsync(_configuration["ConnectSite"], 465, true); + await _client.AuthenticateAsync(_configuration["Mail"], _configuration["Password"]); + await _client.SendAsync(emailMessage); + + await _client.DisconnectAsync(true); + + } + public async Task SendTelegramMessageAsync(Notification notification, InlineKeyboardMarkup inlineKeyboard) { var user = await _telegramBotServiceClient.GetTelegramUser(notification.Owner); diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json index 46a4b5921..31690ed6b 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json @@ -26,6 +26,6 @@ }, "Telegram": { "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://9afa-92-42-26-35.ngrok.io/" + "Url" : "https://8e76-92-42-26-35.ngrok.io/" } } diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs index 5d5e5c0a3..18c9dda47 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs @@ -6,10 +6,10 @@ namespace HwProj.SolutionsService.API.Events { public class RateEvent : Event { - public HomeworkTaskViewModel Task { get; set; } - public SolutionViewModel Solution { get; set; } + public HomeworkTaskViewModel Task { get; } + public SolutionViewModel Solution { get; } - public long SolutionId { get; set; } + public long SolutionId { get; } public RateEvent(HomeworkTaskViewModel task, SolutionViewModel solution, long solutionId) { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/Commands.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/Commands.cs index fb42457e7..cae490620 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/Commands.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/Commands.cs @@ -11,7 +11,7 @@ public abstract class Commands public abstract Task ExecuteAsync(Update update); protected InlineKeyboardButton GetButton(string text, string callbackData) - => new InlineKeyboardButton + => new() { Text = text, CallbackData = callbackData diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs index 02cb2e6e6..1284752e6 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs @@ -21,7 +21,7 @@ public ErrorCommand(TelegramBot telegramBot, IUserService userService) public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetUserByUpdate(update); + var user = await _userService.UserByUpdate(update); await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!\n Введите ваш e-mail на Hw-Proj2.0.1", ParseMode.Markdown); } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs index 86227ca2b..365acb94a 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs @@ -25,7 +25,7 @@ public GetAllCourses(TelegramBot telegramBot, IUserService userService, ICourses public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetUserByUpdate(update); + var user = await _userService.UserByUpdate(update); await _botClient.SendTextMessageAsync(user.ChatId, "Повторите запрос снова!", ParseMode.Markdown/*, replyMarkup:inlineKeyboard*/); } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs index ba49ab0f0..b829eca32 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs @@ -26,7 +26,7 @@ public GetCourses(TelegramBot telegramBot, ICoursesServiceClient coursesServiceC public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetUserByUpdate(update); + var user = await _userService.UserByUpdate(update); var courses = _coursesServiceClient.GetAllUserCourses(user.AccountId).Result; await _botClient.SendTextMessageAsync(user.ChatId, "*Выберите курс для просмотра домашних работ или статистики:*", ParseMode.Markdown); @@ -39,7 +39,7 @@ public override async Task ExecuteAsync(Update update) cols.Add(GetButton("Cтатистика", $"/statistics {course.Id}")); rows.Add(cols.ToArray()); var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); - await _botClient.SendTextMessageAsync(user.ChatId, "Курс:" + $" {course.Name}", parseMode: ParseMode.Html, replyMarkup:keyboardMarkup); + await _botClient.SendTextMessageAsync(user.ChatId, "Курс:" + $" {course.Name}", ParseMode.Html, replyMarkup:keyboardMarkup); } } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs index 5a85fd212..010544f72 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs @@ -27,7 +27,7 @@ public GetHomeworks(TelegramBot telegramBot, ICoursesServiceClient coursesServic public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetUserByUpdate(update); + var user = await _userService.UserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var homeworks = _coursesServiceClient.GetAllHomeworkByCourse(Int32.Parse(text[1])).Result; @@ -54,7 +54,7 @@ public override async Task ExecuteAsync(Update update) await _botClient.SendTextMessageAsync( user.ChatId, $"Курс: {course.Name}\nВыберите домашнюю работу", - parseMode: ParseMode.Html, + ParseMode.Html, replyMarkup:keyboardMarkup); } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs index e6d4a87a3..abe7484c2 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs @@ -31,7 +31,7 @@ public GetSolutionInfo(TelegramBot telegramBot, ISolutionsServiceClient solution public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetUserByUpdate(update); + var user = await _userService.UserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var solution =_solutionsServiceClient.GetSolutionById(Int32.Parse(text[1])).Result; @@ -57,7 +57,7 @@ public override async Task ExecuteAsync(Update update) await _botClient.SendTextMessageAsync(user.ChatId, $"Отзыв преподователя: {solution.LecturerComment}." + $"\nОценка: {solution.Rating}/{task.MaxRating}.", - parseMode: ParseMode.Html, + ParseMode.Html, replyMarkup:keyboardMarkup); } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs index 4717814bd..83a313f98 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs @@ -30,7 +30,7 @@ public GetSolutionsFromTask(TelegramBot telegramBot, IUserService userService, I public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetUserByUpdate(update); + var user = await _userService.UserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var solutions = _solutionsServiceClient.GetUserSolution(Int32.Parse(text[1]), user.AccountId).Result; @@ -62,7 +62,7 @@ await _botClient.SendTextMessageAsync(user.ChatId, $"\nДомашнаяя работа: {hw.Title}" + $"\nЗадача: {task.Title}" + "\nВыберите решение:", - parseMode: ParseMode.Html, + ParseMode.Html, replyMarkup : keyboardMarkup); } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs index b2aa41f19..fe9d07171 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs @@ -30,7 +30,7 @@ public GetStatistics(TelegramBot telegramBot, IUserService userService, ICourses public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetUserByUpdate(update); + var user = await _userService.UserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var course = _coursesServiceClient.GetCourseById(Int64.Parse(text[1]), user.AccountId).Result; @@ -62,7 +62,7 @@ public override async Task ExecuteAsync(Update update) await _botClient.SendTextMessageAsync(user.ChatId, $"Курс: {course.Name}." + $"\nБаллы: {studentRating}/{maxRating}", - parseMode: ParseMode.Html, + ParseMode.Html, replyMarkup:inlineKeyboard); } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs index 44f220c49..05d8d8ea5 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs @@ -29,7 +29,7 @@ public GetTaskInfo(TelegramBot telegramBot, ICoursesServiceClient coursesService public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetUserByUpdate(update); + var user = await _userService.UserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var task = _coursesServiceClient.GetTask(Int64.Parse(text[1])).Result; @@ -53,7 +53,7 @@ await _botClient.SendTextMessageAsync(user.ChatId, $"\nДата публикации: {task.PublicationDate.Date}." + $"\nДедлайн: {task.DeadlineDate}." + $"\nМаксимальный балл: {task.MaxRating}.", - parseMode: ParseMode.Html, + ParseMode.Html, replyMarkup:keyboardMarkup); } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs index 1ea88a4fa..d21e4e973 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs @@ -28,7 +28,7 @@ public GetTasks(TelegramBot telegramBot, ICoursesServiceClient coursesServiceCli public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetUserByUpdate(update); + var user = await _userService.UserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var hw = _coursesServiceClient.GetHomework(Int32.Parse(text[1])).Result; @@ -61,7 +61,7 @@ await _botClient.SendTextMessageAsync( $"\nHomework: {hw.Title}" + $"\nОписание: {hw.Description}" + "\nВыберите задачу:", - parseMode: ParseMode.Html, + ParseMode.Html, replyMarkup:keyboardMarkup); } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs index 274ad6f98..6d8a2f60a 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs @@ -25,11 +25,12 @@ public SendSolution(TelegramBot telegramBot, IUserService userService, public override async Task ExecuteAsync(Update update) { - var user = await _userService.GetUserByUpdate(update); + var user = await _userService.UserByUpdate(update); /*await _solutionsServiceClient.PostSolution();*/ - await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!", + await _botClient.SendTextMessageAsync(user.ChatId, "Введите ссылку на pull request и комментарий. " + + "\n Пример: ' <комментарий'", ParseMode.Markdown /*, replyMarkup:inlineKeyboard*/); } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs index 75a96b635..492480b18 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs @@ -25,7 +25,7 @@ public override async Task ExecuteAsync(Update update) if (user == null) { - await _botClient.SendTextMessageAsync(update.Message.Chat.Id, "E-mail не зарегистрирован на Hw-Proj.\nВведите /start", ParseMode.Markdown); + await _botClient.SendTextMessageAsync(update.Message.Chat.Id, "E-mail не зарегистрирован на Hw-Proj2.0.1.\nВведите /start", ParseMode.Markdown); } await _botClient.SendTextMessageAsync(user.ChatId, "Ваш код отправлен.\nВведите его:", ParseMode.Markdown); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs index e30fa374f..9df6fc9b1 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs @@ -44,7 +44,7 @@ public async Task Update(Update update) [HttpGet("get/{studentId}")] public async Task GetUser(string studentId) { - return await _userService.GetTelegramUserModelByStudentId(studentId); + return await _userService.TelegramUserModelByStudentId(studentId); } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs index 876834388..ee3c1e5cc 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs @@ -5,7 +5,7 @@ namespace HwProj.TelegramBotService.API.Events { public class ConfirmTelegramBotEvent : Event { - public TelegramUserModel TelegramUserModel { get; set; } + public TelegramUserModel TelegramUserModel { get; } public ConfirmTelegramBotEvent(TelegramUserModel userModel) { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs index c824f5bd6..00ec51714 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs @@ -2,7 +2,7 @@ namespace HwProj.TelegramBotService.API.Models { - public class TelegramUserModel /*: IEntity*/ + public class TelegramUserModel { public long Id { get; set; } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserResponse.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserResponse.cs deleted file mode 100644 index a8c1ef4fc..000000000 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserResponse.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace HwProj.TelegramBotService.API.Models -{ - public class TelegramUserResponse - { - public long AuthDate { get; set; } - public string FirstName { get; set; } - public string Hash { get; set; } - public long ChatId { get; set; } - public string LastName { get; set; } - } -} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs deleted file mode 100644 index bfe4da7b1..000000000 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs +++ /dev/null @@ -1,10 +0,0 @@ -using HwProj.Repositories; -using HwProj.TelegramBotService.API.Models; - -namespace HwProj.TelegramBotService.API.Repositories -{ - /*public interface ITelegramBotRepository : ICrudRepository - { - - }*/ -} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs deleted file mode 100644 index 451cc06db..000000000 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs +++ /dev/null @@ -1,13 +0,0 @@ -using HwProj.Repositories; -using HwProj.TelegramBotService.API.Models; - -namespace HwProj.TelegramBotService.API.Repositories -{ - /*public class TelegramBotRepository : CrudRepository, ITelegramBotRepository - { - public TelegramBotRepository(TelegramBotContext context) - : base(context) - { - } - }*/ -} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs index f2d8a8d13..431f344c1 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs @@ -25,8 +25,12 @@ public CommandService(IServiceProvider serviceProvider, TelegramBotContext conte public async Task Execute(Update update) { - if(update?.Message?.Chat == null && update?.CallbackQuery == null) + if (update?.Message?.Chat == null && update?.CallbackQuery == null) + { return; + } + + var user = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result; if (update.Type == UpdateType.Message) { @@ -40,7 +44,6 @@ public async Task Execute(Update update) await ExecuteCommand(CommandNames.GetCourses, update); return; } - var user = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result; if (user.Operation == "wait_code" || user.Operation == "check_code") { switch (user.Operation) @@ -53,16 +56,8 @@ public async Task Execute(Update update) break; } } - if (user == null) - { - await ExecuteCommand(CommandNames.StartCommand, update); - } - if (user.Operation == null) - { - - } } - else + else if (user.IsLecture == false) { switch (update.CallbackQuery.Data.Split(' ')[0]) { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs index 41fbe8cb5..a227802d0 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs @@ -12,12 +12,10 @@ public interface IUserService Task AddFinishUser(Update update); - Task GetUserByUpdate(Update update); + Task UserByUpdate(Update update); - Task GetTelegramUserModelByStudentId(string studentId); + Task TelegramUserModelByStudentId(string studentId); Task DeleteUser(Update update); - - Task GetTelegramUserModelByChatId(long chatId); } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs index 32158ac44..e8df11f79 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs @@ -1,9 +1,9 @@ using System; using System.Linq; +using System.Text; using System.Threading.Tasks; using HwProj.AuthService.Client; using HwProj.EventBus.Client.Interfaces; -using HwProj.Models.AuthService.DTO; using HwProj.TelegramBotService.API.Events; using HwProj.TelegramBotService.API.Models; using Microsoft.EntityFrameworkCore; @@ -26,11 +26,13 @@ public UserService(TelegramBotContext context, IAuthServiceClient authClient, IE public async Task CreateUser(Update update) { - /*var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id); - _context.Remove(user); - await _context.SaveChangesAsync();*/ var random = new Random(); - var code = random.Next(10) * 1000 + random.Next(10) * 100 + random.Next(10) * 10 + random.Next(10); + var chars = "ABCEFGHJKPQRSTXYZ0123456789"; + var code = new StringBuilder(); + code.Append(chars[random.Next(chars.Length)]); + code.Append(chars[random.Next(chars.Length)]); + code.Append(chars[random.Next(chars.Length)]); + code.Append(chars[random.Next(chars.Length)]); var newUser = new TelegramUserModel { Id = update.Message.Chat.Id, @@ -90,10 +92,10 @@ public async Task AddFinishUser(Update update) return user; } - public async Task GetUserByUpdate(Update update) + public async Task UserByUpdate(Update update) => await _context.TelegramUser.FindAsync(update.CallbackQuery == null ? update.Message.Chat.Id : update.CallbackQuery.Message.Chat.Id); - public async Task GetTelegramUserModelByStudentId(string studentId) + public async Task TelegramUserModelByStudentId(string studentId) => _context.TelegramUser.First(x => x.AccountId == studentId); public async Task DeleteUser(Update update) @@ -106,8 +108,5 @@ public async Task DeleteUser(Update update) await _context.SaveChangesAsync(); } } - - public async Task GetTelegramUserModelByChatId(long chatId) - => _context.TelegramUser.FindAsync(chatId).Result; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json index 6c9b5a59a..d51d472f5 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json @@ -24,5 +24,5 @@ "TelegramBot" : "http://localhost:5009" }, "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://9afa-92-42-26-35.ngrok.io/" + "Url" : "https://8e76-92-42-26-35.ngrok.io/" } \ No newline at end of file From 24c4ea0f3da824ad73dfc1857b923f7877e806b7 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Fri, 24 Dec 2021 21:05:44 +0300 Subject: [PATCH 10/19] fix bugs --- .../TelegramBotService/UserTelegram.cs | 21 ++++++ .../ConfirmTelegramBotEventHandler.cs | 4 +- .../EventHandlers/NewHomeworkEventHandler.cs | 2 +- .../Services/NotificationsService.cs | 8 ++- .../appsettings.json | 8 ++- .../Services/ISolutionsService.cs | 2 +- .../Services/SolutionsService.cs | 25 +++++-- .../Commands/CommandNames.cs | 1 + .../Commands/GetAllCourses.cs | 2 +- .../Commands/GetTaskInfo.cs | 3 + .../Commands/SendSolution.cs | 47 +++++++++++-- .../Commands/StartCommand.cs | 3 +- .../Commands/WaitCodeCommand.cs | 3 +- .../Commands/WaitSolution.cs | 40 +++++++++++ .../Controllers/TelegramBotController.cs | 3 +- .../Events/ConfirmTelegramBotEvent.cs | 10 ++- .../HwProj.TelegramBotService.API.csproj | 2 + .../Models/TelegramBotContext.cs | 8 ++- .../Models/TelegramUserModel.cs | 10 +-- .../Repositories/ITelegramBotRepository.cs | 12 ++++ .../Repositories/TelegramBotRepository.cs | 22 ++++++ .../Service/CommandService.cs | 60 ++++++++-------- .../Service/IUserService.cs | 15 ++-- .../Service/UserService.cs | 65 +++++++++++------- .../HwProj.TelegramBotService.API/Startup.cs | 2 + .../appsettings.json | 2 +- .../ITelegramBotServiceClient.cs | 5 +- .../TelegramBotServiceClient.cs | 7 +- hwproj.front/src/components/Profile.tsx | 20 +++--- .../src/components/Styles/telegram.css | 4 -- hwproj.front/src/components/tlgm.png | Bin 1248 -> 0 bytes 31 files changed, 300 insertions(+), 116 deletions(-) create mode 100644 HwProj.Common/HwProj.Models/TelegramBotService/UserTelegram.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitSolution.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs delete mode 100644 hwproj.front/src/components/Styles/telegram.css delete mode 100644 hwproj.front/src/components/tlgm.png diff --git a/HwProj.Common/HwProj.Models/TelegramBotService/UserTelegram.cs b/HwProj.Common/HwProj.Models/TelegramBotService/UserTelegram.cs new file mode 100644 index 000000000..4622678c8 --- /dev/null +++ b/HwProj.Common/HwProj.Models/TelegramBotService/UserTelegram.cs @@ -0,0 +1,21 @@ +using HwProj.Repositories; + +namespace HwProj.Models.TelegramBotService +{ + public class UserTelegram : IEntity + { + public long Id { get; set; } + + public long ChatId { get; set; } + + public string AccountId { get; set; } + + public bool IsLecture { get; set; } + + public bool IsRegistered { get; set; } + + public string Code { get; set; } + + public string Operation { get; set; } + } +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs index 622046862..3c6198ec8 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/ConfirmTelegramBotEventHandler.cs @@ -22,11 +22,11 @@ public async Task HandleAsync(ConfirmTelegramBotEvent @event) var notification = new Notification { Sender = "TelegramBotService", - Body = $"Ваш код для телеграмма - {@event.TelegramUserModel.Code}.", + Body = $"Ваш код для телеграмма - {@event.Code}.", Category = "TelegramBotService", Date = DateTime.UtcNow, HasSeen = false, - Owner = @event.TelegramUserModel.AccountId + Owner = @event.StudentId }; await _notificationRepository.AddAsync(notification); } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs index acadd851d..f949feb1a 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs @@ -51,7 +51,7 @@ public async Task HandleAsync(NewHomeworkEvent @event) var inlineKeyboard = new InlineKeyboardMarkup(new InlineKeyboardButton { Text = $"{@event.Homework}", - CallbackData = $"/homeworks {@event.HomeworkId}" + CallbackData = $"/homeworks {@event.Course.Id}" }); await _notificationsService.SendTelegramMessageAsync(notification, inlineKeyboard); } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs index 9922c9d6e..1a4b6e8b9 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs @@ -17,6 +17,7 @@ public class NotificationsService : INotificationsService private readonly INotificationsRepository _repository; private readonly IMapper _mapper; private readonly IConfigurationSection _configuration; + private readonly IConfigurationSection _configurationMail; private readonly TelegramBotClient _botClient; private readonly ITelegramBotServiceClient _telegramBotServiceClient; private readonly MailKit.Net.Smtp.SmtpClient _client; @@ -26,6 +27,7 @@ public NotificationsService(INotificationsRepository repository, IMapper mapper, _repository = repository; _mapper = mapper; _configuration = configuration.GetSection("Telegram"); + _configurationMail = configuration.GetSection("Notification"); _telegramBotServiceClient = telegramBotServiceClient; _botClient = new TelegramBotClient(_configuration["Token"]); _client = new MailKit.Net.Smtp.SmtpClient(); @@ -57,7 +59,7 @@ public async Task SendEmailAsync(Notification notification, string email, string { var emailMessage = new MimeMessage(); - emailMessage.From.Add(new MailboxAddress("HwProj-2.0.1", _configuration["Mail"])); + emailMessage.From.Add(new MailboxAddress("HwProj-2.0.1", _configurationMail["Mail"])); emailMessage.To.Add(new MailboxAddress("", email)); emailMessage.Subject = topic; emailMessage.Body = new TextPart(MimeKit.Text.TextFormat.Html) @@ -65,8 +67,8 @@ public async Task SendEmailAsync(Notification notification, string email, string Text = notification.Body }; - await _client.ConnectAsync(_configuration["ConnectSite"], 465, true); - await _client.AuthenticateAsync(_configuration["Mail"], _configuration["Password"]); + await _client.ConnectAsync(_configurationMail["ConnectSite"], 465, true); + await _client.AuthenticateAsync(_configurationMail["Mail"], _configurationMail["Password"]); await _client.SendAsync(emailMessage); await _client.DisconnectAsync(true); diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json index 31690ed6b..a5d8cfc43 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json @@ -24,8 +24,14 @@ "Solutions": "http://localhost:5007", "TelegramBot" : "http://localhost:5009" }, + "Notification": { + "Mail": "testhwproj@gmail.com", + "ConnectSite": "smtp.gmail.com", + "Password": "HwProj-2.0.1", + "Url": "http://localhost:3000" + }, "Telegram": { "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://8e76-92-42-26-35.ngrok.io/" + "Url" : "https://502f-92-42-26-35.ngrok.io/" } } diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs index c58b7f31f..c94898927 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs @@ -16,7 +16,7 @@ public interface ISolutionsService Task PostOrUpdateAsync(long taskId, Solution solution); - /*Task PostOrUpdateFromTelegramAsync(long taskId, string githubUrl, string comment);*/ + Task PostFromTelegramAsync(long taskId, string githubUrl, string comment, string studentId); Task RateSolutionAsync(long solutionId, int newRating, string lecturerComment); diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs index 79d8d4fba..303f1925f 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs @@ -84,18 +84,29 @@ public async Task PostOrUpdateAsync(long taskId, Solution solution) return solution.Id; } - /*public async Task PostOrUpdateFromTelegramAsync(long taskId, string githubUrl, string comment, string studentId) + public async Task PostFromTelegramAsync(long taskId, string githubUrl, string comment, + string studentId) { - var solution = new Solution { - Id = , + var task1 = _coursesServiceClient.GetTask(taskId); + var taskModel1 = _mapper.Map(task1); + var homework1 = await _coursesServiceClient.GetHomework(taskModel1.HomeworkId); + var courseId = homework1.CourseId; + var group = await _coursesServiceClient.GetCourseGroupsById(courseId, studentId); + long? groupId = null; + if (group.Tasks.Contains(taskId)) + { + groupId = group.Id; + } + var solution = new Solution{ + GithubUrl = githubUrl, Comment = comment, - State = SolutionState.Rated, + State = SolutionState.Posted, StudentId = studentId, - GroupId = , + GroupId = groupId, TaskId = taskId, PublicationDate = DateTime.Now, - LecturerComment = null}; + LecturerComment = null}; var allSolutionsForTask= await GetTaskSolutionsFromStudentAsync(taskId, solution.StudentId); var currentSolution = allSolutionsForTask.FirstOrDefault(s => s.Id == solution.Id); var solutionModel = _mapper.Map(solution); @@ -124,7 +135,7 @@ public async Task PostOrUpdateAsync(long taskId, Solution solution) ); return solution.Id; - }*/ + } public async Task RateSolutionAsync(long solutionId, int newRating, string lecturerComment) { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs index df694b467..0af4dc0d6 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs @@ -15,5 +15,6 @@ public static class CommandNames public const string WaitCodeCommand = "wait_code"; public const string CheckCodeCommand = "check_code"; public const string ErrorCommand = "error_response"; + public const string WaitSolution = "wait_solution"; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs index 365acb94a..96ff6481d 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs @@ -27,7 +27,7 @@ public override async Task ExecuteAsync(Update update) { var user = await _userService.UserByUpdate(update); - await _botClient.SendTextMessageAsync(user.ChatId, "Повторите запрос снова!", ParseMode.Markdown/*, replyMarkup:inlineKeyboard*/); + await _botClient.SendTextMessageAsync(user.ChatId, "Повторите запрос снова!", ParseMode.Markdown); } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs index 05d8d8ea5..64c69415e 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs @@ -40,6 +40,9 @@ public override async Task ExecuteAsync(Update update) cols.Add(GetButton($"Решения {task.Title}", $"/solutions {task.Id}")); rows.Add(cols.ToArray()); cols = new List(); + cols.Add(GetButton($"Отправить решение {task.Title}", $"/wait_solution {task.Id}")); + rows.Add(cols.ToArray()); + cols = new List(); cols.Add(GetButton("Мои курсы", $"/courses")); cols.Add(GetButton("Мои домашки", $"/homeworks {hw.CourseId}")); cols.Add(GetButton("Мои задачи", $"/task {task.HomeworkId}")); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs index 6d8a2f60a..54b151300 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs @@ -1,9 +1,14 @@ -using System.Threading.Tasks; +using System.Collections.Generic; +using System.Threading.Tasks; +using HwProj.CoursesService.Client; +using HwProj.SolutionsService.API.Services; using HwProj.SolutionsService.Client; using HwProj.TelegramBotService.API.Service; +using Microsoft.AspNetCore.Builder; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; +using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.TelegramBotService.API.Commands { @@ -11,14 +16,16 @@ public class SendSolution : Commands { private readonly TelegramBotClient _botClient; private readonly IUserService _userService; - private readonly ISolutionsServiceClient _solutionsServiceClient; + private readonly ISolutionsService _solutionsServiceClient; + private readonly ICoursesServiceClient _coursesServiceClient; public SendSolution(TelegramBot telegramBot, IUserService userService, - ISolutionsServiceClient solutionsServiceClient) + ISolutionsService solutionsServiceClient, ICoursesServiceClient coursesServiceClient) { _botClient = telegramBot.GetBot().Result; _userService = userService; _solutionsServiceClient = solutionsServiceClient; + _coursesServiceClient = coursesServiceClient; } public override string Name => CommandNames.SendSolution; @@ -26,12 +33,38 @@ public SendSolution(TelegramBot telegramBot, IUserService userService, public override async Task ExecuteAsync(Update update) { var user = await _userService.UserByUpdate(update); + /*if (user.TaskId == -1) + { + await _botClient.SendTextMessageAsync(user.ChatAspNetUsersId, "Попробуйте ещё раз.", + ParseMode.Markdown); + return; + }*/ - /*await _solutionsServiceClient.PostSolution();*/ + var message = update.CallbackQuery.Data; - await _botClient.SendTextMessageAsync(user.ChatId, "Введите ссылку на pull request и комментарий. " + - "\n Пример: ' <комментарий'", - ParseMode.Markdown /*, replyMarkup:inlineKeyboard*/); + var pullRequested = message.Split(' ')[0]; + var comment = message.Split(' ')[1]; + /*await _solutionsServiceClient.PostFromTelegramAsync(user.TaskId, pullRequested, comment, user.AccountId); + var task = _coursesServiceClient.GetTask(user.TaskId).Result; + var hw = _coursesServiceClient.GetHomework(task.HomeworkId).Result; + + var rows = new List(); + var cols = new List(); + cols.Add(GetButton($"Решения {task.Title}", $"/solutions {task.Id}")); + rows.Add(cols.ToArray()); + cols = new List(); + cols.Add(GetButton($"Отправить решение {task.Title}", $"/wait_solution {task.Id}")); + rows.Add(cols.ToArray()); + cols = new List(); + cols.Add(GetButton("Мои курсы", $"/courses")); + cols.Add(GetButton("Мои домашки", $"/homeworks {hw.CourseId}")); + cols.Add(GetButton("Мои задачи", $"/task {task.HomeworkId}")); + rows.Add(cols.ToArray()); + + var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray());*/ + + await _botClient.SendTextMessageAsync(user.ChatId, "Ваша задача отправлена.", + ParseMode.Markdown/*, replyMarkup:keyboardMarkup*/); } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs index f103dd1b1..b5137cf74 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs @@ -26,7 +26,8 @@ public override async Task ExecuteAsync(Update update) var user = await _userService.CreateUser(update); - await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!\n Введите ваш e-mail на Hw-Proj2.0.1", ParseMode.Markdown); + await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!\n Введите ваш e-mail на Hw-Proj2.0.1", + ParseMode.Markdown); } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs index 492480b18..9b8900683 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs @@ -25,7 +25,8 @@ public override async Task ExecuteAsync(Update update) if (user == null) { - await _botClient.SendTextMessageAsync(update.Message.Chat.Id, "E-mail не зарегистрирован на Hw-Proj2.0.1.\nВведите /start", ParseMode.Markdown); + await _botClient.SendTextMessageAsync(update.Message.Chat.Id, "E-mail не зарегистрирован на Hw-Proj2.0.1." + + "\nВведите /start", ParseMode.Markdown); } await _botClient.SendTextMessageAsync(user.ChatId, "Ваш код отправлен.\nВведите его:", ParseMode.Markdown); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitSolution.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitSolution.cs new file mode 100644 index 000000000..0053d03a9 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitSolution.cs @@ -0,0 +1,40 @@ +using System; +using System.Threading.Tasks; +using HwProj.SolutionsService.Client; +using HwProj.TelegramBotService.API.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + +namespace HwProj.TelegramBotService.API.Commands +{ + public class WaitSolution: Commands + { + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + private readonly ISolutionsServiceClient _solutionsServiceClient; + + public WaitSolution(TelegramBot telegramBot, IUserService userService, + ISolutionsServiceClient solutionsServiceClient) + { + _botClient = telegramBot.GetBot().Result; + _userService = userService; + _solutionsServiceClient = solutionsServiceClient; + } + + public override string Name => CommandNames. WaitSolution; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.UserByUpdate(update); + var message = update.CallbackQuery.Data; + var taskId = int.Parse(message.Split(' ')[1]); + + user = await _userService.AddTaskIdToSentSolution(update.CallbackQuery.Message.Chat.Id, taskId); + + await _botClient.SendTextMessageAsync(user.ChatId, "Введите ссылку на pull request и комментарий. " + + "\n Пример: ' <комментарий'", + ParseMode.Markdown); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs index 9df6fc9b1..27670048a 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs @@ -1,5 +1,6 @@ using System; using System.Threading.Tasks; +using HwProj.Models.TelegramBotService; using HwProj.TelegramBotService.API.Models; using HwProj.TelegramBotService.API.Service; using Microsoft.AspNetCore.Mvc; @@ -42,7 +43,7 @@ public async Task Update(Update update) } [HttpGet("get/{studentId}")] - public async Task GetUser(string studentId) + public async Task GetUser(string studentId) { return await _userService.TelegramUserModelByStudentId(studentId); } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs index ee3c1e5cc..70ee043b4 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Events/ConfirmTelegramBotEvent.cs @@ -1,15 +1,19 @@ using HwProj.EventBus.Client; +using HwProj.Models.TelegramBotService; using HwProj.TelegramBotService.API.Models; namespace HwProj.TelegramBotService.API.Events { public class ConfirmTelegramBotEvent : Event { - public TelegramUserModel TelegramUserModel { get; } + public string StudentId { get; } + + public string Code { get; } - public ConfirmTelegramBotEvent(TelegramUserModel userModel) + public ConfirmTelegramBotEvent(string studentId, string code) { - TelegramUserModel = userModel; + StudentId = studentId; + Code = code; } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/HwProj.TelegramBotService.API.csproj b/HwProj.TelegramBot/HwProj.TelegramBotService.API/HwProj.TelegramBotService.API.csproj index b8fa61a22..8358aee3d 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/HwProj.TelegramBotService.API.csproj +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/HwProj.TelegramBotService.API.csproj @@ -14,6 +14,7 @@ + @@ -21,6 +22,7 @@ + diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramBotContext.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramBotContext.cs index eb9d74d21..c71ca70a7 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramBotContext.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramBotContext.cs @@ -1,14 +1,16 @@ -using Microsoft.EntityFrameworkCore; +using HwProj.Models.TelegramBotService; +using Microsoft.EntityFrameworkCore; namespace HwProj.TelegramBotService.API.Models { - public class TelegramBotContext : DbContext + public sealed class TelegramBotContext : DbContext { - public DbSet TelegramUser { get; set; } + public DbSet TelegramUser { get; set; } public TelegramBotContext(DbContextOptions options) : base(options) { + Database.EnsureCreated(); } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs index 00ec51714..bbffe50f7 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs @@ -1,10 +1,10 @@ -using HwProj.Repositories; +/*using HwProj.Repositories; namespace HwProj.TelegramBotService.API.Models { public class TelegramUserModel { - public long Id { get; set; } + /*public long Id { get; set; } public long ChatId { get; set; } @@ -16,6 +16,8 @@ public class TelegramUserModel public string Code { get; set; } - public string Operation { get; set; } + public string Operation { get; set; }#1# + + /*public long TaskId { get; set; }#1# } -} \ No newline at end of file +}*/ \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs new file mode 100644 index 000000000..ff99752bd --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs @@ -0,0 +1,12 @@ +using System.Linq; +using System.Threading.Tasks; +using HwProj.Models.TelegramBotService; +using HwProj.Repositories; + +namespace HwProj.TelegramBotService.API.Repositories +{ + public interface ITelegramBotRepository : ICrudRepository + { + IQueryable GetUserTelegramByChatId(long chatId); + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs new file mode 100644 index 000000000..96557ca17 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs @@ -0,0 +1,22 @@ +using System.Linq; +using System.Threading.Tasks; +using HwProj.Models.TelegramBotService; +using HwProj.Repositories; +using HwProj.TelegramBotService.API.Models; +using Microsoft.EntityFrameworkCore; + +namespace HwProj.TelegramBotService.API.Repositories +{ + public class TelegramBotRepository : CrudRepository, ITelegramBotRepository + { + public TelegramBotRepository(TelegramBotContext context) + : base(context) + { + } + + public IQueryable GetUserTelegramByChatId(long chatId) + { + return Context.Set().Where(h => h.ChatId == chatId); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs index 431f344c1..2ca28b9f1 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs @@ -29,9 +29,7 @@ public async Task Execute(Update update) { return; } - - var user = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result; - + if (update.Type == UpdateType.Message) { var message = update.Message?.Text; @@ -44,9 +42,10 @@ public async Task Execute(Update update) await ExecuteCommand(CommandNames.GetCourses, update); return; } - if (user.Operation == "wait_code" || user.Operation == "check_code") + var userWantRegister = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result; + if (userWantRegister.Operation == "wait_code" || userWantRegister.Operation == "check_code") { - switch (user.Operation) + switch (userWantRegister.Operation) { case "wait_code": await ExecuteCommand(CommandNames.WaitCodeCommand, update); @@ -57,34 +56,37 @@ public async Task Execute(Update update) } } } - else if (user.IsLecture == false) + else if (update.Type == UpdateType.CallbackQuery) { - switch (update.CallbackQuery.Data.Split(' ')[0]) + var user = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id).Result; + if (user.IsLecture == false) { - case "/courses": - await ExecuteCommand(CommandNames.GetCourses, update); - break; - case "/homeworks": - await ExecuteCommand(CommandNames.GetHomeworks, update); - break; - case "/statistics": - await ExecuteCommand(CommandNames.GetStatistics, update); - break; - case "/task": - await ExecuteCommand(CommandNames.GetTasks, update); - break; - case "/taskinfo": - await ExecuteCommand(CommandNames.GetTaskInfo, update); - break; - case "/solutions": - await ExecuteCommand(CommandNames.GetSolutionsFromTask, update); - break; - case "/solutioninfo": - await ExecuteCommand(CommandNames.GetSolutionInfo, update); - break; + switch (update.CallbackQuery.Data.Split(' ')[0]) + { + case "/courses": + await ExecuteCommand(CommandNames.GetCourses, update); + break; + case "/homeworks": + await ExecuteCommand(CommandNames.GetHomeworks, update); + break; + case "/statistics": + await ExecuteCommand(CommandNames.GetStatistics, update); + break; + case "/task": + await ExecuteCommand(CommandNames.GetTasks, update); + break; + case "/taskinfo": + await ExecuteCommand(CommandNames.GetTaskInfo, update); + break; + case "/solutions": + await ExecuteCommand(CommandNames.GetSolutionsFromTask, update); + break; + case "/solutioninfo": + await ExecuteCommand(CommandNames.GetSolutionInfo, update); + break; + } } } - } private async Task ExecuteCommand(string commandName, Update update) diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs index a227802d0..f0695d1c4 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs @@ -1,4 +1,5 @@ using System.Threading.Tasks; +using HwProj.Models.TelegramBotService; using HwProj.TelegramBotService.API.Models; using Telegram.Bot.Types; @@ -6,16 +7,18 @@ namespace HwProj.TelegramBotService.API.Service { public interface IUserService { - Task CreateUser(Update update); + Task CreateUser(Update update); - Task AddEmailToUser(Update update); + Task AddEmailToUser(Update update); - Task AddFinishUser(Update update); + Task AddFinishUser(Update update); - Task UserByUpdate(Update update); + Task UserByUpdate(Update update); + + Task TelegramUserModelByStudentId(string studentId); + + Task AddTaskIdToSentSolution(long chatId, long taskId); - Task TelegramUserModelByStudentId(string studentId); - Task DeleteUser(Update update); } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs index e8df11f79..a920b3cf1 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs @@ -2,10 +2,13 @@ using System.Linq; using System.Text; using System.Threading.Tasks; +using AutoMapper; using HwProj.AuthService.Client; using HwProj.EventBus.Client.Interfaces; +using HwProj.Models.TelegramBotService; using HwProj.TelegramBotService.API.Events; using HwProj.TelegramBotService.API.Models; +using HwProj.TelegramBotService.API.Repositories; using Microsoft.EntityFrameworkCore; using Telegram.Bot.Types; @@ -13,18 +16,22 @@ namespace HwProj.TelegramBotService.API.Service { public class UserService : IUserService { + private readonly ITelegramBotRepository _telegramBotRepository; private readonly TelegramBotContext _context; private readonly IAuthServiceClient _authClient; private readonly IEventBus _eventBus; + private readonly IMapper _mapper; - public UserService(TelegramBotContext context, IAuthServiceClient authClient, IEventBus eventBus) + public UserService(TelegramBotContext context, IAuthServiceClient authClient, IEventBus eventBus, ITelegramBotRepository telegramBotRepository, IMapper mapper) { _context = context; _authClient = authClient; _eventBus = eventBus; + _telegramBotRepository = telegramBotRepository; + _mapper = mapper; } - public async Task CreateUser(Update update) + public async Task CreateUser(Update update) { var random = new Random(); var chars = "ABCEFGHJKPQRSTXYZ0123456789"; @@ -33,15 +40,15 @@ public async Task CreateUser(Update update) code.Append(chars[random.Next(chars.Length)]); code.Append(chars[random.Next(chars.Length)]); code.Append(chars[random.Next(chars.Length)]); - var newUser = new TelegramUserModel + var newUser = new UserTelegram { - Id = update.Message.Chat.Id, ChatId = update.Message.Chat.Id, AccountId = null, IsLecture = false, IsRegistered = false, Code = code.ToString(), - Operation = "wait_code" + Operation = "wait_code", + /*TaskId = -1*/ }; var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == newUser.ChatId); @@ -56,47 +63,59 @@ public async Task CreateUser(Update update) return result.Entity; } - public async Task AddEmailToUser(Update update) + public async Task AddEmailToUser(Update update) { var message = update.Message?.Text; - var user = await _context.TelegramUser.FindAsync(update.Message.Chat.Id); - if (user.Operation != "wait_code" || user == null) + var user = _telegramBotRepository.GetUserTelegramByChatId(update.Message.Chat.Id); + var userModel = user.ToArray()[0]; + if (userModel.Operation != "wait_code" || user == null) { - _context.Remove(user); + _context.Remove(userModel); await _context.SaveChangesAsync(); return null; } var accountId = _authClient.FindByEmailAsync(message).Result; var studentModel = _authClient.GetAccountData(accountId).Result; - user.Operation = "check_code"; - user.AccountId = accountId; - user.IsLecture = studentModel.Role == "Lecture"; + userModel.Operation = "check_code"; + userModel.AccountId = accountId; + userModel.IsLecture = studentModel.Role == "Lecture"; await _context.SaveChangesAsync(); - _eventBus.Publish(new ConfirmTelegramBotEvent(user)); - return user; + _eventBus.Publish(new ConfirmTelegramBotEvent(userModel.AccountId, userModel.Code)); + return userModel; } - public async Task AddFinishUser(Update update) + public async Task AddFinishUser(Update update) { var message = update.Message?.Text; - var user = await _context.TelegramUser.FindAsync(update.Message.Chat.Id); - if (user.Operation != "check_code" || user.Code != message || user == null) + var user = _telegramBotRepository.GetUserTelegramByChatId(update.Message.Chat.Id); + var userModel = user.ToArray()[0]; + if (userModel.Operation != "check_code" || userModel.Code != message || user == null) { _context.Remove(user); await _context.SaveChangesAsync(); return null; } - user.Operation = "finish"; - user.IsRegistered = true; + userModel.Operation = "finish"; + userModel.IsRegistered = true; await _context.SaveChangesAsync(); - return user; + return userModel; } - public async Task UserByUpdate(Update update) - => await _context.TelegramUser.FindAsync(update.CallbackQuery == null ? update.Message.Chat.Id : update.CallbackQuery.Message.Chat.Id); + public async Task UserByUpdate(Update update) + => update.Message == null + ? _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id).Result + : _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result; - public async Task TelegramUserModelByStudentId(string studentId) + public async Task TelegramUserModelByStudentId(string studentId) => _context.TelegramUser.First(x => x.AccountId == studentId); + + public async Task AddTaskIdToSentSolution(long chatId, long taskId) + { + var user = await _context.TelegramUser.FindAsync(chatId); + /*user.TaskId = taskId;*/ + await _context.SaveChangesAsync(); + return user; + } public async Task DeleteUser(Update update) { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs index e3a04cbc1..c7639772c 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs @@ -4,6 +4,7 @@ using HwProj.SolutionsService.Client; using HwProj.TelegramBotService.API.Commands; using HwProj.TelegramBotService.API.Models; +using HwProj.TelegramBotService.API.Repositories; using HwProj.TelegramBotService.API.Service; using HwProj.Utils.Configuration; using Microsoft.AspNetCore.Builder; @@ -28,6 +29,7 @@ public void ConfigureServices(IServiceCollection services) var connectionString = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext(options => options.UseSqlServer(connectionString)); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json index d51d472f5..0b69a234b 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json @@ -24,5 +24,5 @@ "TelegramBot" : "http://localhost:5009" }, "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://8e76-92-42-26-35.ngrok.io/" + "Url" : "https://502f-92-42-26-35.ngrok.io/" } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs index a8895c19d..de362881c 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs @@ -1,11 +1,10 @@ using System.Threading.Tasks; -using HwProj.Models.Result; -using HwProj.TelegramBotService.API.Models; +using HwProj.Models.TelegramBotService; namespace HwProj.TelegramBotService.Client { public interface ITelegramBotServiceClient { - Task GetTelegramUser(string studentId); + Task GetTelegramUser(string studentId); } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs index 7f1f6f733..43611f278 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs @@ -2,8 +2,7 @@ using System.Net.Http; using System.Threading.Tasks; using HwProj.HttpUtils; -using HwProj.Models.Result; -using HwProj.TelegramBotService.API.Models; +using HwProj.Models.TelegramBotService; using Microsoft.Extensions.Configuration; namespace HwProj.TelegramBotService.Client @@ -19,14 +18,14 @@ public TelegramBotServiceClient(IHttpClientFactory clientFactory, IConfiguration _telegramBotUri = new Uri(configuration.GetSection("Services")["TelegramBot"]); } - public async Task GetTelegramUser(string studentId) + public async Task GetTelegramUser(string studentId) { using var httpRequest = new HttpRequestMessage( HttpMethod.Get, _telegramBotUri + $"api/TelegramBot/get/{studentId}"); var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); + return await response.DeserializeAsync(); } } } \ No newline at end of file diff --git a/hwproj.front/src/components/Profile.tsx b/hwproj.front/src/components/Profile.tsx index e79400d3f..82ba333f3 100644 --- a/hwproj.front/src/components/Profile.tsx +++ b/hwproj.front/src/components/Profile.tsx @@ -14,9 +14,7 @@ import parse from 'html-react-parser'; import {ChangeEvent, Component, FC, useEffect, useState} from "react"; import {Redirect} from "react-router-dom"; import {makeStyles} from "@material-ui/styles"; -import Image from 'material-ui-image' -import telegramLogo from './tlgm.png' -import "./Styles/telegram.css"; +import Button from "@material-ui/core/Button"; interface IProfileState { isLoaded: boolean; @@ -119,7 +117,7 @@ const Profile: FC> = (props) => { } if (profileState.isLoaded) { - const hrefLink = "https://t.me/HwProjBot?start=>" + accountState.email; + const hrefLink = "https://t.me/HwProjBot?start=>"; const fullName = accountState.middleName && accountState.surname ? accountState.name + ' ' + accountState.middleName + ' ' + accountState.surname : accountState.surname @@ -132,12 +130,14 @@ const Profile: FC> = (props) => { {fullName} - - - + {accountState.email} diff --git a/hwproj.front/src/components/Styles/telegram.css b/hwproj.front/src/components/Styles/telegram.css deleted file mode 100644 index a90cf303d..000000000 --- a/hwproj.front/src/components/Styles/telegram.css +++ /dev/null @@ -1,4 +0,0 @@ -.telegram { - height: 25px; - width: 25px; -} \ No newline at end of file diff --git a/hwproj.front/src/components/tlgm.png b/hwproj.front/src/components/tlgm.png deleted file mode 100644 index c73e64b2ed0ee6f2a149647c99a029cfcc332f5f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1248 zcmV<61Rwi}P)r)0J+fs zKx`8sP#8rB#5Mx}g|bcix9wZ$iKVKI`Zv{q^v1}>Vo(@a3^Lwgf19V$Be_u(gV<(< zz|v-hKyH*FklD--SW;EyUu#3@os{WA{{3hny;Bk)^$%(&2E>E~-X8|BS>+Tl^X(LmIXx-F6T8XtGdaY})l~zW&6-#xj0X%M9yCi)0 z0X%Mx(Nya$JnoFqP#1o%lXg<1lnTFt$H-}@njY{h(w)-*@2*RTkkf%G{9u1d;FfgP zF+?bY1vfpeAwt7W7h7;fw_AUaEbh1{52oHU|!p=otNUZDl5J?IFUg6nAz-4Xv&M!-`HiZCRaC=NA5?K*M17cD^C614{fUO~7%4@J zxS&3{goymSzhXTu$ldUYZ4^s(i{(gqJYqKjAGt<>tw3>PO@@fysB5T3QSfITUf4## zy1b%7G~%~=D=I{pV#E4KJ#D~(HDTlSFyKvCb4wQ91Zk)hh28|h0@8$)bBIda39ri8 z<5+q8r*ZW-&AtAQp^E?vjVuNW8;e0?RK;LnGXM}8WfUYfZ3u)$ z0|1H506=6EA+WHC5EvR2F}O15LcKNBJa8fOj;NW>rO}_U{NJ&m)dV3)MhOCmxj(%aVMQz2Hr$7X=UOy zJ@9%g|78q!eYwFXaQF8?pUm&R4P$&c4|->K^Kkyj!+je39R33S3D{Zj Date: Fri, 24 Dec 2021 22:52:42 +0300 Subject: [PATCH 11/19] clean code --- .../Commands/CommandNames.cs | 5 +- .../Commands/ErrorCommand.cs | 2 +- .../Commands/GetAllCourses.cs | 33 --------- .../Commands/SendSolution.cs | 70 ------------------- .../Commands/WaitSolution.cs | 40 ----------- .../Service/CommandService.cs | 2 + .../HwProj.TelegramBotService.API/Startup.cs | 1 - 7 files changed, 4 insertions(+), 149 deletions(-) delete mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs delete mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs delete mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitSolution.cs diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs index 0af4dc0d6..9ab6307fa 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs @@ -4,17 +4,14 @@ public static class CommandNames { public const string StartCommand = "/start"; public const string GetCourses = "/courses"; // /courses {courseId} - public const string GetAllCourses = "/courses_all"; // /courses_all {courseId} public const string GetHomeworks = "/homeworks"; // /homeworks {courseId} public const string GetTasks = "/task"; // /task {homeworksId} public const string GetTaskInfo = "/taskinfo"; // /taskinfo {taskId} public const string GetSolutionsFromTask = "/solutions"; // /solutions {taskId} public const string GetSolutionInfo = "/solutioninfo"; // /solutioninfo {solutionId} public const string GetStatistics = "/statistics"; // /statistics {courseId} - public const string SendSolution = "/send_solution"; public const string WaitCodeCommand = "wait_code"; public const string CheckCodeCommand = "check_code"; - public const string ErrorCommand = "error_response"; - public const string WaitSolution = "wait_solution"; + public const string ErrorCommand = "error_response"; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs index 1284752e6..6da8d4ce3 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs @@ -23,7 +23,7 @@ public override async Task ExecuteAsync(Update update) { var user = await _userService.UserByUpdate(update); - await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!\n Введите ваш e-mail на Hw-Proj2.0.1", ParseMode.Markdown); + await _botClient.SendTextMessageAsync(user.ChatId, "Повторите ещё раз!", ParseMode.Markdown); } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs deleted file mode 100644 index 96ff6481d..000000000 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetAllCourses.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Threading.Tasks; -using HwProj.CoursesService.Client; -using HwProj.TelegramBotService.API.Service; -using Telegram.Bot; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; -using Telegram.Bot.Types.ReplyMarkups; - -namespace HwProj.TelegramBotService.API.Commands -{ - public class GetAllCourses : Commands - { - private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; - private readonly ICoursesServiceClient _coursesServiceClient; - - public GetAllCourses(TelegramBot telegramBot, IUserService userService, ICoursesServiceClient coursesServiceClient) - { - _botClient = telegramBot.GetBot().Result; - _userService = userService; - _coursesServiceClient = coursesServiceClient; - } - - public override string Name => CommandNames.GetAllCourses; - - public override async Task ExecuteAsync(Update update) - { - var user = await _userService.UserByUpdate(update); - - await _botClient.SendTextMessageAsync(user.ChatId, "Повторите запрос снова!", ParseMode.Markdown); - } - } -} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs deleted file mode 100644 index 54b151300..000000000 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using HwProj.CoursesService.Client; -using HwProj.SolutionsService.API.Services; -using HwProj.SolutionsService.Client; -using HwProj.TelegramBotService.API.Service; -using Microsoft.AspNetCore.Builder; -using Telegram.Bot; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; -using Telegram.Bot.Types.ReplyMarkups; - -namespace HwProj.TelegramBotService.API.Commands -{ - public class SendSolution : Commands - { - private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; - private readonly ISolutionsService _solutionsServiceClient; - private readonly ICoursesServiceClient _coursesServiceClient; - - public SendSolution(TelegramBot telegramBot, IUserService userService, - ISolutionsService solutionsServiceClient, ICoursesServiceClient coursesServiceClient) - { - _botClient = telegramBot.GetBot().Result; - _userService = userService; - _solutionsServiceClient = solutionsServiceClient; - _coursesServiceClient = coursesServiceClient; - } - - public override string Name => CommandNames.SendSolution; - - public override async Task ExecuteAsync(Update update) - { - var user = await _userService.UserByUpdate(update); - /*if (user.TaskId == -1) - { - await _botClient.SendTextMessageAsync(user.ChatAspNetUsersId, "Попробуйте ещё раз.", - ParseMode.Markdown); - return; - }*/ - - var message = update.CallbackQuery.Data; - - var pullRequested = message.Split(' ')[0]; - var comment = message.Split(' ')[1]; - /*await _solutionsServiceClient.PostFromTelegramAsync(user.TaskId, pullRequested, comment, user.AccountId); - var task = _coursesServiceClient.GetTask(user.TaskId).Result; - var hw = _coursesServiceClient.GetHomework(task.HomeworkId).Result; - - var rows = new List(); - var cols = new List(); - cols.Add(GetButton($"Решения {task.Title}", $"/solutions {task.Id}")); - rows.Add(cols.ToArray()); - cols = new List(); - cols.Add(GetButton($"Отправить решение {task.Title}", $"/wait_solution {task.Id}")); - rows.Add(cols.ToArray()); - cols = new List(); - cols.Add(GetButton("Мои курсы", $"/courses")); - cols.Add(GetButton("Мои домашки", $"/homeworks {hw.CourseId}")); - cols.Add(GetButton("Мои задачи", $"/task {task.HomeworkId}")); - rows.Add(cols.ToArray()); - - var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray());*/ - - await _botClient.SendTextMessageAsync(user.ChatId, "Ваша задача отправлена.", - ParseMode.Markdown/*, replyMarkup:keyboardMarkup*/); - } - } -} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitSolution.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitSolution.cs deleted file mode 100644 index 0053d03a9..000000000 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitSolution.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Threading.Tasks; -using HwProj.SolutionsService.Client; -using HwProj.TelegramBotService.API.Service; -using Telegram.Bot; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; - -namespace HwProj.TelegramBotService.API.Commands -{ - public class WaitSolution: Commands - { - private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; - private readonly ISolutionsServiceClient _solutionsServiceClient; - - public WaitSolution(TelegramBot telegramBot, IUserService userService, - ISolutionsServiceClient solutionsServiceClient) - { - _botClient = telegramBot.GetBot().Result; - _userService = userService; - _solutionsServiceClient = solutionsServiceClient; - } - - public override string Name => CommandNames. WaitSolution; - - public override async Task ExecuteAsync(Update update) - { - var user = await _userService.UserByUpdate(update); - var message = update.CallbackQuery.Data; - var taskId = int.Parse(message.Split(' ')[1]); - - user = await _userService.AddTaskIdToSentSolution(update.CallbackQuery.Message.Chat.Id, taskId); - - await _botClient.SendTextMessageAsync(user.ChatId, "Введите ссылку на pull request и комментарий. " + - "\n Пример: ' <комментарий'", - ParseMode.Markdown); - } - } -} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs index 2ca28b9f1..ef78fe9ce 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs @@ -87,6 +87,8 @@ public async Task Execute(Update update) } } } + + await ExecuteCommand(CommandNames.ErrorCommand, update); } private async Task ExecuteCommand(string commandName, Update update) diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs index c7639772c..c2cb9b2b8 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs @@ -43,7 +43,6 @@ public void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); services.AddScoped(); - /*services.AddScoped();*/ services.AddHttpClient(); services.AddAuthServiceClient(); From f5365229749c8306b66f006c53982b9e34379042 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Fri, 24 Dec 2021 22:55:33 +0300 Subject: [PATCH 12/19] clean code --- .../Configuration/StartupExtensions.cs | 1 + .../HwProj.CoursesService.API/Startup.cs | 3 +- .../Services/ISolutionsService.cs | 2 - .../Services/SolutionsService.cs | 53 ------------------- 4 files changed, 2 insertions(+), 57 deletions(-) diff --git a/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs b/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs index a172a6b73..7290d133c 100644 --- a/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs +++ b/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs @@ -77,6 +77,7 @@ public static IServiceCollection ConfigureHwProjServices(this IServiceCollection } services.AddTransient(); + services.AddHttpContextAccessor(); return services; diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Startup.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Startup.cs index 09de9ccb9..21cf15178 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Startup.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Startup.cs @@ -41,8 +41,7 @@ public void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddEventBus(Configuration); - - /*services.AddHttpContextAccessor();*/ + services.AddHttpClient(); services.AddAuthServiceClient(); diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs index c94898927..137c88d3f 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs @@ -16,8 +16,6 @@ public interface ISolutionsService Task PostOrUpdateAsync(long taskId, Solution solution); - Task PostFromTelegramAsync(long taskId, string githubUrl, string comment, string studentId); - Task RateSolutionAsync(long solutionId, int newRating, string lecturerComment); Task DeleteSolutionAsync(long solutionId); diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs index 303f1925f..17a3d29ef 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs @@ -84,59 +84,6 @@ public async Task PostOrUpdateAsync(long taskId, Solution solution) return solution.Id; } - public async Task PostFromTelegramAsync(long taskId, string githubUrl, string comment, - string studentId) - { - var task1 = _coursesServiceClient.GetTask(taskId); - var taskModel1 = _mapper.Map(task1); - var homework1 = await _coursesServiceClient.GetHomework(taskModel1.HomeworkId); - var courseId = homework1.CourseId; - var group = await _coursesServiceClient.GetCourseGroupsById(courseId, studentId); - long? groupId = null; - if (group.Tasks.Contains(taskId)) - { - groupId = group.Id; - } - var solution = new Solution{ - - GithubUrl = githubUrl, - Comment = comment, - State = SolutionState.Posted, - StudentId = studentId, - GroupId = groupId, - TaskId = taskId, - PublicationDate = DateTime.Now, - LecturerComment = null}; - var allSolutionsForTask= await GetTaskSolutionsFromStudentAsync(taskId, solution.StudentId); - var currentSolution = allSolutionsForTask.FirstOrDefault(s => s.Id == solution.Id); - var solutionModel = _mapper.Map(solution); - var task = await _coursesServiceClient.GetTask(solution.TaskId); - var taskModel = _mapper.Map(task); - var homework = await _coursesServiceClient.GetHomework(task.HomeworkId); - var courses = await _coursesServiceClient.GetCourseById(homework.CourseId, solution.StudentId); - var student = await _authServiceClient.GetAccountData((solutionModel.StudentId)); - var studentModel = _mapper.Map(student); - _eventBus.Publish(new StudentPassTaskEvent(courses, solutionModel, studentModel, taskModel)); - - if (currentSolution == null) - { - solution.TaskId = taskId; - var id = await _solutionsRepository.AddAsync(solution); - return id; - } - - await _solutionsRepository.UpdateAsync(currentSolution.Id, s => new Solution() - { - State = SolutionState.Rated, - Comment = solution.Comment, - GithubUrl = solution.GithubUrl, - PublicationDate = solution.PublicationDate, - } - ); - - return solution.Id; - } - public async Task RateSolutionAsync(long solutionId, int newRating, string lecturerComment) { var solution = await _solutionsRepository.GetAsync(solutionId); From 11dc41541e5a2792799a606f2732978890b8c568 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Mon, 4 Apr 2022 12:09:06 +0300 Subject: [PATCH 13/19] swap url to check working --- .../appsettings.json | 2 +- .../Commands/CheckCodeCommand.cs | 1 - .../Commands/GetTaskInfo.cs | 1 - .../Commands/StartCommand.cs | 1 - .../Models/TelegramUserModel.cs | 23 ------------------- .../Service/IUserService.cs | 2 +- .../Service/UserService.cs | 14 +++++------ .../appsettings.json | 2 +- 8 files changed, 10 insertions(+), 36 deletions(-) delete mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json index a5d8cfc43..5c4e31a19 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json @@ -32,6 +32,6 @@ }, "Telegram": { "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://502f-92-42-26-35.ngrok.io/" + "Url" : "https://8961-92-42-26-35.ngrok.io/" } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs index 17a79b164..50e4afa8f 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs @@ -2,7 +2,6 @@ using HwProj.TelegramBotService.API.Service; using Telegram.Bot; using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.TelegramBotService.API.Commands diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs index 64c69415e..1352f5c84 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading.Tasks; using HwProj.CoursesService.Client; -using HwProj.Models.CoursesService.ViewModels; using HwProj.TelegramBotService.API.Service; using Telegram.Bot; using Telegram.Bot.Types; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs index b5137cf74..017165969 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs @@ -3,7 +3,6 @@ using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -using Telegram.Bot.Types.ReplyMarkups; namespace HwProj.TelegramBotService.API.Commands { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs deleted file mode 100644 index bbffe50f7..000000000 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Models/TelegramUserModel.cs +++ /dev/null @@ -1,23 +0,0 @@ -/*using HwProj.Repositories; - -namespace HwProj.TelegramBotService.API.Models -{ - public class TelegramUserModel - { - /*public long Id { get; set; } - - public long ChatId { get; set; } - - public string AccountId { get; set; } - - public bool IsLecture { get; set; } - - public bool IsRegistered { get; set; } - - public string Code { get; set; } - - public string Operation { get; set; }#1# - - /*public long TaskId { get; set; }#1# - } -}*/ \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs index f0695d1c4..3d74ac6cd 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs @@ -17,7 +17,7 @@ public interface IUserService Task TelegramUserModelByStudentId(string studentId); - Task AddTaskIdToSentSolution(long chatId, long taskId); + /*Task AddTaskIdToSentSolution(long chatId, long taskId);*/ Task DeleteUser(Update update); } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs index a920b3cf1..50837b5b7 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs @@ -20,7 +20,6 @@ public class UserService : IUserService private readonly TelegramBotContext _context; private readonly IAuthServiceClient _authClient; private readonly IEventBus _eventBus; - private readonly IMapper _mapper; public UserService(TelegramBotContext context, IAuthServiceClient authClient, IEventBus eventBus, ITelegramBotRepository telegramBotRepository, IMapper mapper) { @@ -28,7 +27,6 @@ public UserService(TelegramBotContext context, IAuthServiceClient authClient, IE _authClient = authClient; _eventBus = eventBus; _telegramBotRepository = telegramBotRepository; - _mapper = mapper; } public async Task CreateUser(Update update) @@ -40,6 +38,8 @@ public async Task CreateUser(Update update) code.Append(chars[random.Next(chars.Length)]); code.Append(chars[random.Next(chars.Length)]); code.Append(chars[random.Next(chars.Length)]); + code.Append(chars[random.Next(chars.Length)]); + code.Append(chars[random.Next(chars.Length)]); var newUser = new UserTelegram { ChatId = update.Message.Chat.Id, @@ -48,7 +48,6 @@ public async Task CreateUser(Update update) IsRegistered = false, Code = code.ToString(), Operation = "wait_code", - /*TaskId = -1*/ }; var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == newUser.ChatId); @@ -108,14 +107,15 @@ public async Task UserByUpdate(Update update) public async Task TelegramUserModelByStudentId(string studentId) => _context.TelegramUser.First(x => x.AccountId == studentId); - - public async Task AddTaskIdToSentSolution(long chatId, long taskId) + + // not write metod + /*public async Task AddTaskIdToSentSolution(long chatId, long taskId) { var user = await _context.TelegramUser.FindAsync(chatId); - /*user.TaskId = taskId;*/ + /*user.TaskId = taskId;#1# await _context.SaveChangesAsync(); return user; - } + }*/ public async Task DeleteUser(Update update) { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json index 0b69a234b..10426119e 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json @@ -24,5 +24,5 @@ "TelegramBot" : "http://localhost:5009" }, "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://502f-92-42-26-35.ngrok.io/" + "Url" : "https://8961-92-42-26-35.ngrok.io/" } \ No newline at end of file From 8e5dfcaa2ec86597f36e513650229dd063a1c598 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Sat, 16 Apr 2022 00:00:58 +0300 Subject: [PATCH 14/19] add send solution fix bug with json add method to send notification to tg with keyboard and without --- .../TelegramBotService/UserTelegram.cs | 8 ++- .../EventHandlers/EditProfileEventHandler.cs | 2 +- .../InviteLecturerEventHandler.cs | 2 +- .../LecturerAcceptToCourseEventHandler.cs | 2 +- .../LecturerRejectToCourseEventHandler.cs | 2 +- .../EventHandlers/NewCourseMateHandler.cs | 2 +- .../EventHandlers/NewHomeworkEventHandler.cs | 2 +- .../EventHandlers/RateEventHandler.cs | 2 +- .../EventHandlers/RegisterEventHandler.cs | 1 - .../StudentPassTaskEventHandler.cs | 2 +- .../UpdateHomeworkEventHandler.cs | 2 +- .../UpdateTaskMaxRatingEventHandler.cs | 2 +- .../Services/INotificationsService.cs | 3 +- .../Services/NotificationsService.cs | 31 ++++++---- .../appsettings.json | 2 +- .../Commands/CommandNames.cs | 2 + .../Commands/GetTaskInfo.cs | 6 +- .../Commands/SendSolution.cs | 47 ++++++++++++++ .../Commands/StartCommand.cs | 2 +- .../Commands/WaitCodeCommand.cs | 5 +- .../Commands/WaitPullRequest.cs | 36 +++++++++++ .../Controllers/TelegramBotController.cs | 9 ++- .../Repositories/ITelegramBotRepository.cs | 1 + .../Repositories/TelegramBotRepository.cs | 5 ++ .../Service/CommandService.cs | 33 ++++++---- .../Service/IUserService.cs | 4 +- .../Service/UserService.cs | 62 ++++++++++++------- .../HwProj.TelegramBotService.API/Startup.cs | 2 + .../appsettings.json | 2 +- .../ITelegramBotServiceClient.cs | 1 + .../TelegramBotServiceClient.cs | 18 ++++++ 31 files changed, 229 insertions(+), 71 deletions(-) create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitPullRequest.cs diff --git a/HwProj.Common/HwProj.Models/TelegramBotService/UserTelegram.cs b/HwProj.Common/HwProj.Models/TelegramBotService/UserTelegram.cs index 4622678c8..ba52b41f5 100644 --- a/HwProj.Common/HwProj.Models/TelegramBotService/UserTelegram.cs +++ b/HwProj.Common/HwProj.Models/TelegramBotService/UserTelegram.cs @@ -14,8 +14,12 @@ public class UserTelegram : IEntity public bool IsRegistered { get; set; } - public string Code { get; set; } + public string? Code { get; set; } - public string Operation { get; set; } + public long? TaskIdToSend { get; set; } + + public string? GitHubUrl { get; set; } + + public string? Operation { get; set; } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/EditProfileEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/EditProfileEventHandler.cs index 4e7bc9ed5..a1d5535bb 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/EditProfileEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/EditProfileEventHandler.cs @@ -43,7 +43,7 @@ public async Task HandleAsync(EditProfileEvent @event) var studentModel = _mapper.Map(studentAccount); await _notificationsService.SendEmailAsync(notification, studentModel.Email, "Редактирование профиля"); - await _notificationsService.SendTelegramMessageAsync(notification, null); + await _notificationsService.SendTelegramMessageAsync(notification); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs index 5ffbc28df..714ed29da 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs @@ -43,7 +43,7 @@ public async Task HandleAsync(InviteLecturerEvent @event) var studentModel = _mapper.Map(studentAccount); await _notificationsService.SendEmailAsync(notification, studentModel.Email, "HwProj"); - await _notificationsService.SendTelegramMessageAsync(notification, null); + await _notificationsService.SendTelegramMessageAsync(notification); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs index 797264275..af1c87f7a 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs @@ -39,7 +39,7 @@ public async Task HandleAsync(LecturerAcceptToCourseEvent @event) await _notificationsService.SendEmailAsync(notification, student.Email, "HwProj"); notification.Body = $"Вас приняли на курс {@event.CourseName}."; - await _notificationsService.SendTelegramMessageAsync(notification, null); + await _notificationsService.SendTelegramMessageAsync(notification); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs index b6ee37f02..86e90bcab 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs @@ -39,7 +39,7 @@ public async Task HandleAsync(LecturerRejectToCourseEvent @event) await _notificationsService.SendEmailAsync(notification, student.Email, "HwProj"); notification.Body = $"Вас не приняли на курс {@event.CourseName}."; - await _notificationsService.SendTelegramMessageAsync(notification, null); + await _notificationsService.SendTelegramMessageAsync(notification); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs index c927c04b6..a1a978440 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs @@ -45,7 +45,7 @@ public async Task HandleAsync(NewCourseMateEvent @event) await _notificationsService.SendEmailAsync(notification, mentor.Email, "HwProj"); notification.Body = $"Пользователь {user.Name} {user.Surname} подал заявку на вступление в курс {@event.CourseName}."; - await _notificationsService.SendTelegramMessageAsync(notification, null); + await _notificationsService.SendTelegramMessageAsync(notification); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs index f949feb1a..bd43c5484 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs @@ -53,7 +53,7 @@ public async Task HandleAsync(NewHomeworkEvent @event) Text = $"{@event.Homework}", CallbackData = $"/homeworks {@event.Course.Id}" }); - await _notificationsService.SendTelegramMessageAsync(notification, inlineKeyboard); + await _notificationsService.SendTelegramMessageWithKeyboardAsync(notification, inlineKeyboard); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs index c45af840a..c82fd42ce 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs @@ -45,7 +45,7 @@ public async Task HandleAsync(RateEvent @event) Text = $"{@event.Task.Title}", CallbackData = $"/solutioninfo {@event.SolutionId}" }); - await _notificationsService.SendTelegramMessageAsync(notification, inlineKeyboard); + await _notificationsService.SendTelegramMessageWithKeyboardAsync(notification, inlineKeyboard); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs index 9cf6477dd..11b66f3a7 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs @@ -32,7 +32,6 @@ public async Task HandleAsync(StudentRegisterEvent @event) }; await _notificationRepository.AddAsync(notification); await _notificationsService.SendEmailAsync(notification, @event.Email, "HwProj"); - await _notificationsService.SendTelegramMessageAsync(notification, null); } } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs index 0beaf3985..1b2856141 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs @@ -44,7 +44,7 @@ public async Task HandleAsync(StudentPassTaskEvent @event) await _notificationsService.SendEmailAsync(notification, mentor.Email, "HwProj"); notification.Body = $"{@event.Student.Name} {@event.Student.Surname} добавил новое решение задачи {@event.Task.Title} из курса {@event.Course.Name}."; - await _notificationsService.SendTelegramMessageAsync(notification, null); + await _notificationsService.SendTelegramMessageAsync(notification); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs index 0f8512f0a..e3eb16622 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs @@ -48,7 +48,7 @@ public async Task HandleAsync(UpdateHomeworkEvent @event) Text = $"{@event.Homework.Title}", CallbackData = $"/task {@event.Homework.Id}" }); - await _notificationsService.SendTelegramMessageAsync(notification, inlineKeyboard); + await _notificationsService.SendTelegramMessageWithKeyboardAsync(notification, inlineKeyboard); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs index 822de9399..d233881d0 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs @@ -52,7 +52,7 @@ public async Task HandleAsync(UpdateTaskMaxRatingEvent @event) Text = $"{@event.Task.Title}", CallbackData = $"/taskinfo {@event.Task.Id}" }); - await _notificationsService.SendTelegramMessageAsync(notification, inlineKeyboard); + await _notificationsService.SendTelegramMessageWithKeyboardAsync(notification, inlineKeyboard); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs index 3502a77cc..2a0ff886d 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/INotificationsService.cs @@ -10,6 +10,7 @@ public interface INotificationsService Task GetAsync(string userId, NotificationFilter filter = null); Task MarkAsSeenAsync(string userId, long[] notificationIds); Task SendEmailAsync(Notification notification, string email, string topic); - Task SendTelegramMessageAsync(Notification notification, InlineKeyboardMarkup inlineKeyboard); + Task SendTelegramMessageAsync(Notification notification); + Task SendTelegramMessageWithKeyboardAsync(Notification notification, InlineKeyboardMarkup inlineKeyboard); } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs index 1a4b6e8b9..a7124655b 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System; +using System.Linq; using System.Threading.Tasks; using AutoMapper; using HwProj.Models.NotificationsService; @@ -74,20 +75,24 @@ public async Task SendEmailAsync(Notification notification, string email, string await _client.DisconnectAsync(true); } - - public async Task SendTelegramMessageAsync(Notification notification, InlineKeyboardMarkup inlineKeyboard) + + public async Task SendTelegramMessageAsync(Notification notification) + { + var checkUser = await _telegramBotServiceClient.CheckUser(notification.Owner); + if (checkUser) + { + var user = await _telegramBotServiceClient.GetTelegramUser(notification.Owner); + await _botClient.SendTextMessageAsync(user.ChatId, notification.Body, ParseMode.Markdown); + } + } + + public async Task SendTelegramMessageWithKeyboardAsync(Notification notification, InlineKeyboardMarkup inlineKeyboard) { - var user = await _telegramBotServiceClient.GetTelegramUser(notification.Owner); - if (user != null) + var checkUser = await _telegramBotServiceClient.CheckUser(notification.Owner); + if (checkUser) { - if (inlineKeyboard == null) - { - await _botClient.SendTextMessageAsync(user.ChatId, notification.Body, ParseMode.Markdown); - } - else - { - await _botClient.SendTextMessageAsync(user.ChatId, notification.Body, ParseMode.Markdown, replyMarkup:inlineKeyboard); - } + var user = await _telegramBotServiceClient.GetTelegramUser(notification.Owner); + await _botClient.SendTextMessageAsync(user.ChatId, notification.Body, ParseMode.Markdown, replyMarkup:inlineKeyboard); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json index 5c4e31a19..c26ae1d43 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json @@ -32,6 +32,6 @@ }, "Telegram": { "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://8961-92-42-26-35.ngrok.io/" + "Url" : "https://6ab7-92-42-26-35.ngrok.io/" } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs index 9ab6307fa..3895a50a3 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs @@ -13,5 +13,7 @@ public static class CommandNames public const string WaitCodeCommand = "wait_code"; public const string CheckCodeCommand = "check_code"; public const string ErrorCommand = "error_response"; + public const string WaitPullRequest = "wait_pull_request"; + public const string SendSolution = "send_solution"; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs index 1352f5c84..3fdb77c7b 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs @@ -39,13 +39,13 @@ public override async Task ExecuteAsync(Update update) cols.Add(GetButton($"Решения {task.Title}", $"/solutions {task.Id}")); rows.Add(cols.ToArray()); cols = new List(); - cols.Add(GetButton($"Отправить решение {task.Title}", $"/wait_solution {task.Id}")); - rows.Add(cols.ToArray()); - cols = new List(); cols.Add(GetButton("Мои курсы", $"/courses")); cols.Add(GetButton("Мои домашки", $"/homeworks {hw.CourseId}")); cols.Add(GetButton("Мои задачи", $"/task {task.HomeworkId}")); rows.Add(cols.ToArray()); + cols = new List(); + cols.Add(GetButton($"Отправить решение {task.Title}", $"wait_pull_request {task.Id}")); + rows.Add(cols.ToArray()); var keyboardMarkup = new InlineKeyboardMarkup(rows.ToArray()); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs new file mode 100644 index 000000000..6420bb490 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs @@ -0,0 +1,47 @@ +using System; +using System.Threading.Tasks; +using HwProj.Models.SolutionsService; +using HwProj.SolutionsService.Client; +using HwProj.TelegramBotService.API.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + +namespace HwProj.TelegramBotService.API.Commands +{ + public class SendSolution: Commands + { + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + private readonly ISolutionsServiceClient _solutionsService; + + public SendSolution(TelegramBot telegramBot, IUserService userService, ISolutionsServiceClient solutionsService) + { + _botClient = telegramBot.GetBot().Result; + _userService = userService; + _solutionsService = solutionsService; + } + + public override string Name => CommandNames.SendSolution; + + public override async Task ExecuteAsync(Update update) + { + var user = await _userService.UserByUpdate(update); + var message = update.Message.Text; + + var solutionModel = new SolutionViewModel + { + GithubUrl = message, + Comment = "", + StudentId = user.AccountId, + PublicationDate = DateTime.Now, + LecturerComment = "" + }; + + await _solutionsService.PostSolution(solutionModel, Convert.ToInt64(user.TaskIdToSend)); + + await _botClient.SendTextMessageAsync(user.ChatId, "Решение отправлено.", + ParseMode.Markdown); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs index 017165969..99b8d6041 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs @@ -25,7 +25,7 @@ public override async Task ExecuteAsync(Update update) var user = await _userService.CreateUser(update); - await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!\n Введите ваш e-mail на Hw-Proj2.0.1", + await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!\nВведите ваш e-mail на Hw-Proj2.0.1", ParseMode.Markdown); } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs index 9b8900683..522812ae7 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs @@ -25,8 +25,9 @@ public override async Task ExecuteAsync(Update update) if (user == null) { - await _botClient.SendTextMessageAsync(update.Message.Chat.Id, "E-mail не зарегистрирован на Hw-Proj2.0.1." + - "\nВведите /start", ParseMode.Markdown); + await _botClient.SendTextMessageAsync(update.Message.Chat.Id, + "E-mail не зарегистрирован на Hw-Proj2.0.1." + + "\nВведите /start", ParseMode.Markdown); } await _botClient.SendTextMessageAsync(user.ChatId, "Ваш код отправлен.\nВведите его:", ParseMode.Markdown); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitPullRequest.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitPullRequest.cs new file mode 100644 index 000000000..397a10c40 --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitPullRequest.cs @@ -0,0 +1,36 @@ +using System; +using System.Threading.Tasks; +using HwProj.Models.TelegramBotService; +using HwProj.SolutionsService.Client; +using HwProj.TelegramBotService.API.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + +namespace HwProj.TelegramBotService.API.Commands +{ + public class WaitPullRequest : Commands + { + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + + public WaitPullRequest(TelegramBot telegramBot, IUserService userService) + { + _botClient = telegramBot.GetBot().Result; + _userService = userService; + } + + public override string Name => CommandNames.WaitPullRequest; + + public override async Task ExecuteAsync(Update update) + { + var message = update.CallbackQuery.Data; + var text = message.Split(' '); + + var user = await _userService.AddTaskIdAndWaitPullRequest(update, Int64.Parse(text[1])); + + await _botClient.SendTextMessageAsync(user.ChatId, "Отправьте ссылку на pull request.", + ParseMode.Markdown); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs index 27670048a..28dd59652 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs @@ -42,8 +42,15 @@ public async Task Update(Update update) return Ok(); } + [HttpGet("check/{studentId}")] + public async Task CheckUserTelegram(string studentId) + { + var response = await _userService.CheckTelegramUserModelByStudentId(studentId); + return Ok(response); + } + [HttpGet("get/{studentId}")] - public async Task GetUser(string studentId) + public async Task GetUserTelegram(string studentId) { return await _userService.TelegramUserModelByStudentId(studentId); } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs index ff99752bd..06329d558 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs @@ -8,5 +8,6 @@ namespace HwProj.TelegramBotService.API.Repositories public interface ITelegramBotRepository : ICrudRepository { IQueryable GetUserTelegramByChatId(long chatId); + IQueryable GetChatIdTelegramByAccountId(string accountId); } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs index 96557ca17..ae07fd66a 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs @@ -18,5 +18,10 @@ public IQueryable GetUserTelegramByChatId(long chatId) { return Context.Set().Where(h => h.ChatId == chatId); } + + public IQueryable GetChatIdTelegramByAccountId(string accountId) + { + return Context.Set().Where(h => h.AccountId == accountId); + } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs index ef78fe9ce..9df56fc8a 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs @@ -42,19 +42,25 @@ public async Task Execute(Update update) await ExecuteCommand(CommandNames.GetCourses, update); return; } - var userWantRegister = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result; - if (userWantRegister.Operation == "wait_code" || userWantRegister.Operation == "check_code") + + var user = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result; + if (user.Operation is "wait_code" or "check_code") { - switch (userWantRegister.Operation) + switch (user.Operation) { case "wait_code": await ExecuteCommand(CommandNames.WaitCodeCommand, update); - break; + return; case "check_code": await ExecuteCommand(CommandNames.CheckCodeCommand, update); - break; + return; } } + if (user.Operation == "wait_pull_request") + { + await ExecuteCommand(CommandNames.SendSolution, update); + return; + } } else if (update.Type == UpdateType.CallbackQuery) { @@ -65,25 +71,28 @@ public async Task Execute(Update update) { case "/courses": await ExecuteCommand(CommandNames.GetCourses, update); - break; + return; case "/homeworks": await ExecuteCommand(CommandNames.GetHomeworks, update); - break; + return; case "/statistics": await ExecuteCommand(CommandNames.GetStatistics, update); - break; + return; case "/task": await ExecuteCommand(CommandNames.GetTasks, update); - break; + return; case "/taskinfo": await ExecuteCommand(CommandNames.GetTaskInfo, update); - break; + return; case "/solutions": await ExecuteCommand(CommandNames.GetSolutionsFromTask, update); - break; + return; case "/solutioninfo": await ExecuteCommand(CommandNames.GetSolutionInfo, update); - break; + return; + case "wait_pull_request": + await ExecuteCommand(CommandNames.WaitPullRequest, update); + return; } } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs index 3d74ac6cd..39f953b3c 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs @@ -15,9 +15,11 @@ public interface IUserService Task UserByUpdate(Update update); + Task CheckTelegramUserModelByStudentId(string studentId); Task TelegramUserModelByStudentId(string studentId); + Task GetChatIdByStudentId(string studentId); - /*Task AddTaskIdToSentSolution(long chatId, long taskId);*/ + Task AddTaskIdAndWaitPullRequest(Update update, long taskId); Task DeleteUser(Update update); } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs index 50837b5b7..53e91091f 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs @@ -21,14 +21,15 @@ public class UserService : IUserService private readonly IAuthServiceClient _authClient; private readonly IEventBus _eventBus; - public UserService(TelegramBotContext context, IAuthServiceClient authClient, IEventBus eventBus, ITelegramBotRepository telegramBotRepository, IMapper mapper) + public UserService(TelegramBotContext context, IAuthServiceClient authClient, IEventBus eventBus, + ITelegramBotRepository telegramBotRepository, IMapper mapper) { _context = context; _authClient = authClient; _eventBus = eventBus; _telegramBotRepository = telegramBotRepository; } - + public async Task CreateUser(Update update) { var random = new Random(); @@ -43,38 +44,39 @@ public async Task CreateUser(Update update) var newUser = new UserTelegram { ChatId = update.Message.Chat.Id, - AccountId = null, + AccountId = null!, IsLecture = false, IsRegistered = false, Code = code.ToString(), Operation = "wait_code", }; var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == newUser.ChatId); - + if (user != null) { return user; } - + var result = await _context.TelegramUser.AddAsync(newUser); await _context.SaveChangesAsync(); - + return result.Entity; } - + public async Task AddEmailToUser(Update update) { var message = update.Message?.Text; - var user = _telegramBotRepository.GetUserTelegramByChatId(update.Message.Chat.Id); + var user =_telegramBotRepository.GetUserTelegramByChatId(update.Message.Chat.Id); var userModel = user.ToArray()[0]; if (userModel.Operation != "wait_code" || user == null) - { + { _context.Remove(userModel); await _context.SaveChangesAsync(); return null; } - var accountId = _authClient.FindByEmailAsync(message).Result; - var studentModel = _authClient.GetAccountData(accountId).Result; + + var accountId = await _authClient.FindByEmailAsync(message); + var studentModel = await _authClient.GetAccountData(accountId); userModel.Operation = "check_code"; userModel.AccountId = accountId; userModel.IsLecture = studentModel.Role == "Lecture"; @@ -89,11 +91,12 @@ public async Task AddFinishUser(Update update) var user = _telegramBotRepository.GetUserTelegramByChatId(update.Message.Chat.Id); var userModel = user.ToArray()[0]; if (userModel.Operation != "check_code" || userModel.Code != message || user == null) - { + { _context.Remove(user); await _context.SaveChangesAsync(); return null; } + userModel.Operation = "finish"; userModel.IsRegistered = true; await _context.SaveChangesAsync(); @@ -102,21 +105,36 @@ public async Task AddFinishUser(Update update) public async Task UserByUpdate(Update update) => update.Message == null - ? _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id).Result + ? _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id) + .Result : _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result; + public async Task CheckTelegramUserModelByStudentId(string studentId) + { + var user = await _telegramBotRepository.FindAsync(cm => cm.AccountId == studentId).ConfigureAwait(false); + return user != null; + } + public async Task TelegramUserModelByStudentId(string studentId) - => _context.TelegramUser.First(x => x.AccountId == studentId); - - // not write metod - /*public async Task AddTaskIdToSentSolution(long chatId, long taskId) + => await _telegramBotRepository.FindAsync(cm => cm.AccountId == studentId); + + public async Task GetChatIdByStudentId(string studentId) + { + var user = await _telegramBotRepository.FindAsync(cm => cm.AccountId == studentId); + return user.ChatId; + } + + + public async Task AddTaskIdAndWaitPullRequest(Update update, long taskId) { - var user = await _context.TelegramUser.FindAsync(chatId); - /*user.TaskId = taskId;#1# + var user = _telegramBotRepository.GetUserTelegramByChatId(update.CallbackQuery.Message.Chat.Id).ToArray()[0]; + var userModel = await _telegramBotRepository.FindAsync(cm => cm.ChatId == update.CallbackQuery.Message.Chat.Id).ConfigureAwait(false); + user.Operation = "wait_pull_request"; + user.TaskIdToSend = taskId; await _context.SaveChangesAsync(); return user; - }*/ - + } + public async Task DeleteUser(Update update) { var user1 = await _context.TelegramUser.FindAsync(update.Message.Chat.Id); @@ -124,7 +142,7 @@ public async Task DeleteUser(Update update) { var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id); _context.Remove(user); - await _context.SaveChangesAsync(); + await _context.SaveChangesAsync(); } } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs index c2cb9b2b8..bbf8fb2f4 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs @@ -41,6 +41,8 @@ public void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json index 10426119e..496656437 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json @@ -24,5 +24,5 @@ "TelegramBot" : "http://localhost:5009" }, "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://8961-92-42-26-35.ngrok.io/" + "Url" : "https://6ab7-92-42-26-35.ngrok.io/" } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs index de362881c..0d3ebcb2c 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs @@ -5,6 +5,7 @@ namespace HwProj.TelegramBotService.Client { public interface ITelegramBotServiceClient { + Task CheckUser(string studentId); Task GetTelegramUser(string studentId); } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs index 43611f278..6e4890bd5 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs @@ -1,9 +1,11 @@ using System; using System.Net.Http; +using System.Text; using System.Threading.Tasks; using HwProj.HttpUtils; using HwProj.Models.TelegramBotService; using Microsoft.Extensions.Configuration; +using Newtonsoft.Json; namespace HwProj.TelegramBotService.Client { @@ -18,6 +20,22 @@ public TelegramBotServiceClient(IHttpClientFactory clientFactory, IConfiguration _telegramBotUri = new Uri(configuration.GetSection("Services")["TelegramBot"]); } + public async Task CheckUser(string studentId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _telegramBotUri + $"api/TelegramBot/check/{studentId}") + { + Content = new StringContent( + JsonConvert.SerializeObject(studentId), + Encoding.UTF8, + "application/json") + }; + + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } + public async Task GetTelegramUser(string studentId) { using var httpRequest = new HttpRequestMessage( From b523e493c24492ea8bf25dce8c226b7dbfa3df18 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Fri, 6 May 2022 14:50:15 +0300 Subject: [PATCH 15/19] fix bug with send solution --- .../TelegramBotService/UserTelegram.cs | 2 + .../Services/NotificationsService.cs | 4 +- .../appsettings.json | 2 +- .../Commands/CommandNames.cs | 1 + .../Commands/SaveUrlAndWaitComment.cs | 34 +++++++++++++++ .../Commands/SendSolution.cs | 4 +- .../Controllers/TelegramBotController.cs | 5 ++- .../Repositories/ITelegramBotRepository.cs | 1 - .../Repositories/TelegramBotRepository.cs | 5 --- .../Service/CommandService.cs | 28 ++++++------ .../Service/IUserService.cs | 10 +---- .../Service/UserService.cs | 43 +++++++++++-------- .../HwProj.TelegramBotService.API/Startup.cs | 1 + .../appsettings.json | 2 +- .../ITelegramBotServiceClient.cs | 2 +- .../TelegramBotServiceClient.cs | 4 +- 16 files changed, 90 insertions(+), 58 deletions(-) create mode 100644 HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SaveUrlAndWaitComment.cs diff --git a/HwProj.Common/HwProj.Models/TelegramBotService/UserTelegram.cs b/HwProj.Common/HwProj.Models/TelegramBotService/UserTelegram.cs index ba52b41f5..37534120c 100644 --- a/HwProj.Common/HwProj.Models/TelegramBotService/UserTelegram.cs +++ b/HwProj.Common/HwProj.Models/TelegramBotService/UserTelegram.cs @@ -16,6 +16,8 @@ public class UserTelegram : IEntity public string? Code { get; set; } + public string? Comment { get; set; } + public long? TaskIdToSend { get; set; } public string? GitHubUrl { get; set; } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs index a7124655b..81ee20960 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs @@ -82,7 +82,7 @@ public async Task SendTelegramMessageAsync(Notification notification) if (checkUser) { var user = await _telegramBotServiceClient.GetTelegramUser(notification.Owner); - await _botClient.SendTextMessageAsync(user.ChatId, notification.Body, ParseMode.Markdown); + await _botClient.SendTextMessageAsync(user, notification.Body, ParseMode.Markdown); } } @@ -92,7 +92,7 @@ public async Task SendTelegramMessageWithKeyboardAsync(Notification notification if (checkUser) { var user = await _telegramBotServiceClient.GetTelegramUser(notification.Owner); - await _botClient.SendTextMessageAsync(user.ChatId, notification.Body, ParseMode.Markdown, replyMarkup:inlineKeyboard); + await _botClient.SendTextMessageAsync(user, notification.Body, ParseMode.Markdown, replyMarkup:inlineKeyboard); } } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json index c26ae1d43..e85d11881 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json @@ -32,6 +32,6 @@ }, "Telegram": { "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://6ab7-92-42-26-35.ngrok.io/" + "Url" : "https://c189-92-42-26-35.ngrok.io/" } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs index 3895a50a3..5a1ae8f43 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CommandNames.cs @@ -15,5 +15,6 @@ public static class CommandNames public const string ErrorCommand = "error_response"; public const string WaitPullRequest = "wait_pull_request"; public const string SendSolution = "send_solution"; + public const string SaveUrlAndWaitComment = "wait_comment"; } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SaveUrlAndWaitComment.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SaveUrlAndWaitComment.cs new file mode 100644 index 000000000..66316c45d --- /dev/null +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SaveUrlAndWaitComment.cs @@ -0,0 +1,34 @@ +using System; +using System.Threading.Tasks; +using HwProj.TelegramBotService.API.Service; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + +namespace HwProj.TelegramBotService.API.Commands +{ + public class SaveUrlAndWaitComment : Commands + { + private readonly TelegramBotClient _botClient; + private readonly IUserService _userService; + + public SaveUrlAndWaitComment(TelegramBot telegramBot, IUserService userService) + { + _botClient = telegramBot.GetBot().Result; + _userService = userService; + } + + public override string Name => CommandNames.SaveUrlAndWaitComment; + + public override async Task ExecuteAsync(Update update) + { + var message = update.Message.Text; + + + var user = await _userService.AddGitHubUrlToTask(update, message); + + await _botClient.SendTextMessageAsync(user.ChatId, "Добавьте комментарий к решению.", + ParseMode.Markdown); + } + } +} \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs index 6420bb490..9814ce42b 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs @@ -31,8 +31,8 @@ public override async Task ExecuteAsync(Update update) var solutionModel = new SolutionViewModel { - GithubUrl = message, - Comment = "", + GithubUrl = user.GitHubUrl, + Comment = message, StudentId = user.AccountId, PublicationDate = DateTime.Now, LecturerComment = "" diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs index 28dd59652..82fdef7b6 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs @@ -50,9 +50,10 @@ public async Task CheckUserTelegram(string studentId) } [HttpGet("get/{studentId}")] - public async Task GetUserTelegram(string studentId) + public async Task GetUserTelegram(string studentId) { - return await _userService.TelegramUserModelByStudentId(studentId); + var response = await _userService.ChatIdByStudentId(studentId); + return Ok(response); } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs index 06329d558..ff99752bd 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs @@ -8,6 +8,5 @@ namespace HwProj.TelegramBotService.API.Repositories public interface ITelegramBotRepository : ICrudRepository { IQueryable GetUserTelegramByChatId(long chatId); - IQueryable GetChatIdTelegramByAccountId(string accountId); } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs index ae07fd66a..96557ca17 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs @@ -18,10 +18,5 @@ public IQueryable GetUserTelegramByChatId(long chatId) { return Context.Set().Where(h => h.ChatId == chatId); } - - public IQueryable GetChatIdTelegramByAccountId(string accountId) - { - return Context.Set().Where(h => h.AccountId == accountId); - } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs index 9df56fc8a..4eeee0a88 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/CommandService.cs @@ -44,22 +44,20 @@ public async Task Execute(Update update) } var user = _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result; - if (user.Operation is "wait_code" or "check_code") + switch (user.Operation) { - switch (user.Operation) - { - case "wait_code": - await ExecuteCommand(CommandNames.WaitCodeCommand, update); - return; - case "check_code": - await ExecuteCommand(CommandNames.CheckCodeCommand, update); - return; - } - } - if (user.Operation == "wait_pull_request") - { - await ExecuteCommand(CommandNames.SendSolution, update); - return; + case "wait_code": + await ExecuteCommand(CommandNames.WaitCodeCommand, update); + return; + case "check_code": + await ExecuteCommand(CommandNames.CheckCodeCommand, update); + return; + case "wait_url": + await ExecuteCommand(CommandNames.SaveUrlAndWaitComment, update); + return; + case "wait_comment": + await ExecuteCommand(CommandNames.SendSolution, update); + return; } } else if (update.Type == UpdateType.CallbackQuery) diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs index 39f953b3c..11ee97356 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs @@ -8,19 +8,13 @@ namespace HwProj.TelegramBotService.API.Service public interface IUserService { Task CreateUser(Update update); - Task AddEmailToUser(Update update); - Task AddFinishUser(Update update); - Task UserByUpdate(Update update); - Task CheckTelegramUserModelByStudentId(string studentId); - Task TelegramUserModelByStudentId(string studentId); - Task GetChatIdByStudentId(string studentId); - + Task ChatIdByStudentId(string studentId); Task AddTaskIdAndWaitPullRequest(Update update, long taskId); - + Task AddGitHubUrlToTask(Update update, string url); Task DeleteUser(Update update); } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs index 53e91091f..5fcf50f96 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs @@ -2,7 +2,6 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -using AutoMapper; using HwProj.AuthService.Client; using HwProj.EventBus.Client.Interfaces; using HwProj.Models.TelegramBotService; @@ -22,7 +21,7 @@ public class UserService : IUserService private readonly IEventBus _eventBus; public UserService(TelegramBotContext context, IAuthServiceClient authClient, IEventBus eventBus, - ITelegramBotRepository telegramBotRepository, IMapper mapper) + ITelegramBotRepository telegramBotRepository) { _context = context; _authClient = authClient; @@ -66,7 +65,7 @@ public async Task CreateUser(Update update) public async Task AddEmailToUser(Update update) { var message = update.Message?.Text; - var user =_telegramBotRepository.GetUserTelegramByChatId(update.Message.Chat.Id); + var user = _telegramBotRepository.GetUserTelegramByChatId(update.Message.Chat.Id); var userModel = user.ToArray()[0]; if (userModel.Operation != "wait_code" || user == null) { @@ -92,7 +91,7 @@ public async Task AddFinishUser(Update update) var userModel = user.ToArray()[0]; if (userModel.Operation != "check_code" || userModel.Code != message || user == null) { - _context.Remove(user); + _context.Remove(userModel); await _context.SaveChangesAsync(); return null; } @@ -104,37 +103,45 @@ public async Task AddFinishUser(Update update) } public async Task UserByUpdate(Update update) - => update.Message == null - ? _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id) - .Result + { + var user = update.Message == null + ? _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id).Result : _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result; - + user.Operation = "finish"; + await _context.SaveChangesAsync(); + return user; + } + public async Task CheckTelegramUserModelByStudentId(string studentId) { var user = await _telegramBotRepository.FindAsync(cm => cm.AccountId == studentId).ConfigureAwait(false); return user != null; } - public async Task TelegramUserModelByStudentId(string studentId) - => await _telegramBotRepository.FindAsync(cm => cm.AccountId == studentId); - - public async Task GetChatIdByStudentId(string studentId) + public async Task ChatIdByStudentId(string studentId) { - var user = await _telegramBotRepository.FindAsync(cm => cm.AccountId == studentId); - return user.ChatId; + var user = await _telegramBotRepository.FindAll(t => t.AccountId == studentId).Select(t => t.ChatId).ToArrayAsync(); + return user[0]; } - - + public async Task AddTaskIdAndWaitPullRequest(Update update, long taskId) { var user = _telegramBotRepository.GetUserTelegramByChatId(update.CallbackQuery.Message.Chat.Id).ToArray()[0]; - var userModel = await _telegramBotRepository.FindAsync(cm => cm.ChatId == update.CallbackQuery.Message.Chat.Id).ConfigureAwait(false); - user.Operation = "wait_pull_request"; + user.Operation = "wait_url"; user.TaskIdToSend = taskId; await _context.SaveChangesAsync(); return user; } + public async Task AddGitHubUrlToTask(Update update, string url) + { + var user = _telegramBotRepository.GetUserTelegramByChatId(update.Message.Chat.Id).ToArray()[0]; + user.Operation = "wait_comment"; + user.GitHubUrl = url; + await _context.SaveChangesAsync(); + return user; + } + public async Task DeleteUser(Update update) { var user1 = await _context.TelegramUser.FindAsync(update.Message.Chat.Id); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs index bbf8fb2f4..230feb41d 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs @@ -39,6 +39,7 @@ public void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json index 496656437..4d5a6c1cd 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json @@ -24,5 +24,5 @@ "TelegramBot" : "http://localhost:5009" }, "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://6ab7-92-42-26-35.ngrok.io/" + "Url" : "https://c189-92-42-26-35.ngrok.io/" } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs index 0d3ebcb2c..0492cb6b9 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs @@ -6,6 +6,6 @@ namespace HwProj.TelegramBotService.Client public interface ITelegramBotServiceClient { Task CheckUser(string studentId); - Task GetTelegramUser(string studentId); + Task GetTelegramUser(string studentId); } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs index 6e4890bd5..767d1225e 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs @@ -36,14 +36,14 @@ public async Task CheckUser(string studentId) return await response.DeserializeAsync(); } - public async Task GetTelegramUser(string studentId) + public async Task GetTelegramUser(string studentId) { using var httpRequest = new HttpRequestMessage( HttpMethod.Get, _telegramBotUri + $"api/TelegramBot/get/{studentId}"); var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); + return await response.DeserializeAsync(); } } } \ No newline at end of file From ded1ca7e5abcc227cb76d2a5c92fe2fd60016dcc Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Fri, 13 May 2022 00:27:08 +0300 Subject: [PATCH 16/19] starting write test --- .../Services/NotificationsService.cs | 4 +- .../appsettings.json | 2 +- .../Commands/CheckCodeCommand.cs | 2 +- .../Commands/StartCommand.cs | 2 +- .../Commands/WaitCodeCommand.cs | 2 +- .../Service/IUserService.cs | 6 +- .../Service/UserService.cs | 142 ++++++++++++++---- .../appsettings.json | 2 +- .../ITelegramBotServiceClient.cs | 2 +- .../TelegramBotServiceClient.cs | 2 +- .../HwProj.TelegramBotService.Test.csproj | 31 ++++ .../TelegramBotServiceClientTest.cs | 126 ++++++++++++++++ HwProj.sln | 7 + 13 files changed, 288 insertions(+), 42 deletions(-) create mode 100644 HwProj.TelegramBotService.Test/HwProj.TelegramBotService.Test.csproj create mode 100644 HwProj.TelegramBotService.Test/TelegramBotServiceClientTest.cs diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs index 81ee20960..efca673eb 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs @@ -81,7 +81,7 @@ public async Task SendTelegramMessageAsync(Notification notification) var checkUser = await _telegramBotServiceClient.CheckUser(notification.Owner); if (checkUser) { - var user = await _telegramBotServiceClient.GetTelegramUser(notification.Owner); + var user = await _telegramBotServiceClient.GetTelegramUserChatId(notification.Owner); await _botClient.SendTextMessageAsync(user, notification.Body, ParseMode.Markdown); } } @@ -91,7 +91,7 @@ public async Task SendTelegramMessageWithKeyboardAsync(Notification notification var checkUser = await _telegramBotServiceClient.CheckUser(notification.Owner); if (checkUser) { - var user = await _telegramBotServiceClient.GetTelegramUser(notification.Owner); + var user = await _telegramBotServiceClient.GetTelegramUserChatId(notification.Owner); await _botClient.SendTextMessageAsync(user, notification.Body, ParseMode.Markdown, replyMarkup:inlineKeyboard); } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json index e85d11881..275540337 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json @@ -32,6 +32,6 @@ }, "Telegram": { "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://c189-92-42-26-35.ngrok.io/" + "Url" : "https://7af4-92-42-26-35.ngrok.io/" } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs index 50e4afa8f..ba5e9ab57 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs @@ -21,7 +21,7 @@ public CheckCodeCommand(TelegramBot telegramBot, IUserService userService) public override async Task ExecuteAsync(Update update) { - var user = await _userService.AddFinishUser(update); + var user = await _userService.AddFinishUser(update.Message.Chat.Id, update.Message.Text); var inlineKeyboard = new InlineKeyboardMarkup(GetButton("Мои курсы", "/courses")); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs index 99b8d6041..e7f37d2b8 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs @@ -23,7 +23,7 @@ public override async Task ExecuteAsync(Update update) { await _userService.DeleteUser(update); - var user = await _userService.CreateUser(update); + var user = await _userService.CreateUser(update.Message.Chat.Id); await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!\nВведите ваш e-mail на Hw-Proj2.0.1", ParseMode.Markdown); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs index 522812ae7..e1d27eecf 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs @@ -21,7 +21,7 @@ public WaitCodeCommand(TelegramBot telegramBot, IUserService userService) public override async Task ExecuteAsync(Update update) { - var user = await _userService.AddEmailToUser(update); + var user = await _userService.AddEmailToUser(update.Message.Chat.Id, update.Message?.Text); if (user == null) { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs index 11ee97356..697d14630 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs @@ -7,9 +7,9 @@ namespace HwProj.TelegramBotService.API.Service { public interface IUserService { - Task CreateUser(Update update); - Task AddEmailToUser(Update update); - Task AddFinishUser(Update update); + Task CreateUser(long chatId); + Task AddEmailToUser(long chatId, string message); + Task AddFinishUser(long chatId, string message); Task UserByUpdate(Update update); Task CheckTelegramUserModelByStudentId(string studentId); Task ChatIdByStudentId(string studentId); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs index 5fcf50f96..7cd5f12a0 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs @@ -16,20 +16,17 @@ namespace HwProj.TelegramBotService.API.Service public class UserService : IUserService { private readonly ITelegramBotRepository _telegramBotRepository; - private readonly TelegramBotContext _context; private readonly IAuthServiceClient _authClient; private readonly IEventBus _eventBus; - public UserService(TelegramBotContext context, IAuthServiceClient authClient, IEventBus eventBus, - ITelegramBotRepository telegramBotRepository) + public UserService(IAuthServiceClient authClient, IEventBus eventBus, ITelegramBotRepository telegramBotRepository) { - _context = context; _authClient = authClient; _eventBus = eventBus; _telegramBotRepository = telegramBotRepository; } - public async Task CreateUser(Update update) + public async Task CreateUser(long chatId) { var random = new Random(); var chars = "ABCEFGHJKPQRSTXYZ0123456789"; @@ -42,16 +39,15 @@ public async Task CreateUser(Update update) code.Append(chars[random.Next(chars.Length)]); var newUser = new UserTelegram { - ChatId = update.Message.Chat.Id, + ChatId = chatId, AccountId = null!, IsLecture = false, IsRegistered = false, Code = code.ToString(), Operation = "wait_code", }; - var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == newUser.ChatId); - - if (user != null) + //var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == newUser.ChatId); + /*if (user != null) { return user; } @@ -59,18 +55,20 @@ public async Task CreateUser(Update update) var result = await _context.TelegramUser.AddAsync(newUser); await _context.SaveChangesAsync(); - return result.Entity; + return result.Entity;*/ + var user = await _telegramBotRepository.AddAsync(newUser); + return await _telegramBotRepository.FindAsync(x => x.Id == user); } - public async Task AddEmailToUser(Update update) + public async Task AddEmailToUser(long chatId, string message) { - var message = update.Message?.Text; - var user = _telegramBotRepository.GetUserTelegramByChatId(update.Message.Chat.Id); + var user = _telegramBotRepository.GetUserTelegramByChatId(chatId); var userModel = user.ToArray()[0]; if (userModel.Operation != "wait_code" || user == null) { - _context.Remove(userModel); - await _context.SaveChangesAsync(); + /*_context.Remove(userModel); + await _context.SaveChangesAsync();*/ + await _telegramBotRepository.DeleteAsync(userModel.Id); return null; } @@ -79,37 +77,86 @@ public async Task AddEmailToUser(Update update) userModel.Operation = "check_code"; userModel.AccountId = accountId; userModel.IsLecture = studentModel.Role == "Lecture"; - await _context.SaveChangesAsync(); + /*await _context.SaveChangesAsync();*/ + var newUserModel = new UserTelegram + { + ChatId = userModel.ChatId, + AccountId = accountId, + IsLecture = userModel.IsLecture, + IsRegistered = false, + Code = userModel.Code, + Operation = "check_code", + }; + await _telegramBotRepository.UpdateAsync(userModel.Id, x => new UserTelegram + { + ChatId = userModel.ChatId, + AccountId = accountId, + IsLecture = userModel.IsLecture, + IsRegistered = false, + Code = userModel.Code, + Operation = "check_code", + }); _eventBus.Publish(new ConfirmTelegramBotEvent(userModel.AccountId, userModel.Code)); return userModel; } - public async Task AddFinishUser(Update update) + public async Task AddFinishUser(long chatId, string message) { - var message = update.Message?.Text; - var user = _telegramBotRepository.GetUserTelegramByChatId(update.Message.Chat.Id); + var user = _telegramBotRepository.GetUserTelegramByChatId(chatId); var userModel = user.ToArray()[0]; if (userModel.Operation != "check_code" || userModel.Code != message || user == null) { - _context.Remove(userModel); - await _context.SaveChangesAsync(); + /*_context.Remove(userModel); + await _context.SaveChangesAsync();*/ + await _telegramBotRepository.DeleteAsync(userModel.Id); return null; } userModel.Operation = "finish"; userModel.IsRegistered = true; - await _context.SaveChangesAsync(); + /*await _context.SaveChangesAsync();*/ + var newUserModel = new UserTelegram + { + ChatId = userModel.ChatId, + AccountId = userModel.AccountId, + IsLecture = userModel.IsLecture, + IsRegistered = true, + Code = userModel.Code, + Operation = "finish", + }; + await _telegramBotRepository.UpdateAsync(userModel.Id,x => new UserTelegram + { + ChatId = userModel.ChatId, + AccountId = userModel.AccountId, + IsLecture = userModel.IsLecture, + IsRegistered = true, + Code = userModel.Code, + Operation = "finish", + }); return userModel; } public async Task UserByUpdate(Update update) { - var user = update.Message == null + /*var user = update.Message == null ? _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id).Result : _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result; user.Operation = "finish"; - await _context.SaveChangesAsync(); - return user; + await _context.SaveChangesAsync();*/ + var user = update.Message == null + ? await _telegramBotRepository.FindAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id) + : await _telegramBotRepository.FindAsync(x => x.ChatId == update.Message.Chat.Id); + var newUserModel = new UserTelegram + { + ChatId = user.ChatId, + AccountId = user.AccountId, + IsLecture = user.IsLecture, + IsRegistered = user.IsRegistered, + Code = user.Code, + Operation = "finish", + }; + await _telegramBotRepository.UpdateAsync(user.Id, x => newUserModel); + return newUserModel; } public async Task CheckTelegramUserModelByStudentId(string studentId) @@ -126,31 +173,66 @@ public async Task ChatIdByStudentId(string studentId) public async Task AddTaskIdAndWaitPullRequest(Update update, long taskId) { - var user = _telegramBotRepository.GetUserTelegramByChatId(update.CallbackQuery.Message.Chat.Id).ToArray()[0]; + /*var user = _telegramBotRepository.GetUserTelegramByChatId(update.CallbackQuery.Message.Chat.Id).ToArray()[0]; user.Operation = "wait_url"; user.TaskIdToSend = taskId; await _context.SaveChangesAsync(); - return user; + return user;*/ + var user = _telegramBotRepository.GetUserTelegramByChatId(update.CallbackQuery.Message.Chat.Id).ToArray()[0]; + var newUserModel = new UserTelegram + { + ChatId = user.ChatId, + AccountId = user.AccountId, + IsLecture = user.IsLecture, + IsRegistered = user.IsRegistered, + Code = user.Code, + Operation = "wait_url", + TaskIdToSend = taskId + }; + await _telegramBotRepository.UpdateAsync(user.Id, x => newUserModel); + return newUserModel; } public async Task AddGitHubUrlToTask(Update update, string url) { - var user = _telegramBotRepository.GetUserTelegramByChatId(update.Message.Chat.Id).ToArray()[0]; + /*var user = _telegramBotRepository.GetUserTelegramByChatId(update.Message.Chat.Id).ToArray()[0]; user.Operation = "wait_comment"; user.GitHubUrl = url; await _context.SaveChangesAsync(); - return user; + return user;*/ + var user = _telegramBotRepository.GetUserTelegramByChatId(update.CallbackQuery.Message.Chat.Id).ToArray()[0]; + var newUserModel = new UserTelegram + { + ChatId = user.ChatId, + AccountId = user.AccountId, + IsLecture = user.IsLecture, + IsRegistered = user.IsRegistered, + Code = user.Code, + Operation = "wait_comment", + TaskIdToSend = user.TaskIdToSend, + GitHubUrl = url + }; + await _telegramBotRepository.UpdateAsync(user.Id, x => newUserModel); + return newUserModel; } public async Task DeleteUser(Update update) { - var user1 = await _context.TelegramUser.FindAsync(update.Message.Chat.Id); + /*var user1 = await _context.TelegramUser.FindAsync(update.Message.Chat.Id); if (user1 != null) { var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id); _context.Remove(user); await _context.SaveChangesAsync(); + }*/ + var user = update.Message == null + ? await _telegramBotRepository.FindAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id) + : await _telegramBotRepository.FindAsync(x => x.ChatId == update.Message.Chat.Id); + if (user == null) + { + return; } + await _telegramBotRepository.DeleteAsync(user.Id); } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json index 4d5a6c1cd..7d7528fcf 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json @@ -24,5 +24,5 @@ "TelegramBot" : "http://localhost:5009" }, "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://c189-92-42-26-35.ngrok.io/" + "Url" : "https://6e95-92-42-26-35.ngrok.io/" } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs index 0492cb6b9..159957ca3 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs @@ -6,6 +6,6 @@ namespace HwProj.TelegramBotService.Client public interface ITelegramBotServiceClient { Task CheckUser(string studentId); - Task GetTelegramUser(string studentId); + Task GetTelegramUserChatId(string studentId); } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs index 767d1225e..4cfa1dec8 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs @@ -36,7 +36,7 @@ public async Task CheckUser(string studentId) return await response.DeserializeAsync(); } - public async Task GetTelegramUser(string studentId) + public async Task GetTelegramUserChatId(string studentId) { using var httpRequest = new HttpRequestMessage( HttpMethod.Get, diff --git a/HwProj.TelegramBotService.Test/HwProj.TelegramBotService.Test.csproj b/HwProj.TelegramBotService.Test/HwProj.TelegramBotService.Test.csproj new file mode 100644 index 000000000..762b82083 --- /dev/null +++ b/HwProj.TelegramBotService.Test/HwProj.TelegramBotService.Test.csproj @@ -0,0 +1,31 @@ + + + + netcoreapp2.2 + + false + + latest + + + + + + + + + + + + + + + + + + + + + + + diff --git a/HwProj.TelegramBotService.Test/TelegramBotServiceClientTest.cs b/HwProj.TelegramBotService.Test/TelegramBotServiceClientTest.cs new file mode 100644 index 000000000..e5f8677cf --- /dev/null +++ b/HwProj.TelegramBotService.Test/TelegramBotServiceClientTest.cs @@ -0,0 +1,126 @@ +using System.Linq; +using System.Net.Http; +using System.Net.Mail; +using System.Threading.Tasks; +using AutoFixture; +using HwProj.AuthService.Client; +using HwProj.EventBus.Client.Interfaces; +using HwProj.Models.AuthService.ViewModels; +using HwProj.Models.TelegramBotService; +using HwProj.TelegramBotService.API.Models; +using NUnit.Framework; +using HwProj.TelegramBotService.API.Repositories; +using HwProj.TelegramBotService.API.Service; +using HwProj.TelegramBotService.Client; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Options; +using Moq; +using Microsoft.Extensions.DependencyInjection; +using Telegram.Bot.Types; +using Startup = HwProj.TelegramBotService.API.Startup; + +namespace HwProj.TelegramBotService.Test +{ + public class Tests + { + private readonly UserService _userService; + private readonly AuthServiceClient _authService; + + public Tests() + { + var eventBus = new Mock(); + _authService = CreateAuthServiceClient(); + var mock = new Mock(); + var repo = new Mock(); + _userService = new UserService(mock.Object, eventBus.Object, repo.Object); + } + + private TelegramBotServiceClient CreateTelegramBotServiceClient() + { + var mockIConfiguration = new Mock(); + mockIConfiguration + .Setup(x => x.GetSection("Services")["TelegramBot"]) + .Returns("http://localhost:5009"); + + var mockClientFactory = new Mock(); + mockClientFactory + .Setup(x => x.CreateClient(Options.DefaultName)) + .Returns(new HttpClient()); + + return new TelegramBotServiceClient(mockClientFactory.Object, mockIConfiguration.Object); + } + + private AuthServiceClient CreateAuthServiceClient() + { + var mockIConfiguration = new Mock(); + mockIConfiguration.Setup(x => x.GetSection("Services")["Auth"]).Returns("http://localhost:5001"); + var mockClientFactory = new Mock(); + mockClientFactory.Setup(x => x.CreateClient(Options.DefaultName)).Returns(new HttpClient()); + return new AuthServiceClient(mockClientFactory.Object, mockIConfiguration.Object); + } + + private static RegisterViewModel GenerateRegisterViewModel() + { + var password = new Fixture().Create(); + + var fixture = new Fixture().Build() + .With(x => x.Email, new Fixture().Create().Address) + .With(x => x.Password, password) + .With(x => x.PasswordConfirm, password); + + return fixture.Create(); + } + + private async Task<(string, string)> CreateAndRegisterUser() + { + var userData = GenerateRegisterViewModel(); + await _authService.Register(userData); + var userId = await _authService.FindByEmailAsync(userData.Email); + return (userId, userData.Email); + } + + private async Task RegisterTelegramUser(string userId, string email) + { + var chatId = new Fixture().Create(); + var userTelegram = new UserTelegram + { + ChatId = chatId, + AccountId = null!, + IsLecture = false, + IsRegistered = false, + Code = "AAAAA", + Operation = "wait_code" + }; + await _userService.CreateUser(chatId); + userTelegram = await _userService.AddEmailToUser(chatId, email); + await _userService.AddFinishUser(chatId, userTelegram.Code); + return userTelegram.ChatId; + } + + [Test] + public async Task СheckUserTest() + { + var (studentId, email) = await CreateAndRegisterUser(); + var telegramBotServiceClient = CreateTelegramBotServiceClient(); + var checkUserBeforeRegisterInTelegram = await telegramBotServiceClient.CheckUser(studentId); + await RegisterTelegramUser(studentId, email); + var checkUserAfterRegisterInTelegram = await telegramBotServiceClient.CheckUser(studentId); + Assert.IsTrue(!checkUserBeforeRegisterInTelegram); + Assert.IsTrue(checkUserAfterRegisterInTelegram); + } + + [Test] + public async Task GetTelegramUserChatIdTest() + { + var (studentId, email) = await CreateAndRegisterUser(); + var telegramBotServiceClient = CreateTelegramBotServiceClient(); + var chatId = await RegisterTelegramUser(studentId, email); + var chatIdFromGet = await telegramBotServiceClient.GetTelegramUserChatId(studentId); + Assert.AreEqual(chatId, chatIdFromGet); + } + } +} + diff --git a/HwProj.sln b/HwProj.sln index d28fce41e..def8db52a 100644 --- a/HwProj.sln +++ b/HwProj.sln @@ -75,6 +75,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HwProj.TelegramBotService.C EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HwProj.TelegramBotService.API", "HwProj.TelegramBot\HwProj.TelegramBotService.API\HwProj.TelegramBotService.API.csproj", "{677D77E8-ACFA-49FE-A752-F787B5F7A3EE}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HwProj.TelegramBotService.Test", "HwProj.TelegramBotService.Test\HwProj.TelegramBotService.Test.csproj", "{CAA4898C-B20E-4EC5-A37C-921A777D4935}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -173,6 +175,10 @@ Global {677D77E8-ACFA-49FE-A752-F787B5F7A3EE}.Debug|Any CPU.Build.0 = Debug|Any CPU {677D77E8-ACFA-49FE-A752-F787B5F7A3EE}.Release|Any CPU.ActiveCfg = Release|Any CPU {677D77E8-ACFA-49FE-A752-F787B5F7A3EE}.Release|Any CPU.Build.0 = Release|Any CPU + {CAA4898C-B20E-4EC5-A37C-921A777D4935}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CAA4898C-B20E-4EC5-A37C-921A777D4935}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CAA4898C-B20E-4EC5-A37C-921A777D4935}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CAA4898C-B20E-4EC5-A37C-921A777D4935}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -201,6 +207,7 @@ Global {51463655-7668-4C7D-9FDE-D4D7CDAA82B8} = {77D857A8-45C6-4432-B4BF-A2F2C9ECA7FE} {00F850B0-419E-44EA-9AFC-CBF3CBA26C91} = {42822186-2040-4216-9C1D-9849EA5D3CB5} {677D77E8-ACFA-49FE-A752-F787B5F7A3EE} = {42822186-2040-4216-9C1D-9849EA5D3CB5} + {CAA4898C-B20E-4EC5-A37C-921A777D4935} = {42822186-2040-4216-9C1D-9849EA5D3CB5} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {C03BF138-4A5B-4261-9495-6D3AC6CE9779} From 7a8532493b2fc92f9cdabddd34cb34a49a1393d9 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Fri, 13 May 2022 00:59:49 +0300 Subject: [PATCH 17/19] wip --- .../Service/UserService.cs | 38 ------------------- 1 file changed, 38 deletions(-) diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs index 7cd5f12a0..2e15fad40 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs @@ -46,16 +46,6 @@ public async Task CreateUser(long chatId) Code = code.ToString(), Operation = "wait_code", }; - //var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == newUser.ChatId); - /*if (user != null) - { - return user; - } - - var result = await _context.TelegramUser.AddAsync(newUser); - await _context.SaveChangesAsync(); - - return result.Entity;*/ var user = await _telegramBotRepository.AddAsync(newUser); return await _telegramBotRepository.FindAsync(x => x.Id == user); } @@ -66,8 +56,6 @@ public async Task AddEmailToUser(long chatId, string message) var userModel = user.ToArray()[0]; if (userModel.Operation != "wait_code" || user == null) { - /*_context.Remove(userModel); - await _context.SaveChangesAsync();*/ await _telegramBotRepository.DeleteAsync(userModel.Id); return null; } @@ -77,7 +65,6 @@ public async Task AddEmailToUser(long chatId, string message) userModel.Operation = "check_code"; userModel.AccountId = accountId; userModel.IsLecture = studentModel.Role == "Lecture"; - /*await _context.SaveChangesAsync();*/ var newUserModel = new UserTelegram { ChatId = userModel.ChatId, @@ -106,15 +93,12 @@ public async Task AddFinishUser(long chatId, string message) var userModel = user.ToArray()[0]; if (userModel.Operation != "check_code" || userModel.Code != message || user == null) { - /*_context.Remove(userModel); - await _context.SaveChangesAsync();*/ await _telegramBotRepository.DeleteAsync(userModel.Id); return null; } userModel.Operation = "finish"; userModel.IsRegistered = true; - /*await _context.SaveChangesAsync();*/ var newUserModel = new UserTelegram { ChatId = userModel.ChatId, @@ -138,11 +122,6 @@ public async Task AddFinishUser(long chatId, string message) public async Task UserByUpdate(Update update) { - /*var user = update.Message == null - ? _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id).Result - : _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id).Result; - user.Operation = "finish"; - await _context.SaveChangesAsync();*/ var user = update.Message == null ? await _telegramBotRepository.FindAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id) : await _telegramBotRepository.FindAsync(x => x.ChatId == update.Message.Chat.Id); @@ -173,11 +152,6 @@ public async Task ChatIdByStudentId(string studentId) public async Task AddTaskIdAndWaitPullRequest(Update update, long taskId) { - /*var user = _telegramBotRepository.GetUserTelegramByChatId(update.CallbackQuery.Message.Chat.Id).ToArray()[0]; - user.Operation = "wait_url"; - user.TaskIdToSend = taskId; - await _context.SaveChangesAsync(); - return user;*/ var user = _telegramBotRepository.GetUserTelegramByChatId(update.CallbackQuery.Message.Chat.Id).ToArray()[0]; var newUserModel = new UserTelegram { @@ -195,11 +169,6 @@ public async Task AddTaskIdAndWaitPullRequest(Update update, long public async Task AddGitHubUrlToTask(Update update, string url) { - /*var user = _telegramBotRepository.GetUserTelegramByChatId(update.Message.Chat.Id).ToArray()[0]; - user.Operation = "wait_comment"; - user.GitHubUrl = url; - await _context.SaveChangesAsync(); - return user;*/ var user = _telegramBotRepository.GetUserTelegramByChatId(update.CallbackQuery.Message.Chat.Id).ToArray()[0]; var newUserModel = new UserTelegram { @@ -218,13 +187,6 @@ public async Task AddGitHubUrlToTask(Update update, string url) public async Task DeleteUser(Update update) { - /*var user1 = await _context.TelegramUser.FindAsync(update.Message.Chat.Id); - if (user1 != null) - { - var user = await _context.TelegramUser.FirstOrDefaultAsync(x => x.ChatId == update.Message.Chat.Id); - _context.Remove(user); - await _context.SaveChangesAsync(); - }*/ var user = update.Message == null ? await _telegramBotRepository.FindAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id) : await _telegramBotRepository.FindAsync(x => x.ChatId == update.Message.Chat.Id); From 0f2b03d78cc4be7db7ef69116f42a4f3db730e3f Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Sun, 15 May 2022 00:11:40 +0300 Subject: [PATCH 18/19] fix bug and add request in test --- .../Services/NotificationsService.cs | 6 +- .../appsettings.json | 2 +- .../Controllers/TelegramBotController.cs | 20 +--- .../Repositories/ITelegramBotRepository.cs | 2 + .../Repositories/TelegramBotRepository.cs | 5 + .../Service/IUserService.cs | 2 +- .../Service/UserService.cs | 29 +++-- .../appsettings.json | 2 +- .../ITelegramBotServiceClient.cs | 4 +- .../TelegramBotServiceClient.cs | 17 +-- .../HwProj.TelegramBotService.Test.csproj | 1 + .../TelegramBotServiceClientTest.cs | 110 +++++++++++++++--- 12 files changed, 133 insertions(+), 67 deletions(-) diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs index efca673eb..1ef973e27 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsService.cs @@ -78,20 +78,18 @@ public async Task SendEmailAsync(Notification notification, string email, string public async Task SendTelegramMessageAsync(Notification notification) { - var checkUser = await _telegramBotServiceClient.CheckUser(notification.Owner); + var (checkUser, user) = await _telegramBotServiceClient.CheckUser(notification.Owner); if (checkUser) { - var user = await _telegramBotServiceClient.GetTelegramUserChatId(notification.Owner); await _botClient.SendTextMessageAsync(user, notification.Body, ParseMode.Markdown); } } public async Task SendTelegramMessageWithKeyboardAsync(Notification notification, InlineKeyboardMarkup inlineKeyboard) { - var checkUser = await _telegramBotServiceClient.CheckUser(notification.Owner); + var (checkUser, user) = await _telegramBotServiceClient.CheckUser(notification.Owner); if (checkUser) { - var user = await _telegramBotServiceClient.GetTelegramUserChatId(notification.Owner); await _botClient.SendTextMessageAsync(user, notification.Body, ParseMode.Markdown, replyMarkup:inlineKeyboard); } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json index 275540337..01c5bf68f 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/appsettings.json @@ -32,6 +32,6 @@ }, "Telegram": { "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://7af4-92-42-26-35.ngrok.io/" + "Url" : "https://4ba7-92-42-26-35.ngrok.io/" } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs index 82fdef7b6..c7add3aac 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs @@ -22,23 +22,14 @@ public TelegramBotController(ICommandService commandService, IUserService userSe } [HttpPost] - public async Task Update(Update update) + public async Task Update([FromBody] Update update) { if (update?.Message?.Chat == null && update?.CallbackQuery == null) { return Ok(); } - - try - { - await _commandService.Execute(update); - } - catch (Exception e) - { - return Ok(); - } - + await _commandService.Execute(update); return Ok(); } @@ -48,12 +39,5 @@ public async Task CheckUserTelegram(string studentId) var response = await _userService.CheckTelegramUserModelByStudentId(studentId); return Ok(response); } - - [HttpGet("get/{studentId}")] - public async Task GetUserTelegram(string studentId) - { - var response = await _userService.ChatIdByStudentId(studentId); - return Ok(response); - } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs index ff99752bd..158297801 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/ITelegramBotRepository.cs @@ -8,5 +8,7 @@ namespace HwProj.TelegramBotService.API.Repositories public interface ITelegramBotRepository : ICrudRepository { IQueryable GetUserTelegramByChatId(long chatId); + + Task GetChatIdByAccountId(string accountId); } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs index 96557ca17..c463d4c71 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Repositories/TelegramBotRepository.cs @@ -18,5 +18,10 @@ public IQueryable GetUserTelegramByChatId(long chatId) { return Context.Set().Where(h => h.ChatId == chatId); } + + public async Task GetChatIdByAccountId(string accountId) + { + return await Context.Set().FirstAsync(h => h.AccountId == accountId); + } } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs index 697d14630..c5c2d28ae 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs @@ -11,7 +11,7 @@ public interface IUserService Task AddEmailToUser(long chatId, string message); Task AddFinishUser(long chatId, string message); Task UserByUpdate(Update update); - Task CheckTelegramUserModelByStudentId(string studentId); + Task<(bool, long)> CheckTelegramUserModelByStudentId(string studentId); Task ChatIdByStudentId(string studentId); Task AddTaskIdAndWaitPullRequest(Update update, long taskId); Task AddGitHubUrlToTask(Update update, string url); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs index 2e15fad40..f860ce023 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs @@ -123,10 +123,9 @@ public async Task AddFinishUser(long chatId, string message) public async Task UserByUpdate(Update update) { var user = update.Message == null - ? await _telegramBotRepository.FindAsync(x => x.ChatId == update.CallbackQuery.Message.Chat.Id) - : await _telegramBotRepository.FindAsync(x => x.ChatId == update.Message.Chat.Id); - var newUserModel = new UserTelegram - { + ? await _telegramBotRepository.FindAsync(cm => cm.ChatId ==update.CallbackQuery.Message.Chat.Id) + : await _telegramBotRepository.FindAsync(cm => cm.ChatId ==update.Message.Chat.Id); + var newUserModel = new UserTelegram { ChatId = user.ChatId, AccountId = user.AccountId, IsLecture = user.IsLecture, @@ -134,23 +133,31 @@ public async Task UserByUpdate(Update update) Code = user.Code, Operation = "finish", }; - await _telegramBotRepository.UpdateAsync(user.Id, x => newUserModel); + await _telegramBotRepository.UpdateAsync(user.Id, x => new UserTelegram + { + ChatId = user.ChatId, + AccountId = user.AccountId, + IsLecture = user.IsLecture, + IsRegistered = user.IsRegistered, + Code = user.Code, + Operation = "finish", + }); return newUserModel; } - public async Task CheckTelegramUserModelByStudentId(string studentId) + public async Task<(bool, long)> CheckTelegramUserModelByStudentId(string studentId) { var user = await _telegramBotRepository.FindAsync(cm => cm.AccountId == studentId).ConfigureAwait(false); - return user != null; + return (user != null, user?.ChatId ?? 0); } public async Task ChatIdByStudentId(string studentId) { - var user = await _telegramBotRepository.FindAll(t => t.AccountId == studentId).Select(t => t.ChatId).ToArrayAsync(); - return user[0]; + var user = await _telegramBotRepository.FindAsync(cm => cm.AccountId == studentId).ConfigureAwait(false); + return user.ChatId; } - - public async Task AddTaskIdAndWaitPullRequest(Update update, long taskId) + + public async Task AddTaskIdAndWaitPullRequest(Update update, long taskId) { var user = _telegramBotRepository.GetUserTelegramByChatId(update.CallbackQuery.Message.Chat.Id).ToArray()[0]; var newUserModel = new UserTelegram diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json index 7d7528fcf..2bd125452 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/appsettings.json @@ -24,5 +24,5 @@ "TelegramBot" : "http://localhost:5009" }, "Token" : "1921590728:AAFFUK6qijY5IoVPiDWtpTCNc2rSh8Fb7EU", - "Url" : "https://6e95-92-42-26-35.ngrok.io/" + "Url" : "https://4ba7-92-42-26-35.ngrok.io/" } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs index 159957ca3..1d1a8fcc3 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/ITelegramBotServiceClient.cs @@ -1,11 +1,11 @@ using System.Threading.Tasks; using HwProj.Models.TelegramBotService; +using Telegram.Bot.Types; namespace HwProj.TelegramBotService.Client { public interface ITelegramBotServiceClient { - Task CheckUser(string studentId); - Task GetTelegramUserChatId(string studentId); + Task<(bool, long)> CheckUser(string studentId); } } \ No newline at end of file diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs index 4cfa1dec8..0bc860cf7 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.Client/TelegramBotServiceClient.cs @@ -6,6 +6,7 @@ using HwProj.Models.TelegramBotService; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; +using Telegram.Bot.Types; namespace HwProj.TelegramBotService.Client { @@ -19,8 +20,8 @@ public TelegramBotServiceClient(IHttpClientFactory clientFactory, IConfiguration _httpClient = clientFactory.CreateClient(); _telegramBotUri = new Uri(configuration.GetSection("Services")["TelegramBot"]); } - - public async Task CheckUser(string studentId) + + public async Task<(bool, long)> CheckUser(string studentId) { using var httpRequest = new HttpRequestMessage( HttpMethod.Get, @@ -33,17 +34,7 @@ public async Task CheckUser(string studentId) }; var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } - - public async Task GetTelegramUserChatId(string studentId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _telegramBotUri + $"api/TelegramBot/get/{studentId}"); - - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); + return await response.DeserializeAsync<(bool, long)>(); } } } \ No newline at end of file diff --git a/HwProj.TelegramBotService.Test/HwProj.TelegramBotService.Test.csproj b/HwProj.TelegramBotService.Test/HwProj.TelegramBotService.Test.csproj index 762b82083..6c8fbd343 100644 --- a/HwProj.TelegramBotService.Test/HwProj.TelegramBotService.Test.csproj +++ b/HwProj.TelegramBotService.Test/HwProj.TelegramBotService.Test.csproj @@ -24,6 +24,7 @@ + diff --git a/HwProj.TelegramBotService.Test/TelegramBotServiceClientTest.cs b/HwProj.TelegramBotService.Test/TelegramBotServiceClientTest.cs index e5f8677cf..9af0faf81 100644 --- a/HwProj.TelegramBotService.Test/TelegramBotServiceClientTest.cs +++ b/HwProj.TelegramBotService.Test/TelegramBotServiceClientTest.cs @@ -1,14 +1,15 @@ +using System; using System.Linq; using System.Net.Http; using System.Net.Mail; +using System.Text; using System.Threading.Tasks; -using AutoFixture; +using NUnit.Framework; using HwProj.AuthService.Client; using HwProj.EventBus.Client.Interfaces; using HwProj.Models.AuthService.ViewModels; using HwProj.Models.TelegramBotService; using HwProj.TelegramBotService.API.Models; -using NUnit.Framework; using HwProj.TelegramBotService.API.Repositories; using HwProj.TelegramBotService.API.Service; using HwProj.TelegramBotService.Client; @@ -17,9 +18,16 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; -using Moq; using Microsoft.Extensions.DependencyInjection; +using AutoFixture; +using FluentAssertions; +using HwProj.Models.NotificationsService; +using HwProj.NotificationsService.Client; +using Moq; +using Newtonsoft.Json; +using Telegram.Bot; using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; using Startup = HwProj.TelegramBotService.API.Startup; namespace HwProj.TelegramBotService.Test @@ -52,6 +60,21 @@ private TelegramBotServiceClient CreateTelegramBotServiceClient() return new TelegramBotServiceClient(mockClientFactory.Object, mockIConfiguration.Object); } + + private NotificationsServiceClient CreateNotificationsServiceClient() + { + var mockIConfiguration = new Mock(); + mockIConfiguration + .Setup(x => x.GetSection("Services")["Notifications"]) + .Returns("http://localhost:5006"); + + var mockClientFactory = new Mock(); + mockClientFactory + .Setup(x => x.CreateClient(Options.DefaultName)) + .Returns(new HttpClient()); + + return new NotificationsServiceClient(mockClientFactory.Object, mockIConfiguration.Object); + } private AuthServiceClient CreateAuthServiceClient() { @@ -100,27 +123,82 @@ private async Task RegisterTelegramUser(string userId, string email) return userTelegram.ChatId; } - [Test] - public async Task СheckUserTest() + public Update createUpdate(long chatId) { - var (studentId, email) = await CreateAndRegisterUser(); - var telegramBotServiceClient = CreateTelegramBotServiceClient(); - var checkUserBeforeRegisterInTelegram = await telegramBotServiceClient.CheckUser(studentId); - await RegisterTelegramUser(studentId, email); - var checkUserAfterRegisterInTelegram = await telegramBotServiceClient.CheckUser(studentId); - Assert.IsTrue(!checkUserBeforeRegisterInTelegram); - Assert.IsTrue(checkUserAfterRegisterInTelegram); + var fixture = new Fixture(); + fixture.Behaviors.OfType().ToList().ForEach(b => fixture.Behaviors.Remove(b)); + fixture.Behaviors.Add(new OmitOnRecursionBehavior()); + var chat = fixture.Build() + .With(h => h.Id, chatId) + .Create(); + var msg = fixture.Build() + .With(h => h.Text, "/start") + .With(h => h.Chat, chat) + .Create(); + return fixture.Build() + .With(h => h.Message, msg) + .Create(); } [Test] - public async Task GetTelegramUserChatIdTest() + public async Task СheckUserTest() { var (studentId, email) = await CreateAndRegisterUser(); var telegramBotServiceClient = CreateTelegramBotServiceClient(); - var chatId = await RegisterTelegramUser(studentId, email); - var chatIdFromGet = await telegramBotServiceClient.GetTelegramUserChatId(studentId); - Assert.AreEqual(chatId, chatIdFromGet); + var notificationsClient = CreateNotificationsServiceClient(); + var webHost = new WebApplicationFactory(); + var client = webHost.CreateClient(); + var chatId = new Fixture().Create(); + var upd = createUpdate(chatId); + + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + "http://localhost:5009/api/TelegramBot"); + httpRequest.Content = new StringContent( + JsonConvert.SerializeObject(upd, Formatting.Indented, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }), + Encoding.UTF8, + "application/json"); + await client.SendAsync(httpRequest); + + upd.Message.Text = email; + using var httpRequest1 = new HttpRequestMessage( + HttpMethod.Post, + "http://localhost:5009/api/TelegramBot"); + httpRequest1.Content = new StringContent( + JsonConvert.SerializeObject(upd, Formatting.Indented, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }), + Encoding.UTF8, + "application/json"); + await client.SendAsync(httpRequest1); + + var notifications = await notificationsClient.Get(studentId, new NotificationFilter()); + while (notifications.Length != 2) + { + notifications = await notificationsClient.Get(studentId, new NotificationFilter()); + } + var text = notifications[1].Body.Split(' ')[5]; + upd.Message.Text = text; + using var httpRequest2 = new HttpRequestMessage( + HttpMethod.Post, + "http://localhost:5009/" + $"api/TelegramBot"); + httpRequest2.Content = new StringContent( + JsonConvert.SerializeObject(upd, Formatting.Indented, new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }), + Encoding.UTF8, + "application/json"); + await client.SendAsync(httpRequest2); + + var (check, _) = await telegramBotServiceClient.CheckUser(studentId); + check.Should().BeTrue(); } + } } From d350fcd4defcea31e934981f65ded63483c71773 Mon Sep 17 00:00:00 2001 From: MikePuzanov Date: Sun, 5 Jun 2022 21:49:33 +0300 Subject: [PATCH 19/19] Change service name --- .../Commands/CheckCodeCommand.cs | 8 ++++---- .../Commands/ErrorCommand.cs | 8 ++++---- .../Commands/GetCourses.cs | 8 ++++---- .../Commands/GetHomeworks.cs | 8 ++++---- .../Commands/GetSolutionInfo.cs | 8 ++++---- .../Commands/GetSolutionsFromTask.cs | 8 ++++---- .../Commands/GetStatistics.cs | 8 ++++---- .../Commands/GetTaskInfo.cs | 8 ++++---- .../HwProj.TelegramBotService.API/Commands/GetTasks.cs | 8 ++++---- .../Commands/SaveUrlAndWaitComment.cs | 8 ++++---- .../Commands/SendSolution.cs | 8 ++++---- .../Commands/StartCommand.cs | 10 +++++----- .../Commands/WaitCodeCommand.cs | 8 ++++---- .../Commands/WaitPullRequest.cs | 8 ++++---- .../Controllers/TelegramBotController.cs | 8 ++++---- .../{IUserService.cs => IUserTelegramService.cs} | 2 +- .../Service/{UserService.cs => UserTelegramService.cs} | 4 ++-- .../HwProj.TelegramBotService.API/Startup.cs | 2 +- .../TelegramBotServiceClientTest.cs | 10 +++++----- 19 files changed, 70 insertions(+), 70 deletions(-) rename HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/{IUserService.cs => IUserTelegramService.cs} (94%) rename HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/{UserService.cs => UserTelegramService.cs} (97%) diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs index ba5e9ab57..382896b9b 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/CheckCodeCommand.cs @@ -9,19 +9,19 @@ namespace HwProj.TelegramBotService.API.Commands public class CheckCodeCommand : Commands { private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; - public CheckCodeCommand(TelegramBot telegramBot, IUserService userService) + public CheckCodeCommand(TelegramBot telegramBot, IUserTelegramService userTelegramService) { _botClient = telegramBot.GetBot().Result; - _userService = userService; + _userTelegramService = userTelegramService; } public override string Name => CommandNames.CheckCodeCommand; public override async Task ExecuteAsync(Update update) { - var user = await _userService.AddFinishUser(update.Message.Chat.Id, update.Message.Text); + var user = await _userTelegramService.AddFinishUser(update.Message.Chat.Id, update.Message.Text); var inlineKeyboard = new InlineKeyboardMarkup(GetButton("Мои курсы", "/courses")); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs index 6da8d4ce3..3ee58c8b6 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/ErrorCommand.cs @@ -9,19 +9,19 @@ namespace HwProj.TelegramBotService.API.Commands public class ErrorCommand : Commands { private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; - public ErrorCommand(TelegramBot telegramBot, IUserService userService) + public ErrorCommand(TelegramBot telegramBot, IUserTelegramService userTelegramService) { _botClient = telegramBot.GetBot().Result; - _userService = userService; + _userTelegramService = userTelegramService; } public override string Name => CommandNames.ErrorCommand; public override async Task ExecuteAsync(Update update) { - var user = await _userService.UserByUpdate(update); + var user = await _userTelegramService.UserByUpdate(update); await _botClient.SendTextMessageAsync(user.ChatId, "Повторите ещё раз!", ParseMode.Markdown); } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs index b829eca32..932437b49 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetCourses.cs @@ -13,20 +13,20 @@ public class GetCourses : Commands { private readonly ICoursesServiceClient _coursesServiceClient; private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; - public GetCourses(TelegramBot telegramBot, ICoursesServiceClient coursesServiceClient, IUserService userService) + public GetCourses(TelegramBot telegramBot, ICoursesServiceClient coursesServiceClient, IUserTelegramService userTelegramService) { _botClient = telegramBot.GetBot().Result; _coursesServiceClient = coursesServiceClient; - _userService = userService; + _userTelegramService = userTelegramService; } public override string Name => CommandNames.GetCourses; public override async Task ExecuteAsync(Update update) { - var user = await _userService.UserByUpdate(update); + var user = await _userTelegramService.UserByUpdate(update); var courses = _coursesServiceClient.GetAllUserCourses(user.AccountId).Result; await _botClient.SendTextMessageAsync(user.ChatId, "*Выберите курс для просмотра домашних работ или статистики:*", ParseMode.Markdown); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs index 010544f72..a27bdcc8c 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetHomeworks.cs @@ -14,20 +14,20 @@ public class GetHomeworks : Commands { private readonly ICoursesServiceClient _coursesServiceClient; private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; - public GetHomeworks(TelegramBot telegramBot, ICoursesServiceClient coursesServiceClient, IUserService userService) + public GetHomeworks(TelegramBot telegramBot, ICoursesServiceClient coursesServiceClient, IUserTelegramService userTelegramService) { _botClient = telegramBot.GetBot().Result; _coursesServiceClient = coursesServiceClient; - _userService = userService; + _userTelegramService = userTelegramService; } public override string Name => CommandNames.GetHomeworks; public override async Task ExecuteAsync(Update update) { - var user = await _userService.UserByUpdate(update); + var user = await _userTelegramService.UserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var homeworks = _coursesServiceClient.GetAllHomeworkByCourse(Int32.Parse(text[1])).Result; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs index abe7484c2..f585d362a 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionInfo.cs @@ -16,14 +16,14 @@ public class GetSolutionInfo : Commands private readonly ISolutionsServiceClient _solutionsServiceClient; private readonly ICoursesServiceClient _coursesServiceClient; private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; public GetSolutionInfo(TelegramBot telegramBot, ISolutionsServiceClient solutionsServiceClient, - IUserService userService, ICoursesServiceClient coursesServiceClient) + IUserTelegramService userTelegramService, ICoursesServiceClient coursesServiceClient) { _botClient = telegramBot.GetBot().Result; _solutionsServiceClient = solutionsServiceClient; - _userService = userService; + _userTelegramService = userTelegramService; _coursesServiceClient = coursesServiceClient; } @@ -31,7 +31,7 @@ public GetSolutionInfo(TelegramBot telegramBot, ISolutionsServiceClient solution public override async Task ExecuteAsync(Update update) { - var user = await _userService.UserByUpdate(update); + var user = await _userTelegramService.UserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var solution =_solutionsServiceClient.GetSolutionById(Int32.Parse(text[1])).Result; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs index 83a313f98..7532f2f8e 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetSolutionsFromTask.cs @@ -14,15 +14,15 @@ namespace HwProj.TelegramBotService.API.Commands public class GetSolutionsFromTask: Commands { private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; private readonly ISolutionsServiceClient _solutionsServiceClient; private readonly ICoursesServiceClient _coursesServiceClient; - public GetSolutionsFromTask(TelegramBot telegramBot, IUserService userService, ISolutionsServiceClient solutionsServiceClient, ICoursesServiceClient coursesServiceClient) + public GetSolutionsFromTask(TelegramBot telegramBot, IUserTelegramService userTelegramService, ISolutionsServiceClient solutionsServiceClient, ICoursesServiceClient coursesServiceClient) { _botClient = telegramBot.GetBot().Result; _solutionsServiceClient = solutionsServiceClient; - _userService = userService; + _userTelegramService = userTelegramService; _coursesServiceClient = coursesServiceClient; } @@ -30,7 +30,7 @@ public GetSolutionsFromTask(TelegramBot telegramBot, IUserService userService, I public override async Task ExecuteAsync(Update update) { - var user = await _userService.UserByUpdate(update); + var user = await _userTelegramService.UserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var solutions = _solutionsServiceClient.GetUserSolution(Int32.Parse(text[1]), user.AccountId).Result; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs index fe9d07171..dadb4e491 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetStatistics.cs @@ -14,14 +14,14 @@ namespace HwProj.TelegramBotService.API.Commands public class GetStatistics: Commands { private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; private readonly ISolutionsServiceClient _solutionsServiceClient; private readonly ICoursesServiceClient _coursesServiceClient; - public GetStatistics(TelegramBot telegramBot, IUserService userService, ICoursesServiceClient coursesServiceClient, ISolutionsServiceClient solutionsServiceClient) + public GetStatistics(TelegramBot telegramBot, IUserTelegramService userTelegramService, ICoursesServiceClient coursesServiceClient, ISolutionsServiceClient solutionsServiceClient) { _botClient = telegramBot.GetBot().Result; - _userService = userService; + _userTelegramService = userTelegramService; _coursesServiceClient = coursesServiceClient; _solutionsServiceClient = solutionsServiceClient; } @@ -30,7 +30,7 @@ public GetStatistics(TelegramBot telegramBot, IUserService userService, ICourses public override async Task ExecuteAsync(Update update) { - var user = await _userService.UserByUpdate(update); + var user = await _userTelegramService.UserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var course = _coursesServiceClient.GetCourseById(Int64.Parse(text[1]), user.AccountId).Result; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs index 3fdb77c7b..3a818942a 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTaskInfo.cs @@ -14,21 +14,21 @@ public class GetTaskInfo : Commands { private readonly ICoursesServiceClient _coursesServiceClient; private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; public GetTaskInfo(TelegramBot telegramBot, ICoursesServiceClient coursesServiceClient, - IUserService userService) + IUserTelegramService userTelegramService) { _botClient = telegramBot.GetBot().Result; _coursesServiceClient = coursesServiceClient; - _userService = userService; + _userTelegramService = userTelegramService; } public override string Name => CommandNames.GetTaskInfo; public override async Task ExecuteAsync(Update update) { - var user = await _userService.UserByUpdate(update); + var user = await _userTelegramService.UserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var task = _coursesServiceClient.GetTask(Int64.Parse(text[1])).Result; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs index d21e4e973..b9e1a17fa 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/GetTasks.cs @@ -14,21 +14,21 @@ public class GetTasks : Commands { private readonly ICoursesServiceClient _coursesServiceClient; private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; public GetTasks(TelegramBot telegramBot, ICoursesServiceClient coursesServiceClient, - IUserService userService) + IUserTelegramService userTelegramService) { _botClient = telegramBot.GetBot().Result; _coursesServiceClient = coursesServiceClient; - _userService = userService; + _userTelegramService = userTelegramService; } public override string Name => CommandNames.GetTasks; public override async Task ExecuteAsync(Update update) { - var user = await _userService.UserByUpdate(update); + var user = await _userTelegramService.UserByUpdate(update); var message = update.CallbackQuery.Data; var text = message.Split(' '); var hw = _coursesServiceClient.GetHomework(Int32.Parse(text[1])).Result; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SaveUrlAndWaitComment.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SaveUrlAndWaitComment.cs index 66316c45d..26052ad03 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SaveUrlAndWaitComment.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SaveUrlAndWaitComment.cs @@ -10,12 +10,12 @@ namespace HwProj.TelegramBotService.API.Commands public class SaveUrlAndWaitComment : Commands { private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; - public SaveUrlAndWaitComment(TelegramBot telegramBot, IUserService userService) + public SaveUrlAndWaitComment(TelegramBot telegramBot, IUserTelegramService userTelegramService) { _botClient = telegramBot.GetBot().Result; - _userService = userService; + _userTelegramService = userTelegramService; } public override string Name => CommandNames.SaveUrlAndWaitComment; @@ -25,7 +25,7 @@ public override async Task ExecuteAsync(Update update) var message = update.Message.Text; - var user = await _userService.AddGitHubUrlToTask(update, message); + var user = await _userTelegramService.AddGitHubUrlToTask(update, message); await _botClient.SendTextMessageAsync(user.ChatId, "Добавьте комментарий к решению.", ParseMode.Markdown); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs index 9814ce42b..56dbd9e02 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/SendSolution.cs @@ -12,13 +12,13 @@ namespace HwProj.TelegramBotService.API.Commands public class SendSolution: Commands { private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; private readonly ISolutionsServiceClient _solutionsService; - public SendSolution(TelegramBot telegramBot, IUserService userService, ISolutionsServiceClient solutionsService) + public SendSolution(TelegramBot telegramBot, IUserTelegramService userTelegramService, ISolutionsServiceClient solutionsService) { _botClient = telegramBot.GetBot().Result; - _userService = userService; + _userTelegramService = userTelegramService; _solutionsService = solutionsService; } @@ -26,7 +26,7 @@ public SendSolution(TelegramBot telegramBot, IUserService userService, ISolution public override async Task ExecuteAsync(Update update) { - var user = await _userService.UserByUpdate(update); + var user = await _userTelegramService.UserByUpdate(update); var message = update.Message.Text; var solutionModel = new SolutionViewModel diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs index e7f37d2b8..02973c424 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/StartCommand.cs @@ -9,21 +9,21 @@ namespace HwProj.TelegramBotService.API.Commands public class StartCommand : Commands { private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; - public StartCommand(TelegramBot telegramBot, IUserService userService) + public StartCommand(TelegramBot telegramBot, IUserTelegramService userTelegramService) { _botClient = telegramBot.GetBot().Result; - _userService = userService; + _userTelegramService = userTelegramService; } public override string Name => CommandNames.StartCommand; public override async Task ExecuteAsync(Update update) { - await _userService.DeleteUser(update); + await _userTelegramService.DeleteUser(update); - var user = await _userService.CreateUser(update.Message.Chat.Id); + var user = await _userTelegramService.CreateUser(update.Message.Chat.Id); await _botClient.SendTextMessageAsync(user.ChatId, "Добро пожаловать!\nВведите ваш e-mail на Hw-Proj2.0.1", ParseMode.Markdown); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs index e1d27eecf..4217d28d7 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitCodeCommand.cs @@ -9,19 +9,19 @@ namespace HwProj.TelegramBotService.API.Commands public class WaitCodeCommand : Commands { private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; - public WaitCodeCommand(TelegramBot telegramBot, IUserService userService) + public WaitCodeCommand(TelegramBot telegramBot, IUserTelegramService userTelegramService) { _botClient = telegramBot.GetBot().Result; - _userService = userService; + _userTelegramService = userTelegramService; } public override string Name => CommandNames.WaitCodeCommand; public override async Task ExecuteAsync(Update update) { - var user = await _userService.AddEmailToUser(update.Message.Chat.Id, update.Message?.Text); + var user = await _userTelegramService.AddEmailToUser(update.Message.Chat.Id, update.Message?.Text); if (user == null) { diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitPullRequest.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitPullRequest.cs index 397a10c40..fc119b1a6 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitPullRequest.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Commands/WaitPullRequest.cs @@ -12,12 +12,12 @@ namespace HwProj.TelegramBotService.API.Commands public class WaitPullRequest : Commands { private readonly TelegramBotClient _botClient; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; - public WaitPullRequest(TelegramBot telegramBot, IUserService userService) + public WaitPullRequest(TelegramBot telegramBot, IUserTelegramService userTelegramService) { _botClient = telegramBot.GetBot().Result; - _userService = userService; + _userTelegramService = userTelegramService; } public override string Name => CommandNames.WaitPullRequest; @@ -27,7 +27,7 @@ public override async Task ExecuteAsync(Update update) var message = update.CallbackQuery.Data; var text = message.Split(' '); - var user = await _userService.AddTaskIdAndWaitPullRequest(update, Int64.Parse(text[1])); + var user = await _userTelegramService.AddTaskIdAndWaitPullRequest(update, Int64.Parse(text[1])); await _botClient.SendTextMessageAsync(user.ChatId, "Отправьте ссылку на pull request.", ParseMode.Markdown); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs index c7add3aac..48d1ebb25 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Controllers/TelegramBotController.cs @@ -13,12 +13,12 @@ namespace HwProj.TelegramBotService.API.Controllers public class TelegramBotController : Controller { private readonly ICommandService _commandService; - private readonly IUserService _userService; + private readonly IUserTelegramService _userTelegramService; - public TelegramBotController(ICommandService commandService, IUserService userService) + public TelegramBotController(ICommandService commandService, IUserTelegramService userTelegramService) { _commandService = commandService; - _userService = userService; + _userTelegramService = userTelegramService; } [HttpPost] @@ -36,7 +36,7 @@ public async Task Update([FromBody] Update update) [HttpGet("check/{studentId}")] public async Task CheckUserTelegram(string studentId) { - var response = await _userService.CheckTelegramUserModelByStudentId(studentId); + var response = await _userTelegramService.CheckTelegramUserModelByStudentId(studentId); return Ok(response); } } diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserTelegramService.cs similarity index 94% rename from HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserTelegramService.cs index c5c2d28ae..ab00c60eb 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/IUserTelegramService.cs @@ -5,7 +5,7 @@ namespace HwProj.TelegramBotService.API.Service { - public interface IUserService + public interface IUserTelegramService { Task CreateUser(long chatId); Task AddEmailToUser(long chatId, string message); diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserTelegramService.cs similarity index 97% rename from HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs rename to HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserTelegramService.cs index f860ce023..b91e9eaa0 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserService.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Service/UserTelegramService.cs @@ -13,13 +13,13 @@ namespace HwProj.TelegramBotService.API.Service { - public class UserService : IUserService + public class UserTelegramTelegramService : IUserTelegramService { private readonly ITelegramBotRepository _telegramBotRepository; private readonly IAuthServiceClient _authClient; private readonly IEventBus _eventBus; - public UserService(IAuthServiceClient authClient, IEventBus eventBus, ITelegramBotRepository telegramBotRepository) + public UserTelegramTelegramService(IAuthServiceClient authClient, IEventBus eventBus, ITelegramBotRepository telegramBotRepository) { _authClient = authClient; _eventBus = eventBus; diff --git a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs index 230feb41d..21f69fec5 100644 --- a/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs +++ b/HwProj.TelegramBot/HwProj.TelegramBotService.API/Startup.cs @@ -31,7 +31,7 @@ public void ConfigureServices(IServiceCollection services) services.AddScoped(); services.AddScoped(); services.AddScoped(); - services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/HwProj.TelegramBotService.Test/TelegramBotServiceClientTest.cs b/HwProj.TelegramBotService.Test/TelegramBotServiceClientTest.cs index 9af0faf81..79451cc7a 100644 --- a/HwProj.TelegramBotService.Test/TelegramBotServiceClientTest.cs +++ b/HwProj.TelegramBotService.Test/TelegramBotServiceClientTest.cs @@ -34,7 +34,7 @@ namespace HwProj.TelegramBotService.Test { public class Tests { - private readonly UserService _userService; + private readonly UserTelegramTelegramService _userTelegramTelegramService; private readonly AuthServiceClient _authService; public Tests() @@ -43,7 +43,7 @@ public Tests() _authService = CreateAuthServiceClient(); var mock = new Mock(); var repo = new Mock(); - _userService = new UserService(mock.Object, eventBus.Object, repo.Object); + _userTelegramTelegramService = new UserTelegramTelegramService(mock.Object, eventBus.Object, repo.Object); } private TelegramBotServiceClient CreateTelegramBotServiceClient() @@ -117,9 +117,9 @@ private async Task RegisterTelegramUser(string userId, string email) Code = "AAAAA", Operation = "wait_code" }; - await _userService.CreateUser(chatId); - userTelegram = await _userService.AddEmailToUser(chatId, email); - await _userService.AddFinishUser(chatId, userTelegram.Code); + await _userTelegramTelegramService.CreateUser(chatId); + userTelegram = await _userTelegramTelegramService.AddEmailToUser(chatId, email); + await _userTelegramTelegramService.AddFinishUser(chatId, userTelegram.Code); return userTelegram.ChatId; }