rework console client

This commit is contained in:
Artemy
2025-07-11 15:52:10 +07:00
parent 2ddc7ae699
commit 9d06984e8c
19 changed files with 312 additions and 67 deletions
@@ -1,5 +1,6 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
namespace Govor.ConsoleClient.Commands
{
@@ -24,7 +25,7 @@ namespace Govor.ConsoleClient.Commands
try
{
// API uses Hub for this: AcceptFriendRequest(Guid friendshipId)
await HubConnection.InvokeAsync("AcceptFriendRequest", friendshipId);
await HubConnection.InvokeAsync("AcceptRequest", friendshipId);
Console.WriteLine("Заявка в друзья принята.");
}
catch (Exception ex)
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
using Govor.Contracts.DTOs; // Required for FriendshipDto
@@ -19,15 +20,12 @@ namespace Govor.ConsoleClient.Commands
Console.WriteLine("Получение всех дружеских связей (только для администраторов)...");
try
{
var response = await HttpClientService.GetAsync("api/admin/Friendships");
if (response.StatusCode == System.Net.HttpStatusCode.Forbidden)
{
Console.WriteLine("[Ошибка] Доступ запрещен. Эта команда только для администраторов.");
return;
}
response.EnsureSuccessStatusCode();
var json = await HttpClientService.GetAsync("api/admin/Friendships");
var friendships = await response.Content.ReadFromJsonAsync<List<FriendshipDto>>();
var friendships = JsonSerializer.Deserialize<List<FriendshipDto>>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
if (friendships != null && friendships.Any())
{
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
using Govor.Contracts.DTOs; // Required for FriendshipDto
@@ -30,14 +31,8 @@ namespace Govor.ConsoleClient.Commands
try
{
var response = await HttpClientService.GetAsync($"api/admin/Friendships/{userId}");
if (response.StatusCode == System.Net.HttpStatusCode.Forbidden)
{
Console.WriteLine("[Ошибка] Доступ запрещен. Эта команда только для администраторов.");
return;
}
response.EnsureSuccessStatusCode();
var friendships = await response.Content.ReadFromJsonAsync<List<FriendshipDto>>();
var friendships = JsonSerializer.Deserialize<List<FriendshipDto>>(response);
if (friendships != null && friendships.Any())
{
@@ -32,14 +32,7 @@ namespace Govor.ConsoleClient.Commands
// Let's assume query parameter for now as it's simpler for HttpPost.
var response = await HttpClientService.PostAsync($"api/admin/Friendships?Id={friendshipId}", null);
if (response.StatusCode == System.Net.HttpStatusCode.Forbidden)
{
Console.WriteLine("[Ошибка] Доступ запрещен. Эта команда только для администраторов.");
return;
}
response.EnsureSuccessStatusCode();
Console.WriteLine($"Дружеская связь {friendshipId} успешно удалена.");
}
catch (HttpRequestException httpEx) when (httpEx.StatusCode == System.Net.HttpStatusCode.Forbidden)
+21 -21
View File
@@ -1,3 +1,4 @@
using Microsoft.AspNetCore.SignalR.Client;
using System;
using System.Threading.Tasks;
@@ -6,13 +7,13 @@ namespace Govor.ConsoleClient.Commands
public abstract class BaseCommand : ICommand
{
protected static FriendsClient? FriendsClient { get; private set; }
protected static HttpClientService HttpClientService { get; private set; }
protected static Func<string?> GetAuthToken { get; private set; }
protected static Action<string> SetAuthToken { get; private set; }
protected static Func<Task> InitializeHubConnectionAsync { get; private set; }
protected static Microsoft.AspNetCore.SignalR.Client.HubConnection? HubConnection => _hubConnection?.Invoke();
private static Func<Microsoft.AspNetCore.SignalR.Client.HubConnection?> _hubConnection;
protected static HttpClientService HttpClientService { get; private set; } = null!;
protected static Func<string?> GetAuthToken { get; private set; } = null!;
protected static Action<string> SetAuthToken { get; private set; } = null!;
protected static Func<Task> InitializeHubConnectionAsync { get; private set; } = null!;
protected static HubConnection HubConnection => _getHubConnection?.Invoke();
private static Func<HubConnection?> _getHubConnection = null!;
public static void InitializeServices(
FriendsClient? friendsClient,
@@ -20,43 +21,42 @@ namespace Govor.ConsoleClient.Commands
Func<string?> getAuthToken,
Action<string> setAuthToken,
Func<Task> initializeHubConnectionAsync,
Func<Microsoft.AspNetCore.SignalR.Client.HubConnection?> hubConnection)
Func<HubConnection?> getHubConnection)
{
FriendsClient = friendsClient;
HttpClientService = httpClientService;
GetAuthToken = getAuthToken;
SetAuthToken = setAuthToken;
InitializeHubConnectionAsync = initializeHubConnectionAsync;
_hubConnection = hubConnection;
_getHubConnection = getHubConnection;
}
public abstract Task ExecuteAsync(string? argument);
public abstract string GetHelp();
protected boolEnsureLoggedIn()
protected bool EnsureLoggedIn()
{
if (GetAuthToken() == null)
{
System.Console.WriteLine("[Ошибка] Сначала войдите в систему. Используйте /login или /reg.");
Console.WriteLine("[Ошибка] Сначала войдите в систему. Используйте /login или /reg.");
return false;
}
if (FriendsClient == null && !(this is LoginCommand || this is RegisterCommand)) // FriendsClient might not be needed for auth commands
if (FriendsClient == null && !(this is LoginCommand || this is RegisterCommand))
{
// Attempt to re-initialize FriendsClient if token exists but client is null
// This can happen if the app was closed and token was persisted, but client was not re-instantiated.
// However, the current setup in Program.cs initializes FriendsClient after login/reg.
// This check is more of a safeguard.
System.Console.WriteLine("[Ошибка] Клиент для работы с друзьями не инициализирован. Попробуйте войти снова.");
return false;
Console.WriteLine("[Ошибка] Клиент для работы с друзьями не инициализирован. Попробуйте войти снова.");
return false;
}
return true;
}
protected boolEnsureHubConnection()
protected bool EnsureHubConnection()
{
if (HubConnection == null || HubConnection.State != Microsoft.AspNetCore.SignalR.Client.HubConnectionState.Connected)
var hub = _getHubConnection?.Invoke();
if (hub == null || hub.State != HubConnectionState.Connected)
{
System.Console.WriteLine("[Ошибка] SignalR соединение не установлено. Попробуйте войти снова или проверьте соединение.");
Console.WriteLine("[Ошибка] SignalR соединение не установлено. Попробуйте войти снова или проверьте соединение.");
return false;
}
return true;
@@ -1,5 +1,6 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
namespace Govor.ConsoleClient.Commands
{
@@ -2,6 +2,7 @@ using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
using Govor.Contracts.DTOs; // Required for FriendshipDto
@@ -17,10 +18,12 @@ namespace Govor.ConsoleClient.Commands
{
// This functionality maps to GET api/friends/responses in FriendsRequestQueryController
// FriendsClient doesn't have a dedicated method, so we use HttpClientService or direct HttpClient
var response = await HttpClientService.GetAsync("api/friends/responses");
response.EnsureSuccessStatusCode();
var json = await HttpClientService.GetAsync("api/friends/responses");
var requests = await response.Content.ReadFromJsonAsync<System.Collections.Generic.List<FriendshipDto>>();
var requests = JsonSerializer.Deserialize<List<FriendshipDto>>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
if (requests != null && requests.Any())
{
+3 -2
View File
@@ -30,8 +30,9 @@ namespace Govor.ConsoleClient.Commands
sharedClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
var friendsClient = new FriendsClient(sharedClient);
// Re-initialize services in BaseCommand with the new FriendsClient
InitializeServices(friendsClient, HttpClientService, GetAuthToken, SetAuthToken, InitializeHubConnectionAsync, HubConnection);
Program.UpdateFriendsClient(friendsClient); // <-- единственный нужный вызов
await InitializeHubConnectionAsync();
Console.WriteLine("[Успех] Вход выполнен. Токен сохранен.");
+1 -1
View File
@@ -34,7 +34,7 @@ namespace Govor.ConsoleClient.Commands
var friendsClient = new FriendsClient(sharedClient);
// Re-initialize services in BaseCommand with the new FriendsClient
InitializeServices(friendsClient, HttpClientService, GetAuthToken, SetAuthToken, InitializeHubConnectionAsync, HubConnection);
Program.UpdateFriendsClient(friendsClient); // <-- единственный нужный вызов
await InitializeHubConnectionAsync();
Console.WriteLine("[Успех] Регистрация завершена. Токен сохранен.");
@@ -1,5 +1,6 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
namespace Govor.ConsoleClient.Commands
{
@@ -25,7 +26,7 @@ namespace Govor.ConsoleClient.Commands
{
// API uses Hub for this: RejectFriendRequest(Guid friendshipId)
// Located in Govor.API/Hubs/FriendsHub.cs
await HubConnection.InvokeAsync("RejectFriendRequest", friendshipId);
await HubConnection.InvokeAsync("RejectRequest", friendshipId);
Console.WriteLine("Заявка в друзья отклонена.");
}
catch (Exception ex)
@@ -1,5 +1,6 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
namespace Govor.ConsoleClient.Commands
{
@@ -24,7 +25,7 @@ namespace Govor.ConsoleClient.Commands
try
{
// API uses Hub for this: SendFriendRequest(Guid targetUserId)
await HubConnection.InvokeAsync("SendFriendRequest", targetUserId);
await HubConnection.InvokeAsync("SendRequest", targetUserId);
Console.WriteLine("Запрос в друзья отправлен.");
}
catch (Exception ex)
@@ -1,5 +1,6 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
namespace Govor.ConsoleClient.Commands
{