Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 47d106e288 | |||
| a5624897e9 | |||
| 11e75d036a | |||
| 2942da0c35 | |||
| 549c0c96ae | |||
| dd9337dd20 | |||
| 3cc3b373e5 | |||
| f6d5281af8 | |||
| fa63886195 | |||
| 9bd5fe75c9 | |||
| d931da37ec | |||
| 9375fa45b2 | |||
| 0b45aee96d | |||
| 80e346d6b5 | |||
| eff0128d29 | |||
| 8214e052af | |||
| 2a233b2b1e | |||
| 5e3028e470 | |||
| 63193310f2 | |||
| af37f3a8ec | |||
| 66228cf106 |
@@ -6,7 +6,7 @@ on:
|
||||
- main
|
||||
|
||||
env:
|
||||
VERSION: 3.0.0
|
||||
VERSION: 3.0.8
|
||||
|
||||
jobs:
|
||||
# ЧАСТЬ 1: Собираем образы и кладем в Gitea (чтобы делиться с ребятами)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Version>3.0.0</Version>
|
||||
<Version>3.0.8</Version>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>preview</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
@@ -85,8 +85,10 @@ TELEGRAM_BOT_TOKEN=ваш_токен_здесь
|
||||
# Токен Discord application bot
|
||||
DISCORD_BOT_TOKEN=ваш_discord_токен_здесь
|
||||
|
||||
# Client ID Discord application (используется для slash-команд)
|
||||
DISCORD_BOT_CLIENT_ID=ваш_discord_client_id_здесь
|
||||
# Discord OAuth (для Web Dashboard)
|
||||
DISCORD_CLIENT_ID=ваш_discord_client_id_здесь
|
||||
DISCORD_CLIENT_SECRET=ваш_discord_client_secret_здесь
|
||||
DISCORD_REDIRECT_URI=https://your-domain.example/auth/discord/callback
|
||||
|
||||
# Имя бота без @ (для Telegram Login Widget)
|
||||
TELEGRAM_BOT_USERNAME=ваше_имя_бота_здесь
|
||||
@@ -119,7 +121,7 @@ docker compose up -d
|
||||
1. Напишите боту `/start`.
|
||||
2. Создайте группу через `/newgroup`.
|
||||
3. Откройте Mini App или Web Dashboard для расширенного управления.
|
||||
4. Для Discord пригласите application bot на сервер с правами `bot` и `applications.commands`. Скопируйте `DISCORD_BOT_TOKEN` и `DISCORD_BOT_CLIENT_ID` в `.env`.
|
||||
4. Для Discord пригласите application bot на сервер с правами `bot` и `applications.commands`. Скопируйте `DISCORD_BOT_TOKEN` в `.env`; `DISCORD_CLIENT_ID`, `DISCORD_CLIENT_SECRET` и `DISCORD_REDIRECT_URI` нужны только для входа в Web Dashboard через Discord.
|
||||
5. Перезапустите Docker Compose (`docker compose up -d`), а затем в Discord создайте сессию через `/newsession` или опубликуйте расписание через `/listsessions`; игроки записываются и выходят кнопками в опубликованном сообщении.
|
||||
|
||||
## 💾 Backup и восстановление
|
||||
|
||||
+3
-3
@@ -49,7 +49,7 @@ services:
|
||||
crond -f
|
||||
|
||||
bot:
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-bot:3.0.0
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-bot:3.0.8
|
||||
restart: always
|
||||
depends_on:
|
||||
db:
|
||||
@@ -67,7 +67,7 @@ services:
|
||||
retries: 3
|
||||
|
||||
discord:
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-discord-bot:3.0.0
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-discord-bot:3.0.8
|
||||
restart: always
|
||||
depends_on:
|
||||
db:
|
||||
@@ -84,7 +84,7 @@ services:
|
||||
retries: 3
|
||||
|
||||
web:
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-web:3.0.0
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-web:3.0.8
|
||||
restart: always
|
||||
depends_on:
|
||||
db:
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
-- =============================================================
|
||||
-- V021: Add avatar_url column to players table
|
||||
-- =============================================================
|
||||
-- Scope: Support storing avatar URLs for Discord and other platforms.
|
||||
-- =============================================================
|
||||
|
||||
ALTER TABLE players
|
||||
ADD COLUMN avatar_url VARCHAR(500);
|
||||
@@ -0,0 +1,16 @@
|
||||
-- =============================================================
|
||||
-- V022: Fix incorrectly oriented player_links for Discord↔Telegram
|
||||
-- =============================================================
|
||||
-- Scope: Reverse player_links where Discord was incorrectly made primary
|
||||
-- and Telegram secondary. Telegram (with historical group/session data)
|
||||
-- must always be the primary account.
|
||||
-- =============================================================
|
||||
|
||||
UPDATE player_links pl
|
||||
SET primary_player_id = pl.secondary_player_id,
|
||||
secondary_player_id = pl.primary_player_id
|
||||
FROM players p1, players p2
|
||||
WHERE pl.primary_player_id = p1.id
|
||||
AND pl.secondary_player_id = p2.id
|
||||
AND p1.platform = 'Discord'
|
||||
AND p2.platform = 'Telegram';
|
||||
@@ -3,7 +3,6 @@ using NetCord.Services.ApplicationCommands;
|
||||
|
||||
namespace GmRelay.DiscordBot.Features.Sessions;
|
||||
|
||||
[SlashCommand("listsessions", "Show upcoming game sessions in this server")]
|
||||
public class DiscordListSessionsCommand : ApplicationCommandModule<SlashCommandContext>
|
||||
{
|
||||
private readonly DiscordListSessionsHandler _handler;
|
||||
@@ -13,9 +12,10 @@ public class DiscordListSessionsCommand : ApplicationCommandModule<SlashCommandC
|
||||
_handler = handler;
|
||||
}
|
||||
|
||||
[SlashCommand("listsessions", "Show upcoming game sessions in this server")]
|
||||
public async Task ExecuteAsync()
|
||||
{
|
||||
var guildId = Context.Guild?.Id.ToString()
|
||||
var guildId = Context.Interaction.GuildId?.ToString()
|
||||
?? throw new InvalidOperationException("This command can only be used in a guild.");
|
||||
var channelId = Context.Channel.Id.ToString();
|
||||
|
||||
|
||||
@@ -21,8 +21,8 @@ public sealed class DiscordListSessionsHandler(NpgsqlDataSource dataSource)
|
||||
var sessions = await connection.QueryAsync<DiscordSessionListItemDto>(
|
||||
@"SELECT s.id as Id, s.title as Title, s.scheduled_at as ScheduledAt, s.status as Status,
|
||||
s.max_players as MaxPlayers,
|
||||
COUNT(sp.id) FILTER (WHERE sp.is_gm = false AND sp.registration_status = @Active) as PlayerCount,
|
||||
COUNT(sp.id) FILTER (WHERE sp.is_gm = false AND sp.registration_status = @Waitlisted) as WaitlistCount
|
||||
COUNT(sp.id) FILTER (WHERE sp.is_gm = false AND sp.registration_status = @Active)::int as PlayerCount,
|
||||
COUNT(sp.id) FILTER (WHERE sp.is_gm = false AND sp.registration_status = @Waitlisted)::int as WaitlistCount
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON s.group_id = g.id
|
||||
LEFT JOIN session_participants sp ON s.id = sp.session_id
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
using GmRelay.DiscordBot.Rendering;
|
||||
using GmRelay.DiscordBot.Rendering;
|
||||
using NetCord;
|
||||
using NetCord.Rest;
|
||||
using NetCord.Services.ApplicationCommands;
|
||||
|
||||
namespace GmRelay.DiscordBot.Features.Sessions;
|
||||
|
||||
[SlashCommand("newsession", "Create a new game session")]
|
||||
public class DiscordNewSessionCommand : ApplicationCommandModule<SlashCommandContext>
|
||||
{
|
||||
private readonly DiscordNewSessionHandler _handler;
|
||||
@@ -16,15 +16,52 @@ public class DiscordNewSessionCommand : ApplicationCommandModule<SlashCommandCon
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[SlashCommand("newsession", "Create a new game session")]
|
||||
public async Task ExecuteAsync(
|
||||
[SlashCommandParameter(Name = "title", Description = "Game title")] string title,
|
||||
[SlashCommandParameter(Name = "time", Description = "Session time (YYYY-MM-DD HH:mm or DD.MM.YYYY HH:mm)")] string time,
|
||||
[SlashCommandParameter(Name = "seats", Description = "Maximum number of players")] long? seats = null,
|
||||
[SlashCommandParameter(Name = "link", Description = "Join link")] string? link = null)
|
||||
{
|
||||
var guild = Context.Guild
|
||||
_logger.LogInformation(
|
||||
"newsession called by user {UserId} ({UserType}) in guild {GuildId}, channel {ChannelId}",
|
||||
Context.User.Id,
|
||||
Context.User.GetType().Name,
|
||||
Context.Interaction.GuildId,
|
||||
Context.Channel?.Id);
|
||||
|
||||
var guildId = Context.Interaction.GuildId
|
||||
?? throw new InvalidOperationException("This command can only be used in a guild.");
|
||||
|
||||
var member = Context.User as GuildInteractionUser;
|
||||
if (member is null)
|
||||
{
|
||||
_logger.LogError("Context.User is not GuildInteractionUser. Actual type: {ActualType}", Context.User.GetType().Name);
|
||||
throw new InvalidOperationException("Guild member data not available in interaction.");
|
||||
}
|
||||
|
||||
var resolvedPermissions = (ulong)member.Permissions;
|
||||
_logger.LogInformation("Resolved permissions for user {UserId}: {Permissions}", Context.User.Id, resolvedPermissions);
|
||||
|
||||
ulong guildOwnerId = 0;
|
||||
try
|
||||
{
|
||||
var guild = await Context.Client.Rest.GetGuildAsync(guildId);
|
||||
guildOwnerId = guild.OwnerId;
|
||||
_logger.LogInformation("Guild owner id: {OwnerId}", guildOwnerId);
|
||||
}
|
||||
catch (RestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
ex,
|
||||
"Bot is not a REST member of guild {GuildId}; using resolved permissions from interaction payload",
|
||||
guildId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Unexpected error fetching guild {GuildId}", guildId);
|
||||
}
|
||||
|
||||
var timeResult = DiscordNewSessionHandler.ParseTimeInput(time);
|
||||
if (!timeResult.IsSuccess)
|
||||
{
|
||||
@@ -33,55 +70,56 @@ public class DiscordNewSessionCommand : ApplicationCommandModule<SlashCommandCon
|
||||
return;
|
||||
}
|
||||
|
||||
var resolvedPermissions = GetResolvedPermissions(guild, Context.User.Id);
|
||||
// Defer the response to avoid Discord 3-second interaction timeout
|
||||
await Context.Interaction.SendResponseAsync(InteractionCallback.DeferredMessage());
|
||||
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Creating session for guild {GuildId}, user {UserId}", guildId, Context.User.Id);
|
||||
|
||||
var view = await _handler.HandleAsync(
|
||||
guildId: guild.Id.ToString(),
|
||||
channelId: Context.Channel.Id.ToString(),
|
||||
guildId: guildId.ToString(),
|
||||
channelId: Context.Channel!.Id.ToString(),
|
||||
userId: Context.User.Id,
|
||||
userDisplayName: Context.User.GlobalName ?? Context.User.Username,
|
||||
resolvedPermissions: resolvedPermissions,
|
||||
guildOwnerId: guild.OwnerId,
|
||||
guildOwnerId: guildOwnerId,
|
||||
title: title,
|
||||
scheduledAt: timeResult.Value,
|
||||
maxPlayers: seats is null ? null : (int)seats.Value,
|
||||
joinLink: link,
|
||||
CancellationToken.None);
|
||||
|
||||
_logger.LogInformation("Session created successfully. Building render.");
|
||||
|
||||
var (embeds, actionRows) = DiscordSessionBatchRenderer.Render(view);
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message(new InteractionMessageProperties()
|
||||
.WithContent(":white_check_mark: **Session created successfully!**")
|
||||
.WithEmbeds(embeds)
|
||||
.WithComponents(actionRows)));
|
||||
|
||||
_logger.LogInformation("Sending success response.");
|
||||
|
||||
await Context.Interaction.ModifyResponseAsync(message =>
|
||||
{
|
||||
message.Content = ":white_check_mark: **Session created successfully!**";
|
||||
message.Embeds = embeds;
|
||||
message.Components = actionRows;
|
||||
});
|
||||
|
||||
_logger.LogInformation("Success response sent.");
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message($":no_entry: {ex.Message}"));
|
||||
_logger.LogWarning(ex, "Unauthorized session creation attempt by user {UserId}", Context.User.Id);
|
||||
await Context.Interaction.ModifyResponseAsync(message =>
|
||||
{
|
||||
message.Content = $":no_entry: {ex.Message}";
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to create session for user {UserId} in guild {GuildId}", Context.User.Id, guild.Id);
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message(":boom: An error occurred while creating the session."));
|
||||
_logger.LogError(ex, "Failed to create session for user {UserId} in guild {GuildId}", Context.User.Id, guildId);
|
||||
await Context.Interaction.ModifyResponseAsync(message =>
|
||||
{
|
||||
message.Content = ":boom: An error occurred while creating the session.";
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static ulong GetResolvedPermissions(NetCord.Gateway.Guild guild, ulong userId)
|
||||
{
|
||||
if (!guild.Users.TryGetValue(userId, out var guildUser))
|
||||
return 0;
|
||||
|
||||
ulong resolved = 0;
|
||||
foreach (var roleId in guildUser.RoleIds)
|
||||
{
|
||||
if (guild.Roles.TryGetValue(roleId, out var role))
|
||||
resolved |= (ulong)role.Permissions;
|
||||
}
|
||||
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
namespace GmRelay.DiscordBot.Features.Sessions;
|
||||
|
||||
using NetCord;
|
||||
using NetCord.Rest;
|
||||
using NetCord.Services.ApplicationCommands;
|
||||
|
||||
[SlashCommand("reschedule", "Initiate reschedule voting for a session")]
|
||||
public class DiscordRescheduleCommand : ApplicationCommandModule<SlashCommandContext>
|
||||
{
|
||||
private readonly DiscordRescheduleHandler _handler;
|
||||
@@ -15,6 +15,7 @@ public class DiscordRescheduleCommand : ApplicationCommandModule<SlashCommandCon
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[SlashCommand("reschedule", "Initiate reschedule voting for a session")]
|
||||
public async Task ExecuteAsync(
|
||||
[SlashCommandParameter(Name = "session", Description = "Session ID to reschedule")] string sessionIdText,
|
||||
[SlashCommandParameter(Name = "option1", Description = "First time option (YYYY-MM-DD HH:mm)")] string option1,
|
||||
@@ -22,9 +23,44 @@ public class DiscordRescheduleCommand : ApplicationCommandModule<SlashCommandCon
|
||||
[SlashCommandParameter(Name = "option3", Description = "Third time option (optional)")] string? option3 = null,
|
||||
[SlashCommandParameter(Name = "deadline", Description = "Voting deadline (YYYY-MM-DD HH:mm)")] string deadline = "")
|
||||
{
|
||||
var guild = Context.Guild
|
||||
_logger.LogInformation(
|
||||
"reschedule called by user {UserId} ({UserType}) in guild {GuildId}",
|
||||
Context.User.Id,
|
||||
Context.User.GetType().Name,
|
||||
Context.Interaction.GuildId);
|
||||
|
||||
var guildId = Context.Interaction.GuildId
|
||||
?? throw new InvalidOperationException("This command can only be used in a guild.");
|
||||
|
||||
var member = Context.User as GuildInteractionUser;
|
||||
if (member is null)
|
||||
{
|
||||
_logger.LogError("Context.User is not GuildInteractionUser. Actual type: {ActualType}", Context.User.GetType().Name);
|
||||
throw new InvalidOperationException("Guild member data not available in interaction.");
|
||||
}
|
||||
|
||||
var resolvedPermissions = (ulong)member.Permissions;
|
||||
_logger.LogInformation("Resolved permissions for user {UserId}: {Permissions}", Context.User.Id, resolvedPermissions);
|
||||
|
||||
ulong guildOwnerId = 0;
|
||||
try
|
||||
{
|
||||
var guild = await Context.Client.Rest.GetGuildAsync(guildId);
|
||||
guildOwnerId = guild.OwnerId;
|
||||
_logger.LogInformation("Guild owner id: {OwnerId}", guildOwnerId);
|
||||
}
|
||||
catch (RestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
ex,
|
||||
"Bot is not a REST member of guild {GuildId}; using resolved permissions from interaction payload",
|
||||
guildId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Unexpected error fetching guild {GuildId}", guildId);
|
||||
}
|
||||
|
||||
if (!Guid.TryParse(sessionIdText, out var sessionId))
|
||||
{
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
@@ -64,54 +100,55 @@ public class DiscordRescheduleCommand : ApplicationCommandModule<SlashCommandCon
|
||||
return;
|
||||
}
|
||||
|
||||
var resolvedPermissions = GetResolvedPermissions(guild, Context.User.Id);
|
||||
// Defer the response to avoid Discord 3-second interaction timeout
|
||||
await Context.Interaction.SendResponseAsync(InteractionCallback.DeferredMessage());
|
||||
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Initiating reschedule for session {SessionId} in guild {GuildId}", sessionId, guildId);
|
||||
|
||||
var result = await _handler.HandleAsync(
|
||||
guildId: guild.Id.ToString(),
|
||||
channelId: Context.Channel.Id.ToString(),
|
||||
guildId: guildId.ToString(),
|
||||
channelId: Context.Channel!.Id.ToString(),
|
||||
userId: Context.User.Id,
|
||||
userDisplayName: Context.User.GlobalName ?? Context.User.Username,
|
||||
resolvedPermissions: resolvedPermissions,
|
||||
guildOwnerId: guild.OwnerId,
|
||||
guildOwnerId: guildOwnerId,
|
||||
sessionId: sessionId,
|
||||
options: parsedOptions,
|
||||
deadline: deadlineResult.Value,
|
||||
CancellationToken.None);
|
||||
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message(
|
||||
$"🗳 Голосование за перенос запущено! Дедлайн: {deadlineResult.Value:yyyy-MM-dd HH:mm} UTC."));
|
||||
_logger.LogInformation("Reschedule voting started for session {SessionId}, proposal {ProposalId}", sessionId, result.ProposalId);
|
||||
|
||||
await Context.Interaction.ModifyResponseAsync(message =>
|
||||
{
|
||||
message.Content = $"🗳 Голосование за перенос запущено! Дедлайн: {deadlineResult.Value:yyyy-MM-dd HH:mm} UTC.";
|
||||
});
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message($":no_entry: {ex.Message}"));
|
||||
_logger.LogWarning(ex, "Unauthorized reschedule attempt by user {UserId}", Context.User.Id);
|
||||
await Context.Interaction.ModifyResponseAsync(message =>
|
||||
{
|
||||
message.Content = $":no_entry: {ex.Message}";
|
||||
});
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message($":warning: {ex.Message}"));
|
||||
_logger.LogWarning(ex, "Invalid reschedule request by user {UserId}", Context.User.Id);
|
||||
await Context.Interaction.ModifyResponseAsync(message =>
|
||||
{
|
||||
message.Content = $":warning: {ex.Message}";
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to initiate reschedule for session {SessionId}", sessionId);
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message(":boom: Ошибка при запуске голосования."));
|
||||
await Context.Interaction.ModifyResponseAsync(message =>
|
||||
{
|
||||
message.Content = ":boom: Ошибка при запуске голосования.";
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static ulong GetResolvedPermissions(NetCord.Gateway.Guild guild, ulong userId)
|
||||
{
|
||||
if (!guild.Users.TryGetValue(userId, out var guildUser))
|
||||
return 0;
|
||||
ulong resolved = 0;
|
||||
foreach (var roleId in guildUser.RoleIds)
|
||||
{
|
||||
if (guild.Roles.TryGetValue(roleId, out var role))
|
||||
resolved |= (ulong)role.Permissions;
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,7 +168,7 @@ public sealed class DiscordSessionInteractionModule(
|
||||
|
||||
private DiscordSessionInteractionInput CreateInput(Guid sessionId)
|
||||
{
|
||||
var guild = Context.Guild
|
||||
var guildId = Context.Interaction.GuildId?.ToString(CultureInfo.InvariantCulture)
|
||||
?? throw new InvalidOperationException("Session buttons can only be used in a guild.");
|
||||
var message = Context.Interaction.Message
|
||||
?? throw new InvalidOperationException("Session button interaction must include a message.");
|
||||
@@ -176,7 +176,7 @@ public sealed class DiscordSessionInteractionModule(
|
||||
return new DiscordSessionInteractionInput(
|
||||
SessionId: sessionId,
|
||||
InteractionId: Context.Interaction.Id.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
GuildId: guild.Id.ToString(CultureInfo.InvariantCulture),
|
||||
GuildId: guildId,
|
||||
ChannelId: Context.Channel.Id.ToString(CultureInfo.InvariantCulture),
|
||||
MessageId: message.Id.ToString(CultureInfo.InvariantCulture),
|
||||
UserId: Context.User.Id,
|
||||
|
||||
@@ -18,8 +18,10 @@ using Microsoft.Extensions.DependencyInjection;
|
||||
using NetCord;
|
||||
using NetCord.Gateway;
|
||||
using NetCord.Hosting.Gateway;
|
||||
using NetCord.Hosting.Services;
|
||||
using NetCord.Hosting.Services.ApplicationCommands;
|
||||
using NetCord.Hosting.Services.ComponentInteractions;
|
||||
using NetCord.Services.ApplicationCommands;
|
||||
using NetCord.Services.ComponentInteractions;
|
||||
using Npgsql;
|
||||
|
||||
@@ -34,6 +36,8 @@ discordOptions.Validate();
|
||||
|
||||
builder.Services.AddSingleton(discordOptions);
|
||||
|
||||
builder.Logging.AddConsole();
|
||||
|
||||
builder.Services.AddSingleton<NpgsqlDataSource>(sp =>
|
||||
{
|
||||
var config = sp.GetRequiredService<IConfiguration>();
|
||||
@@ -82,12 +86,13 @@ builder.Services
|
||||
options.Token = discordOptions.Token;
|
||||
options.Intents = GatewayIntents.Guilds;
|
||||
})
|
||||
.AddApplicationCommands()
|
||||
.AddApplicationCommands<SlashCommandInteraction, SlashCommandContext>()
|
||||
.AddComponentInteractions<ButtonInteraction, ButtonInteractionContext>()
|
||||
.AddGatewayHandlers(typeof(Program).Assembly);
|
||||
|
||||
var host = builder.Build();
|
||||
|
||||
host.AddSlashCommand("ping", "Checks whether GM-Relay Discord is online.", () => "Pong!");
|
||||
host.AddModules(typeof(Program).Assembly);
|
||||
|
||||
await host.RunAsync();
|
||||
|
||||
@@ -73,7 +73,7 @@
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="nav-version">v3.0.0</div>
|
||||
<div class="nav-version">v3.0.8</div>
|
||||
</div>
|
||||
</Authorized>
|
||||
<NotAuthorized>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
@page "/profile"
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using Microsoft.AspNetCore.Components.Authorization
|
||||
@using System.Net.Http.Json
|
||||
@using Microsoft.Extensions.Configuration
|
||||
@attribute [Authorize]
|
||||
@inject IHttpClientFactory HttpClientFactory
|
||||
@inject ISessionStore SessionStore
|
||||
@inject IConfiguration Configuration
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<PageTitle>Профиль — GM-Relay</PageTitle>
|
||||
@@ -55,7 +56,7 @@
|
||||
<h2 class="section-title">Добавить аккаунт</h2>
|
||||
@if (!HasLinkedPlatform("Discord"))
|
||||
{
|
||||
<a class="btn btn-primary" href="/auth/discord">
|
||||
<a href="/auth/discord" class="btn btn-primary">
|
||||
Привязать Discord
|
||||
</a>
|
||||
}
|
||||
@@ -63,6 +64,19 @@
|
||||
{
|
||||
<p class="muted-text">Discord уже привязан.</p>
|
||||
}
|
||||
|
||||
@if (currentPlatform == "Discord" && !HasLinkedPlatform("Telegram"))
|
||||
{
|
||||
var botUsername = Configuration["Telegram__BotUsername"] ?? Configuration["Telegram:BotUsername"];
|
||||
if (!string.IsNullOrWhiteSpace(botUsername))
|
||||
{
|
||||
var authUrl = new Uri(new Uri(Navigation.BaseUri), "auth/telegram").ToString();
|
||||
var widgetHtml = $"<script async src=\"https://telegram.org/js/telegram-widget.js?22\" data-telegram-login=\"{botUsername}\" data-size=\"large\" data-auth-url=\"{authUrl}\" data-request-access=\"write\"></script>";
|
||||
<div class="telegram-widget-wrapper">
|
||||
@((MarkupString)widgetHtml)
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (!string.IsNullOrWhiteSpace(errorMessage))
|
||||
@@ -87,6 +101,12 @@
|
||||
[CascadingParameter]
|
||||
private Task<AuthenticationState>? AuthenticationStateTask { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery]
|
||||
public string? Linked { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "link_error")]
|
||||
public string? LinkError { get; set; }
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
if (AuthenticationStateTask is not null)
|
||||
@@ -100,6 +120,16 @@
|
||||
}
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(Linked))
|
||||
{
|
||||
successMessage = $"{Linked} аккаунт успешно привязан!";
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(LinkError))
|
||||
{
|
||||
errorMessage = $"Ошибка привязки: {Uri.UnescapeDataString(LinkError)}";
|
||||
}
|
||||
|
||||
await LoadIdentities();
|
||||
}
|
||||
|
||||
@@ -107,9 +137,14 @@
|
||||
{
|
||||
try
|
||||
{
|
||||
var http = HttpClientFactory.CreateClient();
|
||||
http.BaseAddress = new Uri(Navigation.BaseUri);
|
||||
identities = await http.GetFromJsonAsync<List<LinkedIdentity>>("api/me/identities");
|
||||
if (currentPlatform is not null && currentExternalUserId is not null)
|
||||
{
|
||||
identities = await SessionStore.GetLinkedIdentitiesAsync(currentPlatform, currentExternalUserId);
|
||||
}
|
||||
else
|
||||
{
|
||||
identities = [];
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -130,19 +165,19 @@
|
||||
|
||||
try
|
||||
{
|
||||
var http = HttpClientFactory.CreateClient();
|
||||
http.BaseAddress = new Uri(Navigation.BaseUri);
|
||||
var response = await http.DeleteAsync($"api/me/identities/{Uri.EscapeDataString(platform)}/{Uri.EscapeDataString(externalUserId)}");
|
||||
if (response.IsSuccessStatusCode)
|
||||
if (currentPlatform is null || currentExternalUserId is null)
|
||||
{
|
||||
successMessage = $"{platform} аккаунт отвязан.";
|
||||
await LoadIdentities();
|
||||
}
|
||||
else
|
||||
{
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
errorMessage = $"Ошибка отвязки: {body}";
|
||||
errorMessage = "Не удалось определить текущего пользователя.";
|
||||
return;
|
||||
}
|
||||
|
||||
await SessionStore.UnlinkIdentityAsync(currentPlatform, currentExternalUserId, platform, externalUserId);
|
||||
successMessage = $"{platform} аккаунт отвязан.";
|
||||
await LoadIdentities();
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
errorMessage = $"Ошибка отвязки: {ex.Message}";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
+30
-10
@@ -61,7 +61,7 @@ builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationSc
|
||||
options.AccessDeniedPath = "/access-denied";
|
||||
options.Cookie.HttpOnly = true;
|
||||
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
|
||||
options.Cookie.SameSite = SameSiteMode.Strict;
|
||||
options.Cookie.SameSite = SameSiteMode.Lax;
|
||||
options.ExpireTimeSpan = TimeSpan.FromDays(7);
|
||||
options.SlidingExpiration = true;
|
||||
});
|
||||
@@ -123,19 +123,39 @@ app.MapHealthChecks("/alive", new HealthCheckOptions
|
||||
});
|
||||
|
||||
// Endpoint to handle Telegram Login callback
|
||||
app.MapGet("/auth/telegram", async (HttpContext context, TelegramAuthService authService) =>
|
||||
app.MapGet("/auth/telegram", async (HttpContext context, TelegramAuthService authService, ISessionStore sessionStore) =>
|
||||
{
|
||||
if (authService.Verify(context.Request.Query, out var telegramId, out var name))
|
||||
if (!authService.Verify(context.Request.Query, out var telegramId, out var name))
|
||||
return Results.Redirect("/login?error=auth_failed");
|
||||
|
||||
await sessionStore.UpsertPlayerAsync("Telegram", telegramId.ToString(System.Globalization.CultureInfo.InvariantCulture), name, null);
|
||||
|
||||
// If already authenticated via another platform, link instead of replacing session
|
||||
if (context.User.Identity?.IsAuthenticated == true
|
||||
&& context.User.TryGetPlatformIdentity(out var currentPlatform, out var currentExternalUserId)
|
||||
&& currentPlatform != "Telegram")
|
||||
{
|
||||
var authProperties = new AuthenticationProperties { IsPersistent = true };
|
||||
await context.SignInAsync(
|
||||
CookieAuthenticationDefaults.AuthenticationScheme,
|
||||
CreateTelegramPrincipal(telegramId, name),
|
||||
authProperties);
|
||||
return Results.Redirect("/");
|
||||
try
|
||||
{
|
||||
// Always make Telegram the primary (it has the historical data/groups)
|
||||
await sessionStore.LinkIdentityAsync(
|
||||
"Telegram", telegramId.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
currentPlatform, currentExternalUserId,
|
||||
name);
|
||||
return Results.Redirect("/profile?linked=telegram");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return Results.Redirect($"/profile?link_error={Uri.EscapeDataString(ex.Message)}");
|
||||
}
|
||||
}
|
||||
|
||||
return Results.Redirect("/login?error=auth_failed");
|
||||
var authProperties = new AuthenticationProperties { IsPersistent = true };
|
||||
await context.SignInAsync(
|
||||
CookieAuthenticationDefaults.AuthenticationScheme,
|
||||
CreateTelegramPrincipal(telegramId, name),
|
||||
authProperties);
|
||||
return Results.Redirect("/");
|
||||
});
|
||||
|
||||
app.MapPost("/auth/telegram-webapp", async (
|
||||
|
||||
@@ -145,7 +145,7 @@ public sealed class DiscordNewSessionHandlerTests
|
||||
var source = File.ReadAllText(commandPath);
|
||||
|
||||
Assert.Contains("DiscordSessionBatchRenderer.Render", source, StringComparison.Ordinal);
|
||||
Assert.Contains("WithEmbeds", source, StringComparison.Ordinal);
|
||||
Assert.Contains("message.Embeds = embeds", source, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static DateTimeOffset FutureDateAt1930()
|
||||
|
||||
@@ -61,7 +61,7 @@ public sealed class DiscordProjectStructureTests
|
||||
var prChecks = File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "pr-checks.yml"));
|
||||
var deploy = File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "deploy.yml"));
|
||||
|
||||
Assert.Contains("gmrelay-discord-bot:3.0.0", compose);
|
||||
Assert.Contains("gmrelay-discord-bot:3.0.8", compose);
|
||||
Assert.Contains("Discord__Token=${DISCORD_BOT_TOKEN:?Set DISCORD_BOT_TOKEN in .env}", compose);
|
||||
Assert.Contains("src/GmRelay.DiscordBot/Dockerfile", deploy);
|
||||
Assert.Contains("DISCORD_BOT_TOKEN", deploy);
|
||||
@@ -75,13 +75,13 @@ public sealed class DiscordProjectStructureTests
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
|
||||
Assert.Contains("<Version>3.0.0</Version>", File.ReadAllText(Path.Combine(repoRoot, "Directory.Build.props")));
|
||||
Assert.Contains("VERSION: 3.0.0", File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "deploy.yml")));
|
||||
Assert.Contains("gmrelay-bot:3.0.0", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
|
||||
Assert.Contains("gmrelay-web:3.0.0", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
|
||||
Assert.Contains("gmrelay-discord-bot:3.0.0", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
|
||||
Assert.Contains("<Version>3.0.8</Version>", File.ReadAllText(Path.Combine(repoRoot, "Directory.Build.props")));
|
||||
Assert.Contains("VERSION: 3.0.8", File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "deploy.yml")));
|
||||
Assert.Contains("gmrelay-bot:3.0.8", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
|
||||
Assert.Contains("gmrelay-web:3.0.8", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
|
||||
Assert.Contains("gmrelay-discord-bot:3.0.8", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
|
||||
Assert.Contains(
|
||||
"v3.0.0",
|
||||
"v3.0.8",
|
||||
File.ReadAllText(Path.Combine(repoRoot, "src", "GmRelay.Web", "Components", "Layout", "NavMenu.razor")));
|
||||
}
|
||||
|
||||
@@ -94,6 +94,16 @@ public sealed class DiscordProjectStructureTests
|
||||
Assert.Contains("DISCORD_BOT_TOKEN", envExample);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Readme_ShouldNotAskForUnusedDiscordBotClientId()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var readme = File.ReadAllText(Path.Combine(repoRoot, "README.md"));
|
||||
|
||||
Assert.DoesNotContain("DISCORD_BOT_CLIENT_ID", readme);
|
||||
Assert.Contains("DISCORD_CLIENT_ID", readme);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Compose_ShouldIncludeDiscordHealthcheck()
|
||||
{
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using GmRelay.DiscordBot.Features.Sessions;
|
||||
using NetCord.Services.ApplicationCommands;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
@@ -47,6 +50,41 @@ public sealed class DiscordStartupTests
|
||||
Assert.Contains(".AddComponentInteractions", program);
|
||||
Assert.Contains(".AddGatewayHandlers", program);
|
||||
Assert.Contains("AddSlashCommand", program);
|
||||
Assert.Contains("AddModules(typeof(Program).Assembly)", program);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(typeof(DiscordNewSessionCommand), "newsession")]
|
||||
[InlineData(typeof(DiscordListSessionsCommand), "listsessions")]
|
||||
[InlineData(typeof(DiscordRescheduleCommand), "reschedule")]
|
||||
public void DiscordSessionSlashCommands_ShouldBeDeclaredOnModuleMethods(Type moduleType, string commandName)
|
||||
{
|
||||
var executeMethod = moduleType.GetMethod("ExecuteAsync", BindingFlags.Instance | BindingFlags.Public);
|
||||
|
||||
Assert.NotNull(executeMethod);
|
||||
|
||||
var methodAttribute = Assert.Single(executeMethod.GetCustomAttributes<SlashCommandAttribute>(inherit: false));
|
||||
var nameProperty = typeof(SlashCommandAttribute).GetProperty("Name")
|
||||
?? throw new InvalidOperationException("SlashCommandAttribute should expose command name.");
|
||||
|
||||
Assert.Equal(commandName, nameProperty.GetValue(methodAttribute));
|
||||
Assert.Empty(moduleType.GetCustomAttributes<SlashCommandAttribute>(inherit: false));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscordSessionSlashCommands_ShouldBeDiscoverableByNetCordService()
|
||||
{
|
||||
var service = new ApplicationCommandService<SlashCommandContext>();
|
||||
|
||||
service.AddModules(typeof(DiscordNewSessionCommand).Assembly);
|
||||
|
||||
var commandNames = service.GetCommands()
|
||||
.Select(command => command.Name)
|
||||
.ToArray();
|
||||
|
||||
Assert.Contains("newsession", commandNames);
|
||||
Assert.Contains("listsessions", commandNames);
|
||||
Assert.Contains("reschedule", commandNames);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Web;
|
||||
|
||||
public sealed class CookieAuthOptionsTests
|
||||
{
|
||||
[Fact]
|
||||
public void CookieAuthOptions_ShouldUseLaxSameSite_ToAllowOAuthCallback()
|
||||
{
|
||||
// Arrange
|
||||
var services = new ServiceCollection();
|
||||
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
||||
.AddCookie(options =>
|
||||
{
|
||||
options.Cookie.HttpOnly = true;
|
||||
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
|
||||
options.Cookie.SameSite = SameSiteMode.Lax;
|
||||
options.ExpireTimeSpan = TimeSpan.FromDays(7);
|
||||
options.SlidingExpiration = true;
|
||||
});
|
||||
|
||||
var provider = services.BuildServiceProvider();
|
||||
var optionsMonitor = provider.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>();
|
||||
var options = optionsMonitor.Get(CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(SameSiteMode.Lax, options.Cookie.SameSite);
|
||||
Assert.True(options.Cookie.HttpOnly);
|
||||
Assert.Equal(CookieSecurePolicy.Always, options.Cookie.SecurePolicy);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user