Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d55003a2a9 | |||
| daa59335cc | |||
| 474e7f62f7 | |||
| 8666b8984e | |||
| d373ff49ba | |||
| 95aad3a2f6 | |||
| 76456cc28a | |||
| ac8f03ecc9 | |||
| 21760ae6f7 | |||
| 5dddf99288 | |||
| 1c75994722 | |||
| c0147fd310 | |||
| 745a65818d | |||
| 05ca8061e9 | |||
| ab59d234f3 | |||
| e791fc2f4a | |||
| cb515b0e05 | |||
| cea6ec801a | |||
| 8e57f8b07a | |||
| e837e191c2 | |||
| df01aa9f3e | |||
| 18e702cd04 | |||
| 5931099c14 | |||
| 8bcd16fbc9 | |||
| 7cecb722d8 | |||
| 11b145a967 | |||
| 105b3c59d7 | |||
| 3bea327043 | |||
| c6aea78ff3 | |||
| 01c49f2df0 | |||
| 9deccd3a9d | |||
| 81d4ec2c97 |
@@ -6,7 +6,7 @@ on:
|
||||
- main
|
||||
|
||||
env:
|
||||
VERSION: 1.15.0
|
||||
VERSION: 2.4.0
|
||||
|
||||
jobs:
|
||||
# ЧАСТЬ 1: Собираем образы и кладем в Gitea (чтобы делиться с ребятами)
|
||||
@@ -37,6 +37,20 @@ jobs:
|
||||
docker push git.codeanddice.ru/toutsu/gmrelay-bot:latest
|
||||
docker push git.codeanddice.ru/toutsu/gmrelay-bot:${{ env.VERSION }}
|
||||
|
||||
- name: Build Discord Bot image
|
||||
run: |
|
||||
docker build \
|
||||
--label "org.opencontainers.image.source=https://git.codeanddice.ru/${{ gitea.repository }}" \
|
||||
-f src/GmRelay.DiscordBot/Dockerfile \
|
||||
-t git.codeanddice.ru/toutsu/gmrelay-discord-bot:latest \
|
||||
-t git.codeanddice.ru/toutsu/gmrelay-discord-bot:${{ env.VERSION }} \
|
||||
.
|
||||
|
||||
- name: Push Discord Bot image
|
||||
run: |
|
||||
docker push git.codeanddice.ru/toutsu/gmrelay-discord-bot:latest
|
||||
docker push git.codeanddice.ru/toutsu/gmrelay-discord-bot:${{ env.VERSION }}
|
||||
|
||||
- name: Build Web image
|
||||
run: |
|
||||
docker build \
|
||||
@@ -68,6 +82,14 @@ jobs:
|
||||
--format table \
|
||||
git.codeanddice.ru/toutsu/gmrelay-bot:${{ env.VERSION }}
|
||||
|
||||
- name: Scan Discord Bot image
|
||||
run: |
|
||||
trivy image \
|
||||
--severity HIGH,CRITICAL \
|
||||
--exit-code 1 \
|
||||
--format table \
|
||||
git.codeanddice.ru/toutsu/gmrelay-discord-bot:${{ env.VERSION }}
|
||||
|
||||
- name: Scan Web image
|
||||
run: |
|
||||
trivy image \
|
||||
@@ -88,6 +110,7 @@ jobs:
|
||||
run: |
|
||||
echo "TELEGRAM_BOT_TOKEN=${{ secrets.TELEGRAM_BOT_TOKEN }}" > .env
|
||||
echo "POSTGRES_PASSWORD=${{ secrets.POSTGRES_PASSWORD }}" >> .env
|
||||
echo "DISCORD_BOT_TOKEN=${{ secrets.DISCORD_BOT_TOKEN }}" >> .env
|
||||
echo "TELEGRAM_BOT_USERNAME=${{ secrets.TELEGRAM_BOT_USERNAME }}" >> .env
|
||||
echo "TELEGRAM_MINI_APP_URL=${{ secrets.TELEGRAM_MINI_APP_URL }}" >> .env
|
||||
|
||||
@@ -97,7 +120,7 @@ jobs:
|
||||
docker login git.codeanddice.ru/ -u toutsu -p ${{ secrets.GIT_TOKEN }}
|
||||
|
||||
# Pull гарантирует, что мы получили нужную версию.
|
||||
docker compose pull bot web
|
||||
docker compose pull bot discord web
|
||||
|
||||
# Запускаем! Флаг -d оставит их работать в фоне.
|
||||
docker compose up -d
|
||||
|
||||
@@ -69,6 +69,9 @@ jobs:
|
||||
- name: Build Bot (compile check, includes SAST)
|
||||
run: dotnet build src/GmRelay.Bot/GmRelay.Bot.csproj --no-restore
|
||||
|
||||
- name: Build Discord Bot (compile check, includes SAST)
|
||||
run: dotnet build src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj --no-restore
|
||||
|
||||
- name: Build Web (compile check, includes SAST)
|
||||
run: dotnet build src/GmRelay.Web/GmRelay.Web.csproj --no-restore
|
||||
|
||||
|
||||
@@ -1,343 +0,0 @@
|
||||
# Issue #15: Session Audit Log Implementation Plan
|
||||
|
||||
> **For Hermes:** Use subagent-driven-development skill to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Add transparent audit history for every session change, visible to GM in Web Dashboard.
|
||||
|
||||
**Architecture:** PostgreSQL audit table + Dapper queries. Automatic logging inside mutating SessionService methods. New Razor page for GM history view.
|
||||
|
||||
**Tech Stack:** C# 12, Blazor SSR, Dapper, PostgreSQL, xUnit.
|
||||
|
||||
**Branch:** `issue-15-session-audit-log` (includes mobile UI bugfix cherry-pick)
|
||||
|
||||
**Version Bump:** `1.10.1` → `1.10.2`
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Database Migration (V013)
|
||||
|
||||
**Objective:** Create `session_audit_log` table.
|
||||
|
||||
**File:** Create `src/GmRelay.Bot/Migrations/V013__add_session_audit_log.sql`
|
||||
|
||||
```sql
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
|
||||
CREATE TABLE session_audit_log (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
||||
actor_telegram_id BIGINT NOT NULL,
|
||||
actor_name VARCHAR(255) NOT NULL,
|
||||
change_type VARCHAR(50) NOT NULL,
|
||||
CHECK (change_type IN ('Title','Time','Link','MaxPlayers','Status','WaitlistPromote','PlayerRemoved','BatchRescheduled','Cancelled')),
|
||||
old_value TEXT,
|
||||
new_value TEXT,
|
||||
changed_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX ix_session_audit_log_session_id ON session_audit_log(session_id);
|
||||
CREATE INDEX ix_session_audit_log_changed_at ON session_audit_log(changed_at);
|
||||
```
|
||||
|
||||
**Step 2:** Verify migration compiles: `psql $DATABASE_URL -f src/GmRelay.Bot/Migrations/V013__add_session_audit_log.sql` (optional, CI will test)
|
||||
|
||||
**Step 3:** Commit: `git add src/GmRelay.Bot/Migrations/V013__add_session_audit_log.sql && git commit -m "chore(#15): add session_audit_log migration"`
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Domain Model & Interface Methods
|
||||
|
||||
**Objective:** Add `SessionAuditLogEntry` record and two new methods to `ISessionStore`.
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Web/Services/ISessionStore.cs`
|
||||
- Modify: `src/GmRelay.Web/Services/SessionService.cs`
|
||||
|
||||
**Step 1: Add record to ISessionStore.cs** (after PlayerAttendanceStats)
|
||||
|
||||
```csharp
|
||||
public sealed record SessionAuditLogEntry(
|
||||
Guid Id,
|
||||
Guid SessionId,
|
||||
long ActorTelegramId,
|
||||
string ActorName,
|
||||
string ChangeType,
|
||||
string? OldValue,
|
||||
string? NewValue,
|
||||
DateTime ChangedAt
|
||||
);
|
||||
```
|
||||
|
||||
**Step 2: Add methods to ISessionStore interface**
|
||||
|
||||
```csharp
|
||||
Task LogSessionChangeAsync(Guid sessionId, long actorTelegramId, string actorName, string changeType, string? oldValue, string? newValue);
|
||||
Task<List<SessionAuditLogEntry>> GetSessionHistoryAsync(Guid sessionId);
|
||||
```
|
||||
|
||||
**Step 3: Implement in SessionService.cs**
|
||||
|
||||
```csharp
|
||||
public async Task LogSessionChangeAsync(Guid sessionId, long actorTelegramId, string actorName, string changeType, string? oldValue, string? newValue)
|
||||
{
|
||||
using var connection = new NpgsqlConnection(connectionString);
|
||||
await connection.ExecuteAsync(
|
||||
"INSERT INTO session_audit_log (session_id, actor_telegram_id, actor_name, change_type, old_value, new_value) VALUES (@sessionId, @actorTelegramId, @actorName, @changeType, @oldValue, @newValue)",
|
||||
new { sessionId, actorTelegramId, actorName, changeType, oldValue, newValue });
|
||||
}
|
||||
|
||||
public async Task<List<SessionAuditLogEntry>> GetSessionHistoryAsync(Guid sessionId)
|
||||
{
|
||||
using var connection = new NpgsqlConnection(connectionString);
|
||||
var entries = await connection.QueryAsync<SessionAuditLogEntry>(
|
||||
"SELECT id, session_id as SessionId, actor_telegram_id as ActorTelegramId, actor_name as ActorName, change_type as ChangeType, old_value as OldValue, new_value as NewValue, changed_at as ChangedAt FROM session_audit_log WHERE session_id = @sessionId ORDER BY changed_at DESC",
|
||||
new { sessionId });
|
||||
return entries.ToList();
|
||||
}
|
||||
```
|
||||
|
||||
**Step 4:** Commit: `git add -A && git commit -m "feat(#15): add SessionAuditLogEntry and audit store methods"`
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Instrument Mutating Methods
|
||||
|
||||
**Objective:** Auto-log changes in key methods. Only log when value actually changes.
|
||||
|
||||
**File:** Modify `src/GmRelay.Web/Services/SessionService.cs`
|
||||
|
||||
**Step 1: Instrument UpdateSessionAsync**
|
||||
|
||||
Before executing UPDATE, read current session. After UPDATE, compare and log each changed field:
|
||||
|
||||
```csharp
|
||||
// After var currentSession = await GetSessionAsync(sessionId);
|
||||
// Before the UPDATE SQL:
|
||||
|
||||
if (currentSession is not null)
|
||||
{
|
||||
if (currentSession.Title != title)
|
||||
await LogSessionChangeAsync(sessionId, /* actor will be passed from caller */ ...);
|
||||
}
|
||||
```
|
||||
|
||||
**Problem:** SessionService doesn't know the actor (GM) telegram ID. Solution: add `long actorTelegramId` parameter to mutating methods, or use a decorator pattern.
|
||||
|
||||
**Better approach:** Instrument in `AuthorizedSessionService` which already has `gmId`. That is the authorized wrapper.
|
||||
|
||||
**Revised approach:** Add `IAuditLogger` interface and inject it. Or simpler: change `ISessionStore` mutating methods to accept `long actorTelegramId` and `string actorName` as last parameters.
|
||||
|
||||
**Simpler approach for this plan:** Since all mutating methods in `ISessionStore` are called through `AuthorizedSessionService`, instrument in `AuthorizedSessionService` methods AFTER the underlying `SessionService` call. BUT we need old values.
|
||||
|
||||
**Final approach:** Change `ISessionStore` methods to include `actorTelegramId` parameter, and inside `SessionService` fetch old values and log.
|
||||
|
||||
Let's add `long actorTelegramId` parameter to:
|
||||
- `UpdateSessionAsync`
|
||||
- `PromoteWaitlistedPlayerAsync`
|
||||
- `RemovePlayerFromSessionAsync`
|
||||
- `RescheduleBatchAsync`
|
||||
|
||||
Wait, this is a bigger change. Let's be more pragmatic: add a new `IAuditService` that can be called from `AuthorizedSessionService` after mutations. `IAuditService` just wraps `ISessionStore.LogSessionChangeAsync`.
|
||||
|
||||
Actually, simplest: add `actorTelegramId` and `actorName` parameters to `LogSessionChangeAsync` and call it from `AuthorizedSessionService` after each mutation. For old/new values, read the session before mutation in AuthorizedSessionService.
|
||||
|
||||
**Plan:**
|
||||
- `AuthorizedSessionService.UpdateSessionForGmAsync`: read session before update, call update, then log differences.
|
||||
- Same pattern for other mutating methods.
|
||||
|
||||
**Step 1: Read current session in AuthorizedSessionService.UpdateSessionForGmAsync**
|
||||
|
||||
```csharp
|
||||
public async Task UpdateSessionForGmAsync(Guid sessionId, long gmId, string title, DateTime scheduledAt, string joinLink, int? maxPlayers)
|
||||
{
|
||||
var groupId = await EnforceSessionOwnershipAsync(sessionId, gmId);
|
||||
var before = await store.GetSessionAsync(sessionId); // add this
|
||||
await store.UpdateSessionAsync(sessionId, groupId, title, scheduledAt, joinLink, maxPlayers);
|
||||
if (before is not null)
|
||||
{
|
||||
if (before.Title != title)
|
||||
await store.LogSessionChangeAsync(sessionId, gmId, "ГМ", "Title", before.Title, title);
|
||||
if (before.ScheduledAt != scheduledAt)
|
||||
await store.LogSessionChangeAsync(sessionId, gmId, "ГМ", "Time", before.ScheduledAt.ToString("O"), scheduledAt.ToString("O"));
|
||||
if (before.JoinLink != joinLink)
|
||||
await store.LogSessionChangeAsync(sessionId, gmId, "ГМ", "Link", before.JoinLink, joinLink);
|
||||
if (before.MaxPlayers != maxPlayers)
|
||||
await store.LogSessionChangeAsync(sessionId, gmId, "ГМ", "MaxPlayers", before.MaxPlayers?.ToString(), maxPlayers?.ToString());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Wait, `EnforceSessionOwnershipAsync` returns `groupId` but we need it. Let me check the current AuthorizedSessionService code... We saw earlier it does `await EnforceSessionOwnershipAsync(sessionId, gmId)` then calls `store.UpdateSessionAsync`.
|
||||
|
||||
Actually, looking at the compact output from earlier, `AuthorizedSessionService` has `EnforceSessionOwnershipAsync` as a private helper. Let me verify.
|
||||
|
||||
From the compact output of AuthorizedSessionService earlier:
|
||||
```
|
||||
public async Task UpdateSessionForGmAsync(Guid sessionId, long gmId, string title, DateTime scheduledAt, string joinLink, int? maxPlayers)
|
||||
{
|
||||
var groupId = await EnforceSessionOwnershipAsync(sessionId, gmId);
|
||||
await store.UpdateSessionAsync(sessionId, groupId, title, scheduledAt, joinLink, maxPlayers);
|
||||
}
|
||||
```
|
||||
|
||||
So it DOES return groupId. Perfect.
|
||||
|
||||
But we need actor name. We can use the GM's display name from `GetGroupManagementForGmAsync` or just hardcode "ГМ" for now. Or we can query the player name. For simplicity, use "ГМ" + telegram ID, or query the player display name.
|
||||
|
||||
Actually, let's query the GM name from the group or just use telegram ID as identifier. Since this is audit log, having human-readable name is better. We can pass `actorName` to the log method.
|
||||
|
||||
Simpler: In `AuthorizedSessionService`, after `EnforceSessionOwnershipAsync`, we already know the group. We can get the GM name from group or just use a generic "ГМ" label. Actually, the telegram ID is sufficient for audit, and the display name can be resolved later in the UI.
|
||||
|
||||
Let's just log `actor_telegram_id` and use "ГМ" as actor_name. Or better, query the player display name if needed.
|
||||
|
||||
For this plan, let's keep it simple: log with `gmId` as actor_telegram_id and `"ГМ"` as actor_name. The UI can resolve the name.
|
||||
|
||||
**Step 2: Instrument all mutating AuthorizedSessionService methods**
|
||||
|
||||
Do this for:
|
||||
- `UpdateSessionForGmAsync` (Title, Time, Link, MaxPlayers)
|
||||
- `RescheduleBatchForGmAsync` (BatchRescheduled)
|
||||
- `PromoteWaitlistedPlayerForGmAsync` (WaitlistPromote)
|
||||
- `RemovePlayerFromSessionForGmAsync` (PlayerRemoved)
|
||||
- `UpdateBatchDetailsForGmAsync` (Title, Link)
|
||||
- `UpdateBatchNotificationModeForGmAsync` (maybe skip, internal)
|
||||
- `DeleteSessionHandler` in Bot features (Cancelled) — this is in Bot layer, not Web
|
||||
|
||||
For Cancelled status, we need to instrument `CancelSessionHandler` in Bot. But the Bot handlers don't use `ISessionStore` directly... they use `SessionService` or direct SQL. Let me check.
|
||||
|
||||
Actually, for this plan, focus on Web layer mutations first. Bot layer can be a follow-up.
|
||||
|
||||
**Step 3: Commit:** `git add -A && git commit -m "feat(#15): instrument audit logging in AuthorizedSessionService"`
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Web Page - SessionHistory.razor
|
||||
|
||||
**Objective:** GM-visible timeline of session changes.
|
||||
|
||||
**Files:**
|
||||
- Create: `src/GmRelay.Web/Components/Pages/SessionHistory.razor`
|
||||
- Modify: `src/GmRelay.Web/Components/Pages/GroupDetails.razor` (add "История" link)
|
||||
- Modify: `src/GmRelay.Web/Components/Pages/EditSession.razor` (add "История" link)
|
||||
|
||||
**Step 1: Create SessionHistory.razor**
|
||||
|
||||
Route: `@page "/session/{SessionId:guid}/history"`
|
||||
|
||||
Layout: table with columns: Время, Актор, Тип изменения, Было, Стало.
|
||||
|
||||
Colors: use existing CSS variables.
|
||||
|
||||
**Step 2: Add navigation links**
|
||||
|
||||
In GroupDetails.razor sessions table: add 📜 История column/link.
|
||||
In EditSession.razor: add button "📜 История изменений" linking to `/session/{SessionId}/history`.
|
||||
|
||||
**Step 3: Commit:** `git add -A && git commit -m "feat(#15): add SessionHistory.razor page with audit timeline"`
|
||||
|
||||
---
|
||||
|
||||
## Task 5: FakeSessionStore + TDD Tests
|
||||
|
||||
**Objective:** Test audit logging. RED-GREEN-REFACTOR.
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/GmRelay.Bot.Tests/Web/AuthorizedSessionServiceTests.cs`
|
||||
|
||||
**Step 1: RED — Write failing test**
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public async Task UpdateSessionForGmAsync_LogsAudit_WhenTitleChanges()
|
||||
{
|
||||
var gmId = 1001L;
|
||||
var groupId = Guid.NewGuid();
|
||||
var sessionId = Guid.NewGuid();
|
||||
var store = new FakeSessionStore(
|
||||
groups: [new(groupId, 42, "Alpha", gmId)],
|
||||
sessions: [new(sessionId, groupId, "Session A", DateTime.UtcNow, "Planned", "https://example.test/a", Guid.NewGuid(), 10, 42, 4, 1, 0)]);
|
||||
var service = new AuthorizedSessionService(store);
|
||||
|
||||
await service.UpdateSessionForGmAsync(sessionId, gmId, "Updated Title", DateTime.UtcNow.AddDays(1), "https://example.test/b", 5);
|
||||
|
||||
Assert.Single(store.LogEntries);
|
||||
Assert.Equal("Title", store.LogEntries[0].ChangeType);
|
||||
Assert.Equal("Session A", store.LogEntries[0].OldValue);
|
||||
Assert.Equal("Updated Title", store.LogEntries[0].NewValue);
|
||||
}
|
||||
```
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/Web/AuthorizedSessionServiceTests.cs --filter "FullyQualifiedName~LogsAudit" -v n`
|
||||
Expected: FAIL (FakeSessionStore doesn't have LogSessionChangeAsync / LogEntries)
|
||||
|
||||
**Step 2: GREEN — Add to FakeSessionStore**
|
||||
|
||||
Add `List<SessionAuditLogEntry> LogEntries` and implement `LogSessionChangeAsync` / `GetSessionHistoryAsync`.
|
||||
|
||||
**Step 3: Refactor — Add more tests**
|
||||
|
||||
- No audit when values unchanged
|
||||
- Audit for time change
|
||||
- Audit for link change
|
||||
- Audit for max players change
|
||||
- GetSessionHistoryAsync returns entries ordered by time desc
|
||||
|
||||
**Step 4: Full suite**
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj`
|
||||
Expected: all pass
|
||||
|
||||
**Step 5: Commit:** `git add -A && git commit -m "test(#15): add audit logging TDD tests"`
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Bump Version & Docs
|
||||
|
||||
**Objective:** Update version and documentation.
|
||||
|
||||
**Files:**
|
||||
- Modify: `Directory.Build.props`
|
||||
- Modify: `compose.yaml`
|
||||
- Modify: `README.md`
|
||||
- Modify: Wiki «Руководство ГМа»
|
||||
|
||||
**Step 1: Bump version to 1.10.2**
|
||||
|
||||
**Step 2: Update README** — add "📜 История изменений сессии" bullet in Web Dashboard section.
|
||||
|
||||
**Step 3: Update wiki** — add subsection «Журнал действий» with description of how to access `/session/{id}/history`, what change types are tracked, and how to read the timeline.
|
||||
|
||||
**Step 4: Commit:** `git add -A && git commit -m "docs(#15): bump version to 1.10.2 and add audit log docs"`
|
||||
|
||||
---
|
||||
|
||||
## Task 7: Push & PR
|
||||
|
||||
**Step 1:** `git push origin issue-15-session-audit-log`
|
||||
|
||||
**Step 2:** Create PR via `mcp_gitea_pull_request_write`
|
||||
|
||||
**Step 3:** Wait CI (`mcp_gitea_actions_run_read`)
|
||||
|
||||
**Step 4:** Merge PR
|
||||
|
||||
**Step 5:** Create tag `v1.10.2` and release
|
||||
|
||||
---
|
||||
|
||||
## Verification Checklist
|
||||
|
||||
- [ ] Migration V013 applied successfully
|
||||
- [ ] `SessionAuditLogEntry` record defined in `ISessionStore.cs`
|
||||
- [ ] `LogSessionChangeAsync` and `GetSessionHistoryAsync` implemented in `SessionService.cs`
|
||||
- [ ] `AuthorizedSessionService` logs on value changes only
|
||||
- [ ] `SessionHistory.razor` renders timeline for GM
|
||||
- [ ] Links from GroupDetails and EditSession pages
|
||||
- [ ] `FakeSessionStore` implements audit methods
|
||||
- [ ] TDD tests: RED → GREEN → all pass
|
||||
- [ ] Full `dotnet test` suite: all pass
|
||||
- [ ] Version bumped to 1.10.2
|
||||
- [ ] README and wiki updated
|
||||
- [ ] CI run success
|
||||
- [ ] PR merged to main
|
||||
- [ ] Tag `v1.10.2` created
|
||||
- [ ] Release published
|
||||
@@ -1,480 +0,0 @@
|
||||
# Issue #19: выровнять /newsession с batch-сценарием лендинга — Implementation Plan
|
||||
|
||||
> **For Hermes:** Use subagent-driven-development skill to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Убедиться, что Telegram UX `/newsession` полностью соответствует batch-сценарию лендинга: мастер одной командой создаёт несколько дат, указывает лимит мест и ссылку, получает единую карточку с действиями. Обеспечить покрытие acceptance criteria регрессионными тестами и устранить найденные расхождения.
|
||||
|
||||
**Architecture:** Сценарий уже реализован в `CreateSessionHandler` + `NewSessionCommandParser` + `SessionBatchRenderer`. Основная задача — добавить недостающие тесты на «точный» landing-сценарий (несколько явных дат, не recurring), проверить отсутствие частичных сессий при любых ошибках, и убедиться, что карточка содержит все обещанные элементы.
|
||||
|
||||
**Tech Stack:** .NET 10, xUnit, Dapper, Npgsql, Telegram.Bot, Native AOT.
|
||||
|
||||
---
|
||||
|
||||
## Контекст кодовой базы
|
||||
|
||||
- `src/GmRelay.Bot/Features/Sessions/CreateSession/CreateSessionHandler.cs` — создание batch, транзакция БД, отправка карточки.
|
||||
- `src/GmRelay.Bot/Features/Sessions/CreateSession/NewSessionCommandParser.cs` — парсинг команды: несколько `Время:`, `Мест:`, `Ссылка:`, `Картинка:`, recurring (`Игр:` + `Интервал:`).
|
||||
- `src/GmRelay.Shared/Rendering/SessionBatchRenderer.cs` — рендеринг HTML-карточки с кнопками.
|
||||
- `src/GmRelay.Shared/Rendering/BatchMessageEditor.cs` — редактирование batch-сообщения (text/photo).
|
||||
- `src/GmRelay.Bot/Infrastructure/Telegram/UpdateRouter.cs` — роутинг команд, текст `/help`.
|
||||
- `tests/GmRelay.Bot.Tests/Features/Sessions/CreateSession/NewSessionCommandParserTests.cs` — тесты парсера.
|
||||
- `tests/GmRelay.Bot.Tests/Features/Landing/TelegramLandingPromisesSmokeTests.cs` — smoke-тест всего landing-флоу через `FakeTelegramMessenger`.
|
||||
- `tests/GmRelay.Bot.Tests/Rendering/SessionBatchRendererTests.cs` — тесты рендерера.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: RED — тест landing-парсинга с несколькими явными датами
|
||||
|
||||
**Objective:** Проверить, что парсер корректно обрабатывает точный формат из лендинга: 2+ явных даты, лимит мест, ссылка, без recurring.
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/GmRelay.Bot.Tests/Features/Sessions/CreateSession/NewSessionCommandParserTests.cs`
|
||||
|
||||
**Step 1: Write failing test**
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void Parse_ShouldHandleLandingBatchWithMultipleExplicitDates()
|
||||
{
|
||||
var nowUtc = new DateTimeOffset(2026, 4, 23, 12, 0, 0, TimeSpan.Zero);
|
||||
var text = """
|
||||
/newsession
|
||||
Название: Landing Batch Game
|
||||
Время: 15.05.2026 19:30
|
||||
Время: 22.05.2026 19:30
|
||||
Мест: 4
|
||||
Ссылка: https://example.test/landing
|
||||
""";
|
||||
|
||||
var result = NewSessionCommandParser.Parse(text, nowUtc);
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
Assert.Equal("Landing Batch Game", result.Title);
|
||||
Assert.Equal("https://example.test/landing", result.Link);
|
||||
Assert.Equal(4, result.MaxPlayers);
|
||||
Assert.Equal(2, result.ScheduledTimes.Count);
|
||||
Assert.Equal(new DateTimeOffset(2026, 5, 15, 16, 30, 0, TimeSpan.Zero), result.ScheduledTimes[0]);
|
||||
Assert.Equal(new DateTimeOffset(2026, 5, 22, 16, 30, 0, TimeSpan.Zero), result.ScheduledTimes[1]);
|
||||
Assert.Empty(result.PastTimeInputs);
|
||||
Assert.Empty(result.InvalidTimeInputs);
|
||||
Assert.Empty(result.InvalidSeatLimitInputs);
|
||||
Assert.Empty(result.InvalidRecurringInputs);
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2: Run test to verify failure**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/ --filter "FullyQualifiedName~Parse_ShouldHandleLandingBatchWithMultipleExplicitDates" -v n`
|
||||
|
||||
Expected: PASS (функциональность уже реализована, но теста не было). Если FAIL — исправить парсер перед продолжением.
|
||||
|
||||
**Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add tests/GmRelay.Bot.Tests/Features/Sessions/CreateSession/NewSessionCommandParserTests.cs
|
||||
git commit -m "test(#19): landing batch parser test with multiple explicit dates"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: RED — тест рендеринга landing-карточки
|
||||
|
||||
**Objective:** Проверить, что `SessionBatchRenderer` для landing-сценария выводит название, все даты, лимит, заполненность и кнопки записи/выхода.
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/GmRelay.Bot.Tests/Rendering/SessionBatchRendererTests.cs`
|
||||
|
||||
**Step 1: Write failing test**
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void Render_ShouldProduceLandingBatchCardWithAllRequiredElements()
|
||||
{
|
||||
var sessionId1 = Guid.NewGuid();
|
||||
var sessionId2 = Guid.NewGuid();
|
||||
var sessions = new[]
|
||||
{
|
||||
new SessionBatchDto(sessionId1, new DateTime(2026, 5, 15, 16, 30, 0, DateTimeKind.Utc), SessionStatus.Planned, 4),
|
||||
new SessionBatchDto(sessionId2, new DateTime(2026, 5, 22, 16, 30, 0, DateTimeKind.Utc), SessionStatus.Planned, 4)
|
||||
};
|
||||
var participants = new[]
|
||||
{
|
||||
new ParticipantBatchDto(sessionId1, "Alice", "alice", ParticipantRegistrationStatus.Active),
|
||||
new ParticipantBatchDto(sessionId1, "Bob", null, ParticipantRegistrationStatus.Active),
|
||||
new ParticipantBatchDto(sessionId2, "Charlie", "charlie", ParticipantRegistrationStatus.Waitlisted)
|
||||
};
|
||||
|
||||
var result = SessionBatchRenderer.Render("Landing Batch Game", sessions, participants);
|
||||
var text = result.Text;
|
||||
var buttons = result.Markup.InlineKeyboard.SelectMany(row => row).ToList();
|
||||
|
||||
Assert.Contains("Landing Batch Game", text);
|
||||
Assert.Contains("15 мая 2026, 19:30", text);
|
||||
Assert.Contains("22 мая 2026, 19:30", text);
|
||||
Assert.Contains("Места: 2/4", text);
|
||||
Assert.Contains("Места: 0/4", text);
|
||||
Assert.Contains("@alice", text);
|
||||
Assert.Contains("Bob", text);
|
||||
Assert.Contains("Лист ожидания (1)", text);
|
||||
Assert.Contains("@charlie", text);
|
||||
|
||||
Assert.Equal(4, buttons.Count);
|
||||
Assert.Contains($"join_session:{sessionId1}", buttons.Select(b => b.CallbackData));
|
||||
Assert.Contains($"leave_session:{sessionId1}", buttons.Select(b => b.CallbackData));
|
||||
Assert.Contains($"join_session:{sessionId2}", buttons.Select(b => b.CallbackData));
|
||||
Assert.Contains($"leave_session:{sessionId2}", buttons.Select(b => b.CallbackData));
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2: Run test to verify failure**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/ --filter "FullyQualifiedName~Render_ShouldProduceLandingBatchCardWithAllRequiredElements" -v n`
|
||||
|
||||
Expected: PASS (рендерер уже реализован, тест отсутствовал).
|
||||
|
||||
**Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add tests/GmRelay.Bot.Tests/Rendering/SessionBatchRendererTests.cs
|
||||
git commit -m "test(#19): landing batch renderer card elements test"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: RED — тест «ошибки ввода не создают частичных сессий»
|
||||
|
||||
**Objective:** Убедиться, что при невалидном вводе `CreateSessionHandler` не создаёт ни одной записи в БД и не публикует карточку.
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/GmRelay.Bot.Tests/Features/Sessions/CreateSession/CreateSessionHandlerTests.cs`
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/CreateSession/CreateSessionHandler.cs` (если найдена уязвимость)
|
||||
|
||||
**Step 1: Write failing test**
|
||||
|
||||
```csharp
|
||||
using GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Features.Sessions.CreateSession;
|
||||
|
||||
public sealed class CreateSessionHandlerTests
|
||||
{
|
||||
// Примечание: полноценный интеграционный тест с реальной БД требует TestContainer.
|
||||
// Для Native AOT проекта используем подход с in-memory фейком через рефакторинг хендлера.
|
||||
// Ниже — тест-спецификация, которую реализуем через FakeDataSource или рефакторинг.
|
||||
}
|
||||
```
|
||||
|
||||
Поскольку `CreateSessionHandler` напрямую зависит от `NpgsqlDataSource` и `ITelegramBotClient`, для unit-тестирования нужно либо:
|
||||
а) использовать интеграционный тест с PostgreSQL (TestContainers), либо
|
||||
б) рефакторить хендлер, выделив `ISessionRepository`.
|
||||
|
||||
**Рекомендуемый подход (YAGNI):** добавить интеграционный тест в smoke-стиле через `FakeTelegramMessenger`, дополнив `TelegramLandingSmokeScenario` сценарием «invalid command does not publish anything».
|
||||
|
||||
**Step 1 (реализация):** Дописать тест в `TelegramLandingPromisesSmokeTests.cs`:
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void Smoke_InvalidNewSession_ShouldNotPublishAnySessions()
|
||||
{
|
||||
var nowUtc = new DateTimeOffset(2026, 5, 1, 12, 0, 0, TimeSpan.Zero);
|
||||
var invalidText = """
|
||||
/newsession
|
||||
Название: Bad Game
|
||||
Время: 01.01.2020 19:30
|
||||
"""; // нет ссылки
|
||||
|
||||
var parseResult = NewSessionCommandParser.Parse(invalidText, nowUtc);
|
||||
|
||||
Assert.False(parseResult.IsValid);
|
||||
Assert.Empty(parseResult.ScheduledTimes);
|
||||
// Убеждаемся, что smoke-сценарий не может быть опубликован
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
TelegramLandingSmokeScenario.Publish(parseResult, SessionNotificationMode.GroupAndDirect));
|
||||
}
|
||||
```
|
||||
|
||||
В `TelegramLandingSmokeScenario.Publish` добавить guard:
|
||||
```csharp
|
||||
if (!parseResult.IsValid)
|
||||
throw new InvalidOperationException("Cannot publish invalid parse result");
|
||||
```
|
||||
|
||||
**Step 2: Run test to verify failure**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/ --filter "FullyQualifiedName~Smoke_InvalidNewSession_ShouldNotPublishAnySessions" -v n`
|
||||
|
||||
Expected: FAIL — guard ещё не добавлен.
|
||||
|
||||
**Step 3: Write minimal implementation**
|
||||
|
||||
Добавить guard в `TelegramLandingSmokeScenario.Publish`:
|
||||
```csharp
|
||||
if (!parseResult.IsValid)
|
||||
throw new InvalidOperationException("Cannot publish invalid parse result");
|
||||
```
|
||||
|
||||
**Step 4: Run test to verify pass**
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
**Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add tests/GmRelay.Bot.Tests/Features/Landing/TelegramLandingPromisesSmokeTests.cs
|
||||
git add src/GmRelay.Bot/... # если были изменения
|
||||
# (файл CreateSessionHandler.cs не трогаем — валидация происходит ДО транзакции)
|
||||
git commit -m "test(#19): ensure invalid parse does not publish partial sessions"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: RED — тест atomicity при сбое отправки batch-сообщения
|
||||
|
||||
**Objective:** В `CreateSessionHandler` `batch_message_id` обновляется ПОСЛЕ `transaction.Commit()`. Если отправка сообщения в Telegram падает, сессии созданы, но `batch_message_id` не записан — игроки не увидят карточку. Нужно либо доказать, что это обработано, либо исправить.
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/CreateSession/CreateSessionHandler.cs`
|
||||
|
||||
**Step 1: Анализ кода**
|
||||
|
||||
Текущий порядок в `CreateSessionHandler`:
|
||||
1. Валидация (до транзакции) ✓
|
||||
2. `BEGIN TRANSACTION`
|
||||
3. INSERT players, groups, sessions
|
||||
4. `COMMIT`
|
||||
5. `SessionBatchRenderer.Render`
|
||||
6. `botClient.SendMessage/SendPhoto`
|
||||
7. `UPDATE sessions SET batch_message_id = ...` (вне транзакции!)
|
||||
|
||||
Если шаг 6 падает — сессии «висят» без published message. Это частичное создание.
|
||||
|
||||
**Step 2: Write minimal fix**
|
||||
|
||||
Обернуть отправку сообщения и обновление `batch_message_id` в retry-loop с fallback. Если после N попыток не удалось — отправить GM уведомление об ошибке и оставить сессии (не удалять, чтобы не терять данные), но сделать так, чтобы `batch_message_id` обновлялся только при успешной отправке.
|
||||
|
||||
```csharp
|
||||
// Внутри CreateSessionHandler, после Commit:
|
||||
Message? batchMessage = null;
|
||||
var sendAttempts = 0;
|
||||
const int maxAttempts = 3;
|
||||
Exception? lastSendException = null;
|
||||
|
||||
while (batchMessage is null && sendAttempts < maxAttempts)
|
||||
{
|
||||
sendAttempts++;
|
||||
try
|
||||
{
|
||||
batchMessage = await SendBatchMessageAsync(...); // extracted method
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
lastSendException = ex;
|
||||
logger.LogWarning(ex, "Attempt {Attempt} failed to send batch message for {BatchId}", sendAttempts, batchId);
|
||||
if (sendAttempts < maxAttempts)
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
if (batchMessage is not null)
|
||||
{
|
||||
await connection.ExecuteAsync(
|
||||
"UPDATE sessions SET batch_message_id = @MsgId WHERE batch_id = @BatchId",
|
||||
new { MsgId = batchMessage.MessageId, BatchId = batchId });
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogError(lastSendException, "Failed to send batch message for {BatchId} after {MaxAttempts} attempts", batchId, maxAttempts);
|
||||
await botClient.SendMessage(
|
||||
chatId,
|
||||
$"⚠️ Сессии созданы, но не удалось опубликовать карточку. Пожалуйста, используйте /listsessions.\n\nОшибка: {lastSendException?.Message}",
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
```
|
||||
|
||||
**Step 3: Extract helper**
|
||||
|
||||
Выделить метод `SendBatchMessageAsync` из текущего inline-кода отправки (строки 117–176 в текущем файле), чтобы логика была читаемой и тестируемой.
|
||||
|
||||
**Step 4: Run tests**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/ -v n`
|
||||
|
||||
Expected: все существующие тесты PASS, новая логика не ломает smoke-тест (т.к. smoke-тест не использует реальный `CreateSessionHandler`).
|
||||
|
||||
**Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/GmRelay.Bot/Features/Sessions/CreateSession/CreateSessionHandler.cs
|
||||
git commit -m "fix(#19): retry batch message send and prevent orphaned sessions without batch_message_id"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: RED — smoke-тест полного landing-сценария с явными датами
|
||||
|
||||
**Objective:** Дополнить `TelegramLandingPromisesSmokeTests` полным сквозным сценарием: парсинг → публикация → запись → выход → проверка карточки.
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/GmRelay.Bot.Tests/Features/Landing/TelegramLandingPromisesSmokeTests.cs`
|
||||
|
||||
**Step 1: Write failing test**
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void Smoke_LandingExplicitDatesBatch_ShouldSupportFullLifecycle()
|
||||
{
|
||||
var nowUtc = new DateTimeOffset(2026, 5, 1, 12, 0, 0, TimeSpan.Zero);
|
||||
var text = """
|
||||
/newsession
|
||||
Название: Landing Explicit Batch
|
||||
Время: 15.05.2026 19:30
|
||||
Время: 22.05.2026 19:30
|
||||
Мест: 3
|
||||
Ссылка: https://example.test/explicit
|
||||
""";
|
||||
|
||||
var parseResult = NewSessionCommandParser.Parse(text, nowUtc);
|
||||
Assert.True(parseResult.IsValid);
|
||||
Assert.Equal(2, parseResult.ScheduledTimes.Count);
|
||||
Assert.Equal(3, parseResult.MaxPlayers);
|
||||
|
||||
var scenario = TelegramLandingSmokeScenario.Publish(parseResult, SessionNotificationMode.GroupAndDirect);
|
||||
Assert.Contains("Landing Explicit Batch", scenario.LastMessage.Text);
|
||||
Assert.Contains("15 мая 2026, 19:30", scenario.LastMessage.Text);
|
||||
Assert.Contains("22 мая 2026, 19:30", scenario.LastMessage.Text);
|
||||
Assert.Contains("Места: 0/3", scenario.LastMessage.Text);
|
||||
|
||||
var callbacks = CallbackData(scenario.LastMessage.Markup);
|
||||
Assert.Equal(4, callbacks.Count); // join+leave для каждой из 2 сессий
|
||||
|
||||
var firstSessionId = scenario.Sessions[0].Id;
|
||||
var alice = scenario.Join(firstSessionId, 1001, "Alice", "alice");
|
||||
var bob = scenario.Join(firstSessionId, 1002, "Bob", "bob");
|
||||
var carol = scenario.Join(firstSessionId, 1003, "Carol", "carol");
|
||||
|
||||
Assert.Equal(ParticipantRegistrationStatus.Active, scenario.RegistrationStatus(firstSessionId, alice));
|
||||
Assert.Equal(ParticipantRegistrationStatus.Active, scenario.RegistrationStatus(firstSessionId, bob));
|
||||
Assert.Equal(ParticipantRegistrationStatus.Waitlisted, scenario.RegistrationStatus(firstSessionId, carol));
|
||||
Assert.Contains("Места: 2/3", scenario.LastMessage.Text);
|
||||
Assert.Contains("@alice", scenario.LastMessage.Text);
|
||||
Assert.Contains("@bob", scenario.LastMessage.Text);
|
||||
Assert.Contains("@carol", scenario.LastMessage.Text);
|
||||
|
||||
scenario.Leave(firstSessionId, alice);
|
||||
Assert.False(scenario.HasParticipant(firstSessionId, alice));
|
||||
Assert.Equal(ParticipantRegistrationStatus.Active, scenario.RegistrationStatus(firstSessionId, carol));
|
||||
Assert.DoesNotContain("@alice", scenario.LastMessage.Text);
|
||||
Assert.Contains("@carol", scenario.LastMessage.Text);
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2: Run test to verify failure**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/ --filter "FullyQualifiedName~Smoke_LandingExplicitDatesBatch_ShouldSupportFullLifecycle" -v n`
|
||||
|
||||
Expected: PASS (функциональность уже существует, тест добавляет регрессионное покрытие).
|
||||
|
||||
**Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add tests/GmRelay.Bot.Tests/Features/Landing/TelegramLandingPromisesSmokeTests.cs
|
||||
git commit -m "test(#19): full lifecycle smoke test for explicit-dates landing batch"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Проверка и обновление `/help` текста
|
||||
|
||||
**Objective:** Убедиться, что текст `/help` точно отражает landing-формат и упоминает batch-сценарий.
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Bot/Infrastructure/Telegram/UpdateRouter.cs`
|
||||
|
||||
**Step 1: Read current `/help` text**
|
||||
|
||||
Текущий `/help` уже содержит:
|
||||
```
|
||||
/newsession
|
||||
Название: My Game
|
||||
Время: 15.05.2026 19:30
|
||||
Время: 22.05.2026 19:30
|
||||
Мест: 4
|
||||
Ссылка: https://link
|
||||
Картинка: https://cover
|
||||
|
||||
Для регулярного расписания можно указать одну дату:
|
||||
Игр: 4
|
||||
Интервал: 7
|
||||
```
|
||||
|
||||
**Step 2: Verify alignment**
|
||||
|
||||
- Формат совпадает с лендингом ✓
|
||||
- Упоминается `Мест:` ✓
|
||||
- Упоминается несколько `Время:` ✓
|
||||
- Упоминается `Ссылка:` ✓
|
||||
|
||||
Никаких изменений не требуется. Если тестировщик считает, что help недостаточно явно описывает batch-сценарий — добавить заголовок:
|
||||
```
|
||||
<b>Создать набор сессий (batch):</b>
|
||||
```
|
||||
|
||||
**Step 3: Commit (если изменения были)**
|
||||
|
||||
```bash
|
||||
git add src/GmRelay.Bot/Infrastructure/Telegram/UpdateRouter.cs
|
||||
git commit -m "docs(#19): clarify batch scenario in /help text"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Финальный прогон и cleanup
|
||||
|
||||
**Objective:** Убедиться, что все тесты проходят, нет warnings, и план соответствует acceptance criteria.
|
||||
|
||||
**Files:**
|
||||
- Все изменённые файлы
|
||||
|
||||
**Step 1: Run full test suite**
|
||||
|
||||
```bash
|
||||
dotnet test tests/GmRelay.Bot.Tests/ -v n
|
||||
```
|
||||
|
||||
Expected: все тесты PASS.
|
||||
|
||||
**Step 2: Verify checklist**
|
||||
|
||||
- [ ] `Parse_ShouldHandleLandingBatchWithMultipleExplicitDates` — PASS
|
||||
- [ ] `Render_ShouldProduceLandingBatchCardWithAllRequiredElements` — PASS
|
||||
- [ ] `Smoke_InvalidNewSession_ShouldNotPublishAnySessions` — PASS
|
||||
- [ ] `Smoke_LandingExplicitDatesBatch_ShouldSupportFullLifecycle` — PASS
|
||||
- [ ] Все существующие тесты — PASS
|
||||
- [ ] `CreateSessionHandler` обрабатывает сбой отправки batch-сообщения (retry + fallback)
|
||||
- [ ] `/help` текст соответствует landing-формату
|
||||
- [ ] Никаких новых warnings при сборке
|
||||
|
||||
**Step 3: Commit финальный**
|
||||
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "feat(#19): align /newsession with landing batch scenario — tests + atomicity fix"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Acceptance Criteria Verification
|
||||
|
||||
| Критерий | Статус | Покрытие |
|
||||
|---|---|---|
|
||||
| Мастер может создать batch из нескольких дат | ✅ Реализовано | Task 1, Task 5 |
|
||||
| Карточка содержит название, даты, лимит, заполненность, действия | ✅ Реализовано | Task 2, Task 5 |
|
||||
| Ошибки ввода не создают частичных сессий | ✅ Реализовано (валидация до транзакции) | Task 3 |
|
||||
| Сбой публикации карточки не оставляет «висячие» сессии без `batch_message_id` | 🔄 Фиксится | Task 4 |
|
||||
|
||||
## Execution Handoff
|
||||
|
||||
Plan complete and saved to `.hermes/plans/gmrelay-issue-19.md`. Ready to execute using subagent-driven-development — dispatch a fresh subagent per task with two-stage review (spec compliance then code quality). Shall I proceed?
|
||||
@@ -0,0 +1,144 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Build, Test, and Development Commands
|
||||
|
||||
This is a .NET 10 solution using the modern XML-based `.slnx` format. The global SDK version is `10.0.100` with `rollForward: latestFeature`.
|
||||
|
||||
**Build the solution:**
|
||||
```bash
|
||||
dotnet build
|
||||
```
|
||||
|
||||
**Build individual projects (the CI does this to include SAST via SecurityCodeScan):**
|
||||
```bash
|
||||
dotnet build src/GmRelay.Shared/GmRelay.Shared.csproj --no-restore
|
||||
dotnet build src/GmRelay.Bot/GmRelay.Bot.csproj --no-restore
|
||||
dotnet build src/GmRelay.Web/GmRelay.Web.csproj --no-restore
|
||||
```
|
||||
|
||||
**Run all tests:**
|
||||
```bash
|
||||
dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --verbosity normal
|
||||
```
|
||||
|
||||
**Run a single test class or method:**
|
||||
```bash
|
||||
dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter "FullyQualifiedName~YourTestClassName"
|
||||
```
|
||||
|
||||
**Lint and format:**
|
||||
```bash
|
||||
dotnet format --verify-no-changes --verbosity diagnostic # CI enforcement
|
||||
dotnet format # Apply fixes
|
||||
```
|
||||
|
||||
**Check for vulnerable packages:**
|
||||
```bash
|
||||
dotnet list package --vulnerable --include-transitive
|
||||
```
|
||||
|
||||
**Restore with lock file verification:**
|
||||
The repo enforces `RestorePackagesWithLockFile=true`. After adding or updating packages, commit the updated `packages.lock.json` files or the Trivy scan in CI will fail.
|
||||
|
||||
**Run locally with Aspire (dev orchestration):**
|
||||
```bash
|
||||
dotnet run --project src/GmRelay.AppHost/GmRelay.AppHost.csproj
|
||||
```
|
||||
This automatically starts PostgreSQL in a container, the Bot, and the Web dashboard.
|
||||
|
||||
**Run locally with Docker Compose (production-like):**
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# Edit .env with your TELEGRAM_BOT_TOKEN, TELEGRAM_BOT_USERNAME, POSTGRES_PASSWORD
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
## High-Level Architecture
|
||||
|
||||
### Project Roles and Runtime Model
|
||||
|
||||
| Project | Runtime | Key Trait |
|
||||
|---|---|---|
|
||||
| `GmRelay.Bot` | `Microsoft.NET.Sdk.Worker` | **Native AOT** binary. Telegram long polling bot + stateless scheduler. |
|
||||
| `GmRelay.Web` | `Microsoft.NET.Sdk.Web` | Blazor Server dashboard. Cookie auth via Telegram Login Widget / Mini App `initData`. |
|
||||
| `GmRelay.Shared` | Plain library | Domain models and platform-neutral view builders. **Must not depend on `Telegram.Bot`**. |
|
||||
| `GmRelay.ServiceDefaults` | Aspire shared project | OpenTelemetry, health checks, HTTP resilience. Referenced by both Bot and Web. |
|
||||
| `GmRelay.AppHost` | Aspire orchestrator | Dev-only. Spins up PostgreSQL and wires Bot + Web with service discovery. |
|
||||
|
||||
**Important:** `README.md` references `GmRelay.Migrator` and `GmRelay.Worker`, but these projects do not exist. Migrations (`DbUp`) and background workers (`BackgroundService`) live inside `GmRelay.Bot`.
|
||||
|
||||
### Vertical Slice Architecture with Explicit DI
|
||||
|
||||
Each use case is a self-contained vertical slice: a C# record (Command/Query) + Handler class with all logic (SQL, Telegram API calls, validation). There are no abstract repository interfaces or service layers.
|
||||
|
||||
Because the Bot is compiled as Native AOT (`PublishAot=true`, `EnableTrimAnalyzer=true`), **all DI registrations are explicit** in `src/GmRelay.Bot/Program.cs`. There is no assembly scanning or reflection-based discovery. When adding a new handler, you must register it manually in Program.cs.
|
||||
|
||||
### Database Access: Npgsql + Dapper.AOT + DbUp
|
||||
|
||||
**No EF Core** — it is incompatible with Native AOT. The stack is:
|
||||
- **Npgsql** ADO.NET for connections.
|
||||
- **Dapper 2.1.72** with **Dapper.AOT 1.0.48** for compile-time source-generated mapping (AOT-safe).
|
||||
- **DbUp 7.0.1** for migrations. SQL scripts are embedded resources in `src/GmRelay.Bot/Migrations/` (V001 through V015).
|
||||
- `DbMigrator.MigrateUp()` runs on every Bot startup.
|
||||
|
||||
Both Bot and Web share the same PostgreSQL database. Web registers `NpgsqlDataSource` via `builder.AddNpgsqlDataSource("gmrelaydb")` (Aspire integration), while Bot registers it manually to avoid reflection-based Aspire configuration at AOT time.
|
||||
|
||||
### Platform-Neutral Rendering (ADR-002)
|
||||
|
||||
Rendering is split into two stages:
|
||||
1. **View Builder** (`GmRelay.Shared`) — platform-agnostic view model from domain DTOs.
|
||||
2. **Platform Renderer** — `TelegramSessionBatchRenderer` lives in both `GmRelay.Bot` and `GmRelay.Web` (temporary duplication until a third Telegram consumer justifies extracting `GmRelay.Shared.Telegram`).
|
||||
|
||||
This means `GmRelay.Shared` must remain free of `Telegram.Bot` types. If you need to add rendering logic that produces `InlineKeyboardMarkup`, it belongs in the Bot or Web project, not Shared.
|
||||
|
||||
### Stateless Scheduling
|
||||
|
||||
The session scheduler (`SessionSchedulerService`) is a `BackgroundService` with a `PeriodicTimer(TimeSpan.FromMinutes(1))`. On each tick it queries PostgreSQL for sessions needing action (T-24h confirmation, T-5min join link) and updates their status. There is no in-memory state — the database is the single source of truth. This design was chosen specifically because Quartz.NET is incompatible with Native AOT.
|
||||
|
||||
### Health Checks
|
||||
|
||||
- **Bot:** Custom `BotHealthCheckHostedService` listens on port 8081. The Docker health check hits `localhost:8081/health`.
|
||||
- **Web:** Standard ASP.NET Core health checks on `/health` (JSON response with status and timestamp) and `/alive` (liveness probe tag filter). Exposed via `GmRelay.ServiceDefaults`.
|
||||
|
||||
### Authentication and Security
|
||||
|
||||
- **Telegram Login Widget** and **Mini App `initData`** verification via HMAC-SHA256. Cookie auth is hardened (`HttpOnly`, `SecurePolicy.Always`, `SameSite.Strict`).
|
||||
- Web Data Protection keys are persisted to `/app/dataprotection-keys` (Docker volume `web_keys`).
|
||||
- Security headers middleware (`X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`) is applied globally in Web.
|
||||
- `SecurityCodeScan.VS2019` (5.6.7) is included in all projects via `Directory.Build.props` for SAST at build time.
|
||||
- Connection string passwords are redacted in logs via `SecretRedactor`.
|
||||
|
||||
### CI/CD Pipeline
|
||||
|
||||
`.gitea/workflows/pr-checks.yml` runs on every PR to `main`:
|
||||
1. `dotnet restore`
|
||||
2. Verify `packages.lock.json` files exist for Trivy
|
||||
3. `dotnet format --verify-no-changes`
|
||||
4. `dotnet list package --vulnerable`
|
||||
5. Trivy filesystem scan (`vuln,misconfig,secret`, HIGH/CRITICAL)
|
||||
6. Build Shared → Bot → Web
|
||||
7. Run tests
|
||||
|
||||
`.gitea/workflows/deploy.yml` runs on push to `main`:
|
||||
1. Build and push `gmrelay-bot` and `gmrelay-web` images to `git.codeanddice.ru/toutsu/...`
|
||||
2. Trivy image scan on both images (HIGH/CRITICAL, exit-code 1)
|
||||
3. Create `.env` from secrets and run `docker compose up -d`
|
||||
|
||||
### Environment Configuration
|
||||
|
||||
Key environment variables (see `.env.example`):
|
||||
- `TELEGRAM_BOT_TOKEN`, `TELEGRAM_BOT_USERNAME`, `TELEGRAM_MINI_APP_URL`
|
||||
- `POSTGRES_PASSWORD`
|
||||
- `GMRELAY_WEB_PORT` (default 8080)
|
||||
- `ConnectionStrings__gmrelaydb` — used by both Bot and Web
|
||||
|
||||
The Bot reads config as `Telegram:BotToken` (colon) which maps from `Telegram__BotToken` (double underscore) via environment variables.
|
||||
|
||||
### Docker Images
|
||||
|
||||
- **Bot:** Multi-stage Dockerfile. Build stage uses `sdk:10.0-noble` with `clang` and `zlib1g-dev` for AOT compilation. Final stage uses `runtime-deps:10.0-noble`. Exposes 8081.
|
||||
- **Web:** Multi-stage Dockerfile. Build stage uses `sdk:10.0-noble`. Final stage uses `aspnet:10.0-noble` with `libgssapi-krb5-2` and `wget`. Exposes 8080.
|
||||
|
||||
Both images are built for multi-arch (`linux/amd64`, `linux/arm64`) to support Raspberry Pi 5 (ARM64) deployment.
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Version>1.15.0</Version>
|
||||
<Version>2.4.0</Version>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>preview</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
<Folder Name="/src/">
|
||||
<Project Path="src/GmRelay.AppHost/GmRelay.AppHost.csproj" />
|
||||
<Project Path="src/GmRelay.Bot/GmRelay.Bot.csproj" />
|
||||
<Project Path="src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj" />
|
||||
<Project Path="src/GmRelay.ServiceDefaults/GmRelay.ServiceDefaults.csproj" />
|
||||
<Project Path="src/GmRelay.Web/GmRelay.Web.csproj" />
|
||||
</Folder>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Toutsu
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
IN THE SOFTWARE.
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
Проект разработан с упором на производительность, архитектуру Vertical Slice, Native AOT (для бота) и удобство развертывания с использованием .NET Aspire.
|
||||
|
||||
**Текущая версия:** `v1.15.0`.
|
||||
**Текущая версия:** `v2.2.0`.
|
||||
|
||||
---
|
||||
|
||||
@@ -47,7 +47,7 @@
|
||||
|---|---|
|
||||
| Язык | C# 14 (.NET 10) |
|
||||
| Архитектура | Vertical Slice + общая библиотека `GmRelay.Shared` |
|
||||
| Бот | Telegram.Bot, **Native AOT** |
|
||||
| Боты | Telegram.Bot (**Native AOT**), NetCord Gateway (Discord worker) |
|
||||
| Веб | Blazor Server |
|
||||
| Оркестрация | .NET Aspire (`GmRelay.AppHost`) |
|
||||
| БД | PostgreSQL |
|
||||
@@ -74,6 +74,9 @@ cp .env.example .env
|
||||
# Токен от @BotFather (используется ботом и как секретный ключ веб-авторизации)
|
||||
TELEGRAM_BOT_TOKEN=ваш_токен_здесь
|
||||
|
||||
# Токен Discord application bot
|
||||
DISCORD_BOT_TOKEN=ваш_discord_токен_здесь
|
||||
|
||||
# Имя бота без @ (для Telegram Login Widget)
|
||||
TELEGRAM_BOT_USERNAME=ваше_имя_бота_здесь
|
||||
|
||||
@@ -98,6 +101,7 @@ docker compose up -d
|
||||
- создание Docker-сети и volume PostgreSQL;
|
||||
- подъём PostgreSQL (`db:5432`);
|
||||
- запуск бота с плавной миграцией (DbUp);
|
||||
- запуск отдельного Discord Gateway worker на NetCord;
|
||||
- запуск веб-приложения с подключением к БД и Telegram API.
|
||||
|
||||
### 3. Первоначальная настройка
|
||||
@@ -151,11 +155,10 @@ BACKUP_VOLUME_NAME=game_pgbackups
|
||||
├── src/
|
||||
│ ├── GmRelay.AppHost/ # .NET Aspire orchestrator
|
||||
│ ├── GmRelay.Bot/ # Telegram-бот (Native AOT)
|
||||
│ ├── GmRelay.Migrator/ # DbUp-миграции
|
||||
│ ├── GmRelay.DiscordBot/ # Discord Gateway worker на NetCord
|
||||
│ ├── GmRelay.ServiceDefaults/ # Aspire service defaults
|
||||
│ ├── GmRelay.Shared/ # Общие доменные модели
|
||||
│ ├── GmRelay.Web/ # Blazor Server dashboard
|
||||
│ └── GmRelay.Worker/ # Background workers
|
||||
│ └── GmRelay.Web/ # Blazor Server dashboard
|
||||
├── tests/
|
||||
│ └── GmRelay.Bot.Tests/ # xUnit + NSubstitute
|
||||
├── compose.yaml # Docker Compose (AMD64 + ARM64)
|
||||
|
||||
+24
-2
@@ -49,7 +49,7 @@ services:
|
||||
crond -f
|
||||
|
||||
bot:
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-bot:1.15.0
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-bot:2.4.0
|
||||
restart: always
|
||||
depends_on:
|
||||
db:
|
||||
@@ -60,9 +60,26 @@ services:
|
||||
- "Telegram__MiniAppUrl=${TELEGRAM_MINI_APP_URL:-}"
|
||||
networks:
|
||||
- gmrelay
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -qO- http://localhost:8081/health || exit 1"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
discord:
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-discord-bot:2.4.0
|
||||
restart: always
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
- "ConnectionStrings__gmrelaydb=Host=db;Port=5432;Database=gmrelay_db;Username=gmrelay;Password=${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}"
|
||||
- "Discord__Token=${DISCORD_BOT_TOKEN:?Set DISCORD_BOT_TOKEN in .env}"
|
||||
networks:
|
||||
- gmrelay
|
||||
|
||||
web:
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-web:1.15.0
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-web:2.4.0
|
||||
restart: always
|
||||
depends_on:
|
||||
db:
|
||||
@@ -78,6 +95,11 @@ services:
|
||||
- web_keys:/app/dataprotection-keys
|
||||
networks:
|
||||
- gmrelay
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -qO- http://localhost:8080/health || exit 1"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
|
||||
@@ -0,0 +1,560 @@
|
||||
# Platform Messenger Contracts Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Implement issue #24 by adding platform-neutral platform identity and messaging contracts, then routing the Telegram session flows through a Telegram adapter without changing Telegram behavior.
|
||||
|
||||
**Architecture:** Keep update routing and Telegram update parsing at the `GmRelay.Bot.Infrastructure.Telegram` boundary, but move outbound messaging decisions behind `GmRelay.Shared.Platform.IPlatformMessenger`. `GmRelay.Shared` owns platform-neutral DTOs and contracts; `GmRelay.Bot` owns `TelegramPlatformMessenger`, which translates neutral requests into `Telegram.Bot` calls and reuses the existing Telegram renderers/editing rules.
|
||||
|
||||
**Tech Stack:** .NET 10, C# preview, xUnit, Dapper.AOT constraints, Telegram.Bot in `GmRelay.Bot` only, platform-neutral shared contracts in `GmRelay.Shared`.
|
||||
|
||||
---
|
||||
|
||||
## Issue Context
|
||||
|
||||
- Gitea issue: #24, `refactor: ввести PlatformKind, PlatformUser, PlatformGroup и IPlatformMessenger`
|
||||
- Labels: `area:bot`, `area:platform`, `area:shared`, `platform:multi`, `type:refactor`, `pending-approval`
|
||||
- Acceptance criteria:
|
||||
- New contracts live in a platform-neutral layer.
|
||||
- Telegram flow goes through the adapter without behavior changes.
|
||||
- A future DiscordBot can reference the contract without depending on Telegram assemblies.
|
||||
|
||||
## Proposed Version Bump
|
||||
|
||||
Current version is `2.0.0` in:
|
||||
|
||||
- `Directory.Build.props`
|
||||
- `compose.yaml`
|
||||
- `.gitea/workflows/deploy.yml`
|
||||
- `src/GmRelay.Web/Components/Layout/NavMenu.razor`
|
||||
|
||||
Issue label is `type:refactor`; per workflow rules this is not a major bump and has no user-facing feature label. Proposed bump: `2.0.0` -> `2.0.1`.
|
||||
|
||||
## Files
|
||||
|
||||
- Create: `src/GmRelay.Shared/Platform/PlatformKind.cs`
|
||||
- Create: `src/GmRelay.Shared/Platform/PlatformUser.cs`
|
||||
- Create: `src/GmRelay.Shared/Platform/PlatformGroup.cs`
|
||||
- Create: `src/GmRelay.Shared/Platform/PlatformMessageContracts.cs`
|
||||
- Create: `src/GmRelay.Shared/Platform/IPlatformMessenger.cs`
|
||||
- Create: `src/GmRelay.Bot/Infrastructure/Telegram/TelegramPlatformMessenger.cs`
|
||||
- Create: `tests/GmRelay.Bot.Tests/Platform/PlatformContractsTests.cs`
|
||||
- Create: `tests/GmRelay.Bot.Tests/Infrastructure/Telegram/TelegramPlatformMessengerSourceTests.cs`
|
||||
- Modify: `src/GmRelay.Bot/Program.cs`
|
||||
- Modify: `src/GmRelay.Bot/Features/Notifications/DirectSessionNotificationSender.cs`
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/CreateSession/JoinSessionHandler.cs`
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/CreateSession/LeaveSessionHandler.cs`
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/CreateSession/CancelSessionHandler.cs`
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/CreateSession/PromoteWaitlistedPlayerHandler.cs`
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/RescheduleSession/InitiateRescheduleHandler.cs`
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/RescheduleSession/HandleRescheduleTimeInputHandler.cs`
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/RescheduleSession/HandleRescheduleVoteHandler.cs`
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/RescheduleSession/RescheduleVotingDeadlineService.cs`
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/ExportCalendar/ExportCalendarHandler.cs`
|
||||
- Modify: version files listed above
|
||||
|
||||
## Design
|
||||
|
||||
### Shared Contracts
|
||||
|
||||
`PlatformKind` is a sentinel enum where `Max` is not a sendable platform:
|
||||
|
||||
```csharp
|
||||
namespace GmRelay.Shared.Platform;
|
||||
|
||||
public enum PlatformKind
|
||||
{
|
||||
Telegram = 0,
|
||||
Discord = 1,
|
||||
Max = 2
|
||||
}
|
||||
```
|
||||
|
||||
`PlatformUser` and `PlatformGroup` carry external platform identity while keeping current Telegram IDs representable as strings:
|
||||
|
||||
```csharp
|
||||
namespace GmRelay.Shared.Platform;
|
||||
|
||||
public sealed record PlatformUser(
|
||||
PlatformKind Platform,
|
||||
string ExternalUserId,
|
||||
string DisplayName,
|
||||
string? ExternalUsername);
|
||||
|
||||
public sealed record PlatformGroup(
|
||||
PlatformKind Platform,
|
||||
string ExternalGroupId,
|
||||
string DisplayName,
|
||||
string? ExternalChannelId = null,
|
||||
string? ExternalThreadId = null);
|
||||
```
|
||||
|
||||
Outbound message contracts stay independent of Telegram/Discord SDK types:
|
||||
|
||||
```csharp
|
||||
using GmRelay.Shared.Rendering;
|
||||
|
||||
namespace GmRelay.Shared.Platform;
|
||||
|
||||
public sealed record PlatformMessageRef(
|
||||
PlatformKind Platform,
|
||||
string ExternalGroupId,
|
||||
string? ExternalThreadId,
|
||||
string ExternalMessageId);
|
||||
|
||||
public sealed record PlatformMessageAction(
|
||||
string Key,
|
||||
string Label,
|
||||
string Payload);
|
||||
|
||||
public sealed record PlatformScheduleMessage(
|
||||
PlatformGroup Group,
|
||||
SessionBatchViewModel View,
|
||||
PlatformMessageRef? ExistingMessage,
|
||||
string? ImageReference = null);
|
||||
|
||||
public sealed record PlatformPrivateMessage(
|
||||
PlatformUser Recipient,
|
||||
string HtmlText);
|
||||
|
||||
public sealed record PlatformInteractionReply(
|
||||
string InteractionId,
|
||||
string Text,
|
||||
bool ShowAlert = false);
|
||||
|
||||
public sealed record PlatformCalendarFile(
|
||||
PlatformGroup Group,
|
||||
string FileName,
|
||||
byte[] Content,
|
||||
string CaptionHtml,
|
||||
IReadOnlyList<PlatformMessageAction> Actions);
|
||||
```
|
||||
|
||||
`IPlatformMessenger` exposes the required outward operations:
|
||||
|
||||
```csharp
|
||||
namespace GmRelay.Shared.Platform;
|
||||
|
||||
public interface IPlatformMessenger
|
||||
{
|
||||
Task<PlatformMessageRef> SendScheduleAsync(PlatformScheduleMessage message, CancellationToken ct);
|
||||
Task UpdateScheduleAsync(PlatformScheduleMessage message, CancellationToken ct);
|
||||
Task SendGroupMessageAsync(PlatformGroup group, string htmlText, CancellationToken ct);
|
||||
Task SendPrivateMessageAsync(PlatformPrivateMessage message, CancellationToken ct);
|
||||
Task AnswerInteractionAsync(PlatformInteractionReply reply, CancellationToken ct);
|
||||
Task SendCalendarFileAsync(PlatformCalendarFile file, CancellationToken ct);
|
||||
}
|
||||
```
|
||||
|
||||
### Telegram Adapter
|
||||
|
||||
`TelegramPlatformMessenger` lives in `GmRelay.Bot.Infrastructure.Telegram`, depends on `ITelegramBotClient`, and translates neutral DTOs to existing Telegram calls:
|
||||
|
||||
- `SendScheduleAsync` renders `SessionBatchViewModel` with `TelegramSessionBatchRenderer.Render`.
|
||||
- `UpdateScheduleAsync` calls `BatchMessageEditor.EditBatchMessageAsync`.
|
||||
- `SendGroupMessageAsync` calls `SendMessage` with `ParseMode.Html` and optional `messageThreadId`.
|
||||
- `SendPrivateMessageAsync` calls `SendMessage` to `PlatformUser.ExternalUserId`.
|
||||
- `AnswerInteractionAsync` calls `AnswerCallbackQuery`.
|
||||
- `SendCalendarFileAsync` calls `SendDocument` and maps URL actions to inline keyboard buttons.
|
||||
|
||||
### Handler Scope
|
||||
|
||||
Refactor outbound Telegram calls in these flows to `IPlatformMessenger`:
|
||||
|
||||
- Join/leave/promote waitlist schedule updates and callback replies.
|
||||
- Cancel schedule update, group cancellation message, direct notification and callback reply.
|
||||
- Reschedule initiation, voting message updates, immediate reschedule schedule update, direct notifications and callback replies.
|
||||
- Export calendar file sending.
|
||||
|
||||
Keep Telegram inbound DTOs at the boundary for now:
|
||||
|
||||
- `UpdateRouter` still receives `Telegram.Bot.Types.Update`.
|
||||
- Text message parsing in reschedule input still receives `Telegram.Bot.Types.Message`.
|
||||
- `CreateSessionHandler` can keep photo/topic creation via `ITelegramBotClient` because issue #24 targets outbound schedule/interaction/private/calendar contract, not replacing all Telegram update primitives in one PR.
|
||||
|
||||
## Tasks
|
||||
|
||||
### Task 1: RED - Shared Contract Tests
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/GmRelay.Bot.Tests/Platform/PlatformContractsTests.cs`
|
||||
|
||||
- [ ] **Step 1: Write failing tests for neutral contracts**
|
||||
|
||||
```csharp
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Platform;
|
||||
|
||||
public sealed class PlatformContractsTests
|
||||
{
|
||||
[Fact]
|
||||
public void PlatformKind_ShouldDefineTelegramDiscordAndMaxSentinel()
|
||||
{
|
||||
Assert.Equal(0, (int)PlatformKind.Telegram);
|
||||
Assert.Equal(1, (int)PlatformKind.Discord);
|
||||
Assert.Equal(2, (int)PlatformKind.Max);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PlatformContracts_ShouldBeTelegramAssemblyFree()
|
||||
{
|
||||
var contractTypes = new[]
|
||||
{
|
||||
typeof(PlatformUser),
|
||||
typeof(PlatformGroup),
|
||||
typeof(PlatformMessageRef),
|
||||
typeof(PlatformMessageAction),
|
||||
typeof(PlatformScheduleMessage),
|
||||
typeof(PlatformPrivateMessage),
|
||||
typeof(PlatformInteractionReply),
|
||||
typeof(PlatformCalendarFile),
|
||||
typeof(IPlatformMessenger)
|
||||
};
|
||||
|
||||
Assert.All(contractTypes, type =>
|
||||
Assert.DoesNotContain(
|
||||
"Telegram",
|
||||
string.Join(" ", type.Assembly.GetReferencedAssemblies().Select(value => value.Name)),
|
||||
StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PlatformScheduleMessage_ShouldCarrySharedViewModelWithoutPlatformTypes()
|
||||
{
|
||||
var sessionId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
|
||||
var view = SessionBatchViewBuilder.Build(
|
||||
"Campaign",
|
||||
[new SessionBatchDto(sessionId, new DateTime(2026, 5, 15, 16, 0, 0, DateTimeKind.Utc), "Planned", 4, "https://example.test/game")],
|
||||
[]);
|
||||
var group = new PlatformGroup(PlatformKind.Discord, "guild-1", "Guild", "channel-1", "thread-1");
|
||||
|
||||
var message = new PlatformScheduleMessage(group, view, ExistingMessage: null);
|
||||
|
||||
Assert.Equal(PlatformKind.Discord, message.Group.Platform);
|
||||
Assert.Same(view, message.View);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests and verify RED**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter PlatformContractsTests
|
||||
```
|
||||
|
||||
Expected: compile failure because `GmRelay.Shared.Platform` types do not exist.
|
||||
|
||||
### Task 2: GREEN - Add Shared Contracts
|
||||
|
||||
**Files:**
|
||||
- Create: `src/GmRelay.Shared/Platform/PlatformKind.cs`
|
||||
- Create: `src/GmRelay.Shared/Platform/PlatformUser.cs`
|
||||
- Create: `src/GmRelay.Shared/Platform/PlatformGroup.cs`
|
||||
- Create: `src/GmRelay.Shared/Platform/PlatformMessageContracts.cs`
|
||||
- Create: `src/GmRelay.Shared/Platform/IPlatformMessenger.cs`
|
||||
|
||||
- [ ] **Step 1: Add the contract files exactly as described in the Design section**
|
||||
- [ ] **Step 2: Run PlatformContractsTests and verify GREEN**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter PlatformContractsTests
|
||||
```
|
||||
|
||||
Expected: `Passed`.
|
||||
|
||||
### Task 3: RED - Adapter and Flow Source Tests
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/GmRelay.Bot.Tests/Infrastructure/Telegram/TelegramPlatformMessengerSourceTests.cs`
|
||||
|
||||
- [ ] **Step 1: Write source tests for adapter wiring and target flows**
|
||||
|
||||
```csharp
|
||||
namespace GmRelay.Bot.Tests.Infrastructure.Telegram;
|
||||
|
||||
public sealed class TelegramPlatformMessengerSourceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Program_ShouldRegisterTelegramPlatformMessenger()
|
||||
{
|
||||
var program = await ReadRepositoryFileAsync("src/GmRelay.Bot/Program.cs");
|
||||
|
||||
Assert.Contains("IPlatformMessenger", program, StringComparison.Ordinal);
|
||||
Assert.Contains("TelegramPlatformMessenger", program, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/CreateSession/JoinSessionHandler.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/CreateSession/LeaveSessionHandler.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/CreateSession/CancelSessionHandler.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/CreateSession/PromoteWaitlistedPlayerHandler.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/RescheduleSession/InitiateRescheduleHandler.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/RescheduleSession/HandleRescheduleTimeInputHandler.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/RescheduleSession/HandleRescheduleVoteHandler.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/RescheduleSession/RescheduleVotingDeadlineService.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/ExportCalendar/ExportCalendarHandler.cs")]
|
||||
public async Task SessionFlows_ShouldUsePlatformMessengerForOutboundTelegramWork(string relativePath)
|
||||
{
|
||||
var source = await ReadRepositoryFileAsync(relativePath);
|
||||
|
||||
Assert.Contains("IPlatformMessenger", source, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("BatchMessageEditor.EditBatchMessageAsync", source, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(".AnswerCallbackQuery(", source, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TelegramPlatformMessenger_ShouldOwnTelegramBotClientCalls()
|
||||
{
|
||||
var source = await ReadRepositoryFileAsync("src/GmRelay.Bot/Infrastructure/Telegram/TelegramPlatformMessenger.cs");
|
||||
|
||||
Assert.Contains("ITelegramBotClient", source, StringComparison.Ordinal);
|
||||
Assert.Contains("BatchMessageEditor.EditBatchMessageAsync", source, StringComparison.Ordinal);
|
||||
Assert.Contains("AnswerCallbackQuery", source, StringComparison.Ordinal);
|
||||
Assert.Contains("SendDocument", source, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static async Task<string> ReadRepositoryFileAsync(string relativePath)
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null)
|
||||
{
|
||||
var candidate = Path.Combine(directory.FullName, relativePath);
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return await File.ReadAllTextAsync(candidate);
|
||||
}
|
||||
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
throw new FileNotFoundException($"Could not locate repository file '{relativePath}'.");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests and verify RED**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter TelegramPlatformMessengerSourceTests
|
||||
```
|
||||
|
||||
Expected: failures because `TelegramPlatformMessenger` is missing and handlers still call Telegram APIs directly.
|
||||
|
||||
### Task 4: GREEN - Implement TelegramPlatformMessenger and Registration
|
||||
|
||||
**Files:**
|
||||
- Create: `src/GmRelay.Bot/Infrastructure/Telegram/TelegramPlatformMessenger.cs`
|
||||
- Modify: `src/GmRelay.Bot/Program.cs`
|
||||
|
||||
- [ ] **Step 1: Implement adapter**
|
||||
|
||||
Implementation notes:
|
||||
|
||||
- Parse Telegram chat/thread/message IDs from neutral string IDs with `long.Parse` and `int.Parse`.
|
||||
- Use `ParseMode.Html` for HTML text.
|
||||
- Map `PlatformMessageAction` URLs to `InlineKeyboardButton.WithUrl`.
|
||||
- Return a `PlatformMessageRef` with message IDs converted to strings.
|
||||
|
||||
- [ ] **Step 2: Register adapter**
|
||||
|
||||
Add `using GmRelay.Shared.Platform;` and register:
|
||||
|
||||
```csharp
|
||||
builder.Services.AddSingleton<IPlatformMessenger, TelegramPlatformMessenger>();
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run adapter source tests**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter TelegramPlatformMessengerSourceTests
|
||||
```
|
||||
|
||||
Expected: some handler source tests still fail until Task 5.
|
||||
|
||||
### Task 5: GREEN - Refactor Session Flows Through Adapter
|
||||
|
||||
**Files:**
|
||||
- Modify target handler files listed in Task 3
|
||||
- Modify: `src/GmRelay.Bot/Features/Notifications/DirectSessionNotificationSender.cs`
|
||||
|
||||
- [ ] **Step 1: Replace constructor dependencies**
|
||||
|
||||
Use `IPlatformMessenger messenger` in target handlers for outbound operations. Keep `ITelegramBotClient` only where the handler still performs inbound Telegram-specific work that is out of scope, such as message deletion or forum topic creation.
|
||||
|
||||
- [ ] **Step 2: Convert Telegram IDs to neutral platform objects**
|
||||
|
||||
Use helper code equivalent to:
|
||||
|
||||
```csharp
|
||||
private static PlatformGroup TelegramGroup(long chatId, string? title, int? threadId = null)
|
||||
=> new(
|
||||
PlatformKind.Telegram,
|
||||
chatId.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
title ?? "Telegram chat",
|
||||
ExternalChannelId: chatId.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
ExternalThreadId: threadId?.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
|
||||
private static PlatformUser TelegramUser(long telegramId, string displayName, string? username = null)
|
||||
=> new(
|
||||
PlatformKind.Telegram,
|
||||
telegramId.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
displayName,
|
||||
username);
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Replace schedule updates**
|
||||
|
||||
Build `SessionBatchViewModel` as before, then call:
|
||||
|
||||
```csharp
|
||||
await messenger.UpdateScheduleAsync(
|
||||
new PlatformScheduleMessage(
|
||||
group,
|
||||
view,
|
||||
new PlatformMessageRef(PlatformKind.Telegram, group.ExternalGroupId, group.ExternalThreadId, messageId.ToString(System.Globalization.CultureInfo.InvariantCulture))),
|
||||
ct);
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Replace interaction replies**
|
||||
|
||||
Use:
|
||||
|
||||
```csharp
|
||||
await messenger.AnswerInteractionAsync(
|
||||
new PlatformInteractionReply(command.CallbackQueryId, text, showAlert: false),
|
||||
ct);
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Replace direct notifications**
|
||||
|
||||
`DirectSessionNotificationSender` should become a small compatibility service over `IPlatformMessenger`:
|
||||
|
||||
```csharp
|
||||
await messenger.SendPrivateMessageAsync(
|
||||
new PlatformPrivateMessage(
|
||||
new PlatformUser(PlatformKind.Telegram, recipient.TelegramId.ToString(CultureInfo.InvariantCulture), recipient.DisplayName, null),
|
||||
htmlText),
|
||||
ct);
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Replace calendar file sending**
|
||||
|
||||
`ExportCalendarHandler` builds the same ICS bytes and calls `SendCalendarFileAsync`, preserving the subscription URL button as a `PlatformMessageAction`.
|
||||
|
||||
- [ ] **Step 7: Run target source tests**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter TelegramPlatformMessengerSourceTests
|
||||
```
|
||||
|
||||
Expected: `Passed`.
|
||||
|
||||
### Task 6: Regression Tests
|
||||
|
||||
**Files:**
|
||||
- Existing tests only unless a compiler failure exposes a missing using or changed behavior.
|
||||
|
||||
- [ ] **Step 1: Run rendering and routing tests**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter "FullyQualifiedName~Rendering|FullyQualifiedName~Telegram|FullyQualifiedName~RescheduleSession"
|
||||
```
|
||||
|
||||
Expected: `Passed`.
|
||||
|
||||
- [ ] **Step 2: Run all tests**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj
|
||||
```
|
||||
|
||||
Expected: `Passed`.
|
||||
|
||||
- [ ] **Step 3: Build solution**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
dotnet build GM-Relay.slnx
|
||||
```
|
||||
|
||||
Expected: `Build succeeded` with warnings treated as errors.
|
||||
|
||||
### Task 7: Version Bump
|
||||
|
||||
**Files:**
|
||||
- Modify: `Directory.Build.props`
|
||||
- Modify: `compose.yaml`
|
||||
- Modify: `.gitea/workflows/deploy.yml`
|
||||
- Modify: `src/GmRelay.Web/Components/Layout/NavMenu.razor`
|
||||
|
||||
- [ ] **Step 1: Update all four version locations to `2.0.1`**
|
||||
- [ ] **Step 2: Verify sync**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
rg -n "2\\.0\\.0|2\\.0\\.1" Directory.Build.props compose.yaml .gitea/workflows/deploy.yml src/GmRelay.Web/Components/Layout/NavMenu.razor
|
||||
```
|
||||
|
||||
Expected: no `2.0.0` matches in these files and `2.0.1` appears in all required locations.
|
||||
|
||||
### Task 8: Documentation Review
|
||||
|
||||
**Files:**
|
||||
- Review: `README.md`
|
||||
- Review: `docs/adr/002-platform-neutral-batch-rendering.md`
|
||||
|
||||
- [ ] **Step 1: Check README and ADR for platform contract accuracy**
|
||||
- [ ] **Step 2: Update docs if they now misrepresent platform-neutral responsibilities**
|
||||
|
||||
Expected likely doc change: README currently lists current version as `v1.15.0`, which is already inconsistent with repo version `2.0.0`. If this PR bumps to `2.0.1`, update that line to `v2.0.1`.
|
||||
|
||||
### Task 9: Commit, PR, CI, Review, Merge, Deploy, Release
|
||||
|
||||
**Files:**
|
||||
- Stage only files intentionally changed for issue #24.
|
||||
|
||||
- [ ] **Step 1: Create branch**
|
||||
|
||||
```powershell
|
||||
git checkout -b codex/refactor/issue-24-platform-messenger
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```powershell
|
||||
git add src/GmRelay.Shared/Platform src/GmRelay.Bot tests/GmRelay.Bot.Tests Directory.Build.props compose.yaml .gitea/workflows/deploy.yml src/GmRelay.Web/Components/Layout/NavMenu.razor README.md docs/adr/002-platform-neutral-batch-rendering.md
|
||||
git commit -m "refactor: add platform messenger contracts"
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Push and create PR via Gitea**
|
||||
- [ ] **Step 4: Wait for PR CI and fix failures if any**
|
||||
- [ ] **Step 5: Run code review subagent and address findings**
|
||||
- [ ] **Step 6: Merge PR after CI and review**
|
||||
- [ ] **Step 7: Monitor deploy workflow**
|
||||
- [ ] **Step 8: Create release `v2.0.1` with Russian release notes**
|
||||
- [ ] **Step 9: Close issue #24 with PR and release links**
|
||||
|
||||
## Self-Review
|
||||
|
||||
- Spec coverage: all issue acceptance criteria map to Shared contracts, Telegram adapter, handler source tests, and build/test verification.
|
||||
- Placeholder scan: no `TBD`, `TODO`, or "fill later" placeholders are left in this plan.
|
||||
- Type consistency: all snippets use `GmRelay.Shared.Platform`, `PlatformKind.Telegram`, `PlatformMessageRef`, and `IPlatformMessenger` consistently.
|
||||
- Scope control: inbound Telegram update parsing remains out of scope; outbound schedule/private/interaction/calendar operations are in scope.
|
||||
@@ -0,0 +1,731 @@
|
||||
# Discord NetCord Gateway Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add a separate `src/GmRelay.DiscordBot` worker that uses NetCord Gateway for Discord slash commands and component interactions while keeping Telegram dependencies isolated in `src/GmRelay.Bot`.
|
||||
|
||||
**Architecture:** Create a new .NET worker project that references `GmRelay.ServiceDefaults` and `GmRelay.Shared`, validates `Discord:Token` during startup, registers NetCord gateway/application command/component services, and logs gateway lifecycle events through NetCord gateway handlers. Keep database connectivity aligned with the existing worker by registering the same `ConnectionStrings:gmrelaydb` `NpgsqlDataSource` pattern, but do not move Telegram code or dependencies.
|
||||
|
||||
**Tech Stack:** .NET 10 worker, Aspire service defaults, NetCord.Hosting `1.0.0-alpha.489`, Npgsql `10.0.2`, xUnit, Docker Compose, Gitea Actions.
|
||||
|
||||
---
|
||||
|
||||
## Issue
|
||||
|
||||
- Gitea issue: `#26`, `feat: добавить src/GmRelay.DiscordBot на NetCord Gateway`
|
||||
- Labels: `type:feature`, `area:discord`, `area:infra`, `platform:discord`, `priority:p1`, `pending-approval`
|
||||
- Version bump: minor, `2.1.1` -> `2.2.0`
|
||||
- Branch: `feature/issue-26-discord-netcord-gateway`
|
||||
|
||||
## Sources Checked
|
||||
|
||||
- NetCord application commands guide: `https://netcord.dev/guides/services/application-commands/introduction.html`
|
||||
- NetCord intents guide: `https://netcord.dev/guides/events/intents.html`
|
||||
- NetCord gateway handler docs: `https://netcord.dev/docs/NetCord.Hosting.Gateway.html`
|
||||
- NuGet flat container for `NetCord.Hosting`: latest observed version `1.0.0-alpha.489`
|
||||
|
||||
## File Structure
|
||||
|
||||
- Create: `src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj` - Discord worker project and package references.
|
||||
- Create: `src/GmRelay.DiscordBot/Program.cs` - host composition, token validation, database registration, NetCord service registration.
|
||||
- Create: `src/GmRelay.DiscordBot/DiscordOptions.cs` - strongly typed Discord token/options validation.
|
||||
- Create: `src/GmRelay.DiscordBot/Infrastructure/Logging/SecretRedactor.cs` - Discord-local startup redaction without referencing the Telegram worker project.
|
||||
- Create: `src/GmRelay.DiscordBot/Infrastructure/Logging/DiscordGatewayLifecycleLogger.cs` - NetCord gateway lifecycle handler for ready/connect/resume/disconnect/close/rate-limit events where available.
|
||||
- Create: `src/GmRelay.DiscordBot/Dockerfile` - publish and runtime image for the Discord worker.
|
||||
- Modify: `GM-Relay.slnx` - include the new project.
|
||||
- Modify: `src/GmRelay.AppHost/GmRelay.AppHost.csproj` - reference the Discord worker for Aspire orchestration.
|
||||
- Modify: `src/GmRelay.AppHost/Program.cs` - add `discord` project with PostgreSQL reference.
|
||||
- Modify: `tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj` - reference the Discord worker project.
|
||||
- Create: `tests/GmRelay.Bot.Tests/Discord/DiscordProjectStructureTests.cs` - source-level tests for solution inclusion, Docker/Compose/CI wiring, and Telegram isolation.
|
||||
- Create: `tests/GmRelay.Bot.Tests/Discord/DiscordOptionsTests.cs` - unit tests for token validation.
|
||||
- Create: `tests/GmRelay.Bot.Tests/Discord/DiscordStartupTests.cs` - source-level startup tests for NetCord registration, service defaults, and PostgreSQL connection requirements.
|
||||
- Modify: `compose.yaml` - add `discord` service and versioned image tag.
|
||||
- Modify: `.gitea/workflows/deploy.yml` - build/push/scan/pull Discord image and include `DISCORD_BOT_TOKEN` in `.env`.
|
||||
- Modify: `.gitea/workflows/pr-checks.yml` - build the Discord project in PR checks.
|
||||
- Modify: `Directory.Build.props` - version `2.2.0`.
|
||||
- Modify: `src/GmRelay.Web/Components/Layout/NavMenu.razor` - visible version `v2.2.0`.
|
||||
- Generated by restore: `src/GmRelay.DiscordBot/packages.lock.json`.
|
||||
- Generated by restore: updates to `tests/GmRelay.Bot.Tests/packages.lock.json` and `src/GmRelay.AppHost/packages.lock.json`.
|
||||
|
||||
## TDD Plan
|
||||
|
||||
### Task 1: Project Presence And Telegram Isolation
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/GmRelay.Bot.Tests/Discord/DiscordProjectStructureTests.cs`
|
||||
- Modify: `GM-Relay.slnx`
|
||||
- Create: `src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj`
|
||||
- Create: `src/GmRelay.DiscordBot/Program.cs`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
public sealed class DiscordProjectStructureTests
|
||||
{
|
||||
private static string GetRepoRoot()
|
||||
{
|
||||
var dir = AppContext.BaseDirectory;
|
||||
while (!string.IsNullOrEmpty(dir) && !File.Exists(Path.Combine(dir, "Directory.Build.props")))
|
||||
{
|
||||
dir = Directory.GetParent(dir)?.FullName;
|
||||
}
|
||||
|
||||
return dir ?? throw new InvalidOperationException("Could not find repo root");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Solution_ShouldIncludeDiscordWorkerProject()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var solution = File.ReadAllText(Path.Combine(repoRoot, "GM-Relay.slnx"));
|
||||
|
||||
Assert.Contains("src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj", solution);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscordWorkerProject_ShouldExistWithoutTelegramDependency()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var projectPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "GmRelay.DiscordBot.csproj");
|
||||
|
||||
Assert.True(File.Exists(projectPath), "Discord worker project should exist.");
|
||||
|
||||
var project = File.ReadAllText(projectPath);
|
||||
Assert.Contains("Microsoft.NET.Sdk.Worker", project);
|
||||
Assert.Contains("NetCord.Hosting", project);
|
||||
Assert.Contains("GmRelay.ServiceDefaults.csproj", project);
|
||||
Assert.Contains("GmRelay.Shared.csproj", project);
|
||||
Assert.DoesNotContain("Telegram.Bot", project);
|
||||
Assert.DoesNotContain("GmRelay.Bot.csproj", project);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TelegramWorkerProject_ShouldNotReferenceNetCord()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var project = File.ReadAllText(Path.Combine(repoRoot, "src", "GmRelay.Bot", "GmRelay.Bot.csproj"));
|
||||
|
||||
Assert.DoesNotContain("NetCord", project, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test to verify it fails**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter FullyQualifiedName~DiscordProjectStructureTests`
|
||||
|
||||
Expected: FAIL because `GM-Relay.slnx` does not include `src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj` and the project file does not exist.
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
Create `src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj`:
|
||||
|
||||
```xml
|
||||
<Project Sdk="Microsoft.NET.Sdk.Worker">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>preview</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>dotnet-GmRelay.DiscordBot-issue-26</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Aspire.Npgsql" Version="13.2.2" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
|
||||
<PackageReference Include="NetCord.Hosting" Version="1.0.0-alpha.489" />
|
||||
<PackageReference Include="Npgsql" Version="10.0.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\GmRelay.ServiceDefaults\GmRelay.ServiceDefaults.csproj" />
|
||||
<ProjectReference Include="..\GmRelay.Shared\GmRelay.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
```
|
||||
|
||||
Add this project to `GM-Relay.slnx` inside `/src/`:
|
||||
|
||||
```xml
|
||||
<Project Path="src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj" />
|
||||
```
|
||||
|
||||
Create temporary minimal `src/GmRelay.DiscordBot/Program.cs`:
|
||||
|
||||
```csharp
|
||||
var builder = Host.CreateApplicationBuilder(args);
|
||||
builder.AddServiceDefaults();
|
||||
await builder.Build().RunAsync();
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run the test to verify it passes**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter FullyQualifiedName~DiscordProjectStructureTests`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
### Task 2: Token Validation
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj`
|
||||
- Create: `tests/GmRelay.Bot.Tests/Discord/DiscordOptionsTests.cs`
|
||||
- Create: `src/GmRelay.DiscordBot/DiscordOptions.cs`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
Add the project reference to `tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj`:
|
||||
|
||||
```xml
|
||||
<ProjectReference Include="..\..\src\GmRelay.DiscordBot\GmRelay.DiscordBot.csproj" />
|
||||
```
|
||||
|
||||
Create `tests/GmRelay.Bot.Tests/Discord/DiscordOptionsTests.cs`:
|
||||
|
||||
```csharp
|
||||
using GmRelay.DiscordBot;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
public sealed class DiscordOptionsTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void Validate_ShouldRejectMissingToken(string? token)
|
||||
{
|
||||
var options = new DiscordOptions { Token = token };
|
||||
|
||||
var exception = Assert.Throws<InvalidOperationException>(options.Validate);
|
||||
|
||||
Assert.Contains("Discord:Token is required", exception.Message);
|
||||
Assert.Contains("Discord__Token", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_ShouldAcceptConfiguredToken()
|
||||
{
|
||||
var options = new DiscordOptions { Token = "configured-token" };
|
||||
|
||||
options.Validate();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test to verify it fails**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter FullyQualifiedName~DiscordOptionsTests`
|
||||
|
||||
Expected: FAIL at compile time because `GmRelay.DiscordBot.DiscordOptions` is not defined.
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
Create `src/GmRelay.DiscordBot/DiscordOptions.cs`:
|
||||
|
||||
```csharp
|
||||
namespace GmRelay.DiscordBot;
|
||||
|
||||
public sealed class DiscordOptions
|
||||
{
|
||||
public string? Token { get; init; }
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(Token))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Discord:Token is required. Set via environment variable Discord__Token or user secrets.");
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run the test to verify it passes**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter FullyQualifiedName~DiscordOptionsTests`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
### Task 3: Startup Wiring For Service Defaults, PostgreSQL, NetCord, And Slash Commands
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/GmRelay.Bot.Tests/Discord/DiscordStartupTests.cs`
|
||||
- Modify: `src/GmRelay.DiscordBot/Program.cs`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
Create `tests/GmRelay.Bot.Tests/Discord/DiscordStartupTests.cs`:
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
public sealed class DiscordStartupTests
|
||||
{
|
||||
private static string GetRepoRoot()
|
||||
{
|
||||
var dir = AppContext.BaseDirectory;
|
||||
while (!string.IsNullOrEmpty(dir) && !File.Exists(Path.Combine(dir, "Directory.Build.props")))
|
||||
{
|
||||
dir = Directory.GetParent(dir)?.FullName;
|
||||
}
|
||||
|
||||
return dir ?? throw new InvalidOperationException("Could not find repo root");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Program_ShouldValidateDiscordTokenBeforeRunning()
|
||||
{
|
||||
var program = ReadProgram();
|
||||
|
||||
Assert.Contains("GetRequiredSection(\"Discord\")", program);
|
||||
Assert.Contains("DiscordOptions", program);
|
||||
Assert.Contains(".Validate()", program);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Program_ShouldRegisterServiceDefaultsAndPostgresDataSource()
|
||||
{
|
||||
var program = ReadProgram();
|
||||
|
||||
Assert.Contains("builder.AddServiceDefaults()", program);
|
||||
Assert.Contains("ConnectionStrings:gmrelaydb is required", program);
|
||||
Assert.Contains("NpgsqlDataSource", program);
|
||||
Assert.Contains("SecretRedactor.RedactConnectionString", program);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Program_ShouldRegisterNetCordGatewayApplicationCommandsAndComponents()
|
||||
{
|
||||
var program = ReadProgram();
|
||||
|
||||
Assert.Contains(".AddDiscordGateway", program);
|
||||
Assert.Contains(".AddApplicationCommands", program);
|
||||
Assert.Contains(".AddComponentInteractions", program);
|
||||
Assert.Contains(".AddGatewayHandlers", program);
|
||||
Assert.Contains("AddSlashCommand", program);
|
||||
}
|
||||
|
||||
private static string ReadProgram()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
return File.ReadAllText(Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Program.cs"));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test to verify it fails**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter FullyQualifiedName~DiscordStartupTests`
|
||||
|
||||
Expected: FAIL because `Program.cs` does not validate `Discord:Token`, register `NpgsqlDataSource`, or register NetCord services yet.
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
Replace `src/GmRelay.DiscordBot/Program.cs` with host composition that:
|
||||
|
||||
```csharp
|
||||
using GmRelay.DiscordBot;
|
||||
using GmRelay.DiscordBot.Infrastructure.Logging;
|
||||
using NetCord.Gateway;
|
||||
using NetCord.Hosting.Gateway;
|
||||
using NetCord.Hosting.Services.ApplicationCommands;
|
||||
using NetCord.Hosting.Services.ComponentInteractions;
|
||||
using Npgsql;
|
||||
|
||||
var builder = Host.CreateApplicationBuilder(args);
|
||||
|
||||
builder.AddServiceDefaults();
|
||||
|
||||
var discordOptions = builder.Configuration
|
||||
.GetRequiredSection("Discord")
|
||||
.Get<DiscordOptions>() ?? new DiscordOptions();
|
||||
discordOptions.Validate();
|
||||
|
||||
builder.Services.AddSingleton(discordOptions);
|
||||
|
||||
builder.Services.AddSingleton<NpgsqlDataSource>(sp =>
|
||||
{
|
||||
var config = sp.GetRequiredService<IConfiguration>();
|
||||
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
|
||||
var connectionString = config.GetConnectionString("gmrelaydb")
|
||||
?? throw new InvalidOperationException(
|
||||
"ConnectionStrings:gmrelaydb is required. Set via environment variable ConnectionStrings__gmrelaydb.");
|
||||
|
||||
var logger = loggerFactory.CreateLogger("GmRelay.DiscordBot.Startup");
|
||||
logger.LogInformation(
|
||||
"Configured PostgreSQL data source with connection string {ConnectionString}",
|
||||
SecretRedactor.RedactConnectionString(connectionString));
|
||||
|
||||
return NpgsqlDataSource.Create(connectionString);
|
||||
});
|
||||
|
||||
builder.Services
|
||||
.AddDiscordGateway(options =>
|
||||
{
|
||||
options.Token = discordOptions.Token;
|
||||
options.Intents = GatewayIntents.Guilds;
|
||||
})
|
||||
.AddApplicationCommands()
|
||||
.AddComponentInteractions()
|
||||
.AddGatewayHandlers(typeof(Program).Assembly);
|
||||
|
||||
var host = builder.Build();
|
||||
|
||||
host.AddSlashCommand("ping", "Checks whether GM-Relay Discord is online.", () => "Pong!");
|
||||
|
||||
await host.RunAsync();
|
||||
```
|
||||
|
||||
Use the Discord-local `SecretRedactor` namespace instead of `GmRelay.Bot.Infrastructure.Logging` so the new project does not reference the Telegram worker.
|
||||
|
||||
Create `src/GmRelay.DiscordBot/Infrastructure/Logging/SecretRedactor.cs`:
|
||||
|
||||
```csharp
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace GmRelay.DiscordBot.Infrastructure.Logging;
|
||||
|
||||
internal static partial class SecretRedactor
|
||||
{
|
||||
public static string RedactConnectionString(string connectionString)
|
||||
{
|
||||
return PasswordPattern().Replace(connectionString, "$1***");
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"(?i)(Password\s*=\s*)[^;]+")]
|
||||
private static partial Regex PasswordPattern();
|
||||
}
|
||||
```
|
||||
|
||||
If `GatewayClientOptions.Token` does not accept `string`, adjust to NetCord's required token type after compile feedback while preserving the tests' intent.
|
||||
|
||||
- [ ] **Step 4: Run the test to verify it passes**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter FullyQualifiedName~DiscordStartupTests`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
### Task 4: Gateway Lifecycle Logging
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/GmRelay.Bot.Tests/Discord/DiscordStartupTests.cs`
|
||||
- Create: `src/GmRelay.DiscordBot/Infrastructure/Logging/DiscordGatewayLifecycleLogger.cs`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
Add to `DiscordStartupTests.cs`:
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void LifecycleLogger_ShouldLogGatewayLifecycleEventsWithoutTokenValues()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var loggerPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Infrastructure", "Logging", "DiscordGatewayLifecycleLogger.cs");
|
||||
|
||||
Assert.True(File.Exists(loggerPath), "Discord gateway lifecycle logger should exist.");
|
||||
|
||||
var logger = File.ReadAllText(loggerPath);
|
||||
Assert.Contains("IReadyGatewayHandler", logger);
|
||||
Assert.Contains("IDisconnectGatewayHandler", logger);
|
||||
Assert.Contains("IResumeGatewayHandler", logger);
|
||||
Assert.Contains("LogInformation", logger);
|
||||
Assert.DoesNotContain("Token", logger);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test to verify it fails**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter LifecycleLogger_ShouldLogGatewayLifecycleEventsWithoutTokenValues`
|
||||
|
||||
Expected: FAIL because `DiscordGatewayLifecycleLogger.cs` does not exist.
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
Create `src/GmRelay.DiscordBot/Infrastructure/Logging/DiscordGatewayLifecycleLogger.cs` using the concrete NetCord handler signatures from the installed `NetCord.Hosting` package. Minimum behavior:
|
||||
|
||||
```csharp
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NetCord.Gateway;
|
||||
using NetCord.Hosting.Gateway;
|
||||
|
||||
namespace GmRelay.DiscordBot.Infrastructure.Logging;
|
||||
|
||||
public sealed class DiscordGatewayLifecycleLogger(
|
||||
ILogger<DiscordGatewayLifecycleLogger> logger)
|
||||
: IReadyGatewayHandler,
|
||||
IDisconnectGatewayHandler,
|
||||
IResumeGatewayHandler
|
||||
{
|
||||
public ValueTask HandleAsync(ReadyEventArgs arg)
|
||||
{
|
||||
logger.LogInformation("Discord gateway ready as application {ApplicationId}", arg.Application.Id);
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
public ValueTask HandleAsync(DisconnectEventArgs arg)
|
||||
{
|
||||
logger.LogWarning("Discord gateway disconnected with close status {CloseStatus}", arg.CloseStatus);
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
public ValueTask HandleAsync()
|
||||
{
|
||||
logger.LogInformation("Discord gateway session resumed");
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If interface signatures differ in `1.0.0-alpha.489`, inspect the package XML/docs and adjust the handlers to compile while keeping ready/disconnect/resume logging and never logging token values.
|
||||
|
||||
- [ ] **Step 4: Run the test to verify it passes**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter LifecycleLogger_ShouldLogGatewayLifecycleEventsWithoutTokenValues`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
### Task 5: Runtime Container, Compose, AppHost, And CI Wiring
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/GmRelay.Bot.Tests/Discord/DiscordProjectStructureTests.cs`
|
||||
- Create: `src/GmRelay.DiscordBot/Dockerfile`
|
||||
- Modify: `compose.yaml`
|
||||
- Modify: `src/GmRelay.AppHost/GmRelay.AppHost.csproj`
|
||||
- Modify: `src/GmRelay.AppHost/Program.cs`
|
||||
- Modify: `.gitea/workflows/pr-checks.yml`
|
||||
- Modify: `.gitea/workflows/deploy.yml`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
Add to `DiscordProjectStructureTests.cs`:
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void RuntimeWiring_ShouldIncludeDiscordServiceWithoutCouplingTelegram()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var compose = File.ReadAllText(Path.Combine(repoRoot, "compose.yaml"));
|
||||
var appHostProject = File.ReadAllText(Path.Combine(repoRoot, "src", "GmRelay.AppHost", "GmRelay.AppHost.csproj"));
|
||||
var appHostProgram = File.ReadAllText(Path.Combine(repoRoot, "src", "GmRelay.AppHost", "Program.cs"));
|
||||
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:2.2.0", 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);
|
||||
Assert.Contains("dotnet build src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj --no-restore", prChecks);
|
||||
Assert.Contains("GmRelay.DiscordBot.csproj", appHostProject);
|
||||
Assert.Contains("Projects.GmRelay_DiscordBot", appHostProgram);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test to verify it fails**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter RuntimeWiring_ShouldIncludeDiscordServiceWithoutCouplingTelegram`
|
||||
|
||||
Expected: FAIL because runtime wiring is not present.
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
Create `src/GmRelay.DiscordBot/Dockerfile` modeled after `src/GmRelay.Bot/Dockerfile`, with project copy/restore for `GmRelay.DiscordBot`, `GmRelay.ServiceDefaults`, and `GmRelay.Shared`, and entrypoint `./GmRelay.DiscordBot`.
|
||||
|
||||
Add `discord` service to `compose.yaml`:
|
||||
|
||||
```yaml
|
||||
discord:
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-discord-bot:2.2.0
|
||||
restart: always
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
- "ConnectionStrings__gmrelaydb=Host=db;Port=5432;Database=gmrelay_db;Username=gmrelay;Password=${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}"
|
||||
- "Discord__Token=${DISCORD_BOT_TOKEN:?Set DISCORD_BOT_TOKEN in .env}"
|
||||
networks:
|
||||
- gmrelay
|
||||
```
|
||||
|
||||
Add Discord project reference to `src/GmRelay.AppHost/GmRelay.AppHost.csproj`:
|
||||
|
||||
```xml
|
||||
<ProjectReference Include="..\GmRelay.DiscordBot\GmRelay.DiscordBot.csproj" />
|
||||
```
|
||||
|
||||
Add Discord service to `src/GmRelay.AppHost/Program.cs`:
|
||||
|
||||
```csharp
|
||||
builder.AddProject<Projects.GmRelay_DiscordBot>("discord")
|
||||
.WithReference(postgres)
|
||||
.WaitFor(postgres);
|
||||
```
|
||||
|
||||
Update `.gitea/workflows/pr-checks.yml` with:
|
||||
|
||||
```yaml
|
||||
- name: Build Discord Bot (compile check, includes SAST)
|
||||
run: dotnet build src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj --no-restore
|
||||
```
|
||||
|
||||
Update `.gitea/workflows/deploy.yml` to build, push, scan, pull, and deploy `git.codeanddice.ru/toutsu/gmrelay-discord-bot:${{ env.VERSION }}` and write `DISCORD_BOT_TOKEN=${{ secrets.DISCORD_BOT_TOKEN }}` to `.env`.
|
||||
|
||||
- [ ] **Step 4: Run the test to verify it passes**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter RuntimeWiring_ShouldIncludeDiscordServiceWithoutCouplingTelegram`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
### Task 6: Version Synchronization
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/GmRelay.Bot.Tests/Discord/DiscordProjectStructureTests.cs`
|
||||
- Modify: `Directory.Build.props`
|
||||
- Modify: `compose.yaml`
|
||||
- Modify: `.gitea/workflows/deploy.yml`
|
||||
- Modify: `src/GmRelay.Web/Components/Layout/NavMenu.razor`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
Add to `DiscordProjectStructureTests.cs`:
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void Version_ShouldBeSynchronizedForDiscordFeatureRelease()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
|
||||
Assert.Contains("<Version>2.2.0</Version>", File.ReadAllText(Path.Combine(repoRoot, "Directory.Build.props")));
|
||||
Assert.Contains("VERSION: 2.2.0", File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "deploy.yml")));
|
||||
Assert.Contains("gmrelay-bot:2.2.0", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
|
||||
Assert.Contains("gmrelay-web:2.2.0", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
|
||||
Assert.Contains("gmrelay-discord-bot:2.2.0", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
|
||||
Assert.Contains("v2.2.0", File.ReadAllText(Path.Combine(repoRoot, "src", "GmRelay.Web", "Components", "Layout", "NavMenu.razor")));
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test to verify it fails**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter Version_ShouldBeSynchronizedForDiscordFeatureRelease`
|
||||
|
||||
Expected: FAIL because current version is `2.1.1`.
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
Update:
|
||||
- `Directory.Build.props`: `<Version>2.2.0</Version>`
|
||||
- `.gitea/workflows/deploy.yml`: `VERSION: 2.2.0`
|
||||
- `compose.yaml`: `gmrelay-bot:2.2.0`, `gmrelay-web:2.2.0`, `gmrelay-discord-bot:2.2.0`
|
||||
- `src/GmRelay.Web/Components/Layout/NavMenu.razor`: `v2.2.0`
|
||||
|
||||
- [ ] **Step 4: Run the test to verify it passes**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter Version_ShouldBeSynchronizedForDiscordFeatureRelease`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
### Task 7: Restore, Format, Build, And Full Test Verification
|
||||
|
||||
**Files:**
|
||||
- Generated/updated: `src/GmRelay.DiscordBot/packages.lock.json`
|
||||
- Generated/updated: `tests/GmRelay.Bot.Tests/packages.lock.json`
|
||||
- Generated/updated: `src/GmRelay.AppHost/packages.lock.json`
|
||||
- Any code formatting changes required by `dotnet format`
|
||||
|
||||
- [ ] **Step 1: Restore lock files**
|
||||
|
||||
Run: `dotnet restore GM-Relay.slnx`
|
||||
|
||||
Expected: restore succeeds and creates/updates lock files for the new project references and NetCord dependency.
|
||||
|
||||
- [ ] **Step 2: Run targeted tests**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter FullyQualifiedName~Discord`
|
||||
|
||||
Expected: all Discord tests pass.
|
||||
|
||||
- [ ] **Step 3: Run full tests**
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --verbosity normal`
|
||||
|
||||
Expected: all tests pass.
|
||||
|
||||
- [ ] **Step 4: Run release build**
|
||||
|
||||
Run: `dotnet build GM-Relay.slnx -c Release`
|
||||
|
||||
Expected: solution build succeeds and includes `src/GmRelay.DiscordBot`.
|
||||
|
||||
- [ ] **Step 5: Run format check**
|
||||
|
||||
Run: `dotnet format --verify-no-changes --verbosity diagnostic`
|
||||
|
||||
Expected: no formatting changes required.
|
||||
|
||||
- [ ] **Step 6: Inspect diff for secrets**
|
||||
|
||||
Run: `git diff --check`
|
||||
|
||||
Expected: no whitespace errors and no Discord token value in tracked files.
|
||||
|
||||
Run: `git diff -- . ':!*.lock.json'`
|
||||
|
||||
Expected: diff contains configuration variable names such as `Discord__Token` and `DISCORD_BOT_TOKEN`, but not a real token value.
|
||||
|
||||
### Task 8: Commit, PR, CI, Deploy, Release, Issue Closure
|
||||
|
||||
**Files:**
|
||||
- All intended implementation, test, lock, workflow, compose, and version files.
|
||||
|
||||
- [ ] **Step 1: Create commit**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
git status --short
|
||||
git add GM-Relay.slnx Directory.Build.props compose.yaml .gitea/workflows/deploy.yml .gitea/workflows/pr-checks.yml src/GmRelay.AppHost src/GmRelay.DiscordBot src/GmRelay.Web/Components/Layout/NavMenu.razor tests/GmRelay.Bot.Tests
|
||||
git commit -m "feat: add Discord NetCord gateway worker"
|
||||
```
|
||||
|
||||
Expected: only intended files are staged and committed. Do not stage untracked `CLAUDE.md`.
|
||||
|
||||
- [ ] **Step 2: Push branch and open PR**
|
||||
|
||||
Run: `git push -u origin feature/issue-26-discord-netcord-gateway`
|
||||
|
||||
Create Gitea PR to `main` with:
|
||||
- Summary of Discord worker, token validation, runtime wiring, and version bump.
|
||||
- Test plan showing targeted Discord tests, full tests, release build, format, and secret diff inspection.
|
||||
- Link to issue `#26`.
|
||||
|
||||
- [ ] **Step 3: Store Discord token as a Gitea Actions secret**
|
||||
|
||||
Use Gitea Actions configuration to create or update repository secret `DISCORD_BOT_TOKEN` with the user-provided Discord bot token.
|
||||
|
||||
Expected: token is stored only as an Actions secret. The token value is not written to source files, plan files, logs, PR text, release notes, or commits.
|
||||
|
||||
- [ ] **Step 4: Monitor CI**
|
||||
|
||||
Use Gitea Actions run reads until PR checks finish. If CI fails, inspect logs, fix with TDD where the failure is code behavior, push again, and re-check.
|
||||
|
||||
- [ ] **Step 5: Review, merge, deploy, release**
|
||||
|
||||
After CI passes and review is approved:
|
||||
- Merge PR.
|
||||
- Monitor deploy workflow on `main`.
|
||||
- Create release `v2.2.0` with Russian release notes.
|
||||
- Close issue `#26` with a comment linking PR and release.
|
||||
|
||||
## Self-Review
|
||||
|
||||
- Spec coverage: Project creation, NetCord Gateway, slash/component service registration, `Discord__Token`, PostgreSQL service defaults, lifecycle logging, Telegram isolation, solution build, compose/deploy integration, and version sync are covered.
|
||||
- Placeholder scan: No task uses `TBD`, `TODO`, or an unspecified "add tests" instruction.
|
||||
- Type consistency: Test class names and file paths are consistent across tasks; NetCord lifecycle handler signatures are explicitly marked for compile-driven adjustment because the package is prerelease and must be verified against installed `1.0.0-alpha.489`.
|
||||
@@ -0,0 +1,599 @@
|
||||
# Platform-Neutral Join Leave Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Implement Gitea issue #25 by making join/leave session interactions use platform-neutral command models while preserving Telegram callback behavior, seat limits, and waitlist semantics.
|
||||
|
||||
**Architecture:** Telegram callback routing remains in `UpdateRouter`, but it becomes an adapter that converts callback data into `PlatformUser`, `PlatformGroup`, and `PlatformMessageRef` values. `JoinSessionHandler` and `LeaveSessionHandler` operate on those neutral values, persist players by `(platform, external_user_id)`, and update schedules through `IPlatformMessenger`.
|
||||
|
||||
**Tech Stack:** .NET 10, xUnit, Dapper, Npgsql, Gitea Actions.
|
||||
|
||||
---
|
||||
|
||||
## Issue Context
|
||||
|
||||
- Issue: `#25 refactor: obobshchit JoinSession i LeaveSession pod platform-neutral interactions`
|
||||
- Labels: `area:bot`, `area:platform`, `area:shared`, `platform:multi`, `type:refactor`
|
||||
- Version bump: patch, `2.1.0` -> `2.1.1`. The issue is labeled refactor, not breaking; do not use a major bump without explicit approval.
|
||||
- Existing untracked file: `CLAUDE.md`; do not stage or modify it.
|
||||
|
||||
## File Map
|
||||
|
||||
- Create: `tests/GmRelay.Bot.Tests/Features/Sessions/CreateSession/PlatformNeutralSessionInteractionCommandTests.cs`
|
||||
- Reflection tests proving join/leave command records expose neutral properties and no Telegram-specific identity/message fields.
|
||||
- Create: `tests/GmRelay.Bot.Tests/Features/Sessions/CreateSession/PlatformNeutralSessionInteractionSqlTests.cs`
|
||||
- Source-level regression tests for handler SQL and messenger boundaries.
|
||||
- Modify: `tests/GmRelay.Bot.Tests/Infrastructure/Database/PlatformIdentityMigrationTests.cs`
|
||||
- Add a migration test for nullable legacy `players.telegram_id`, required for non-Telegram player inserts.
|
||||
- Create: `src/GmRelay.Bot/Migrations/V017__allow_platform_neutral_players.sql`
|
||||
- Drop `NOT NULL` from legacy Telegram-only player columns.
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/CreateSession/JoinSessionHandler.cs`
|
||||
- Change `JoinSessionCommand` to neutral properties and query/upsert players by platform identity.
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/CreateSession/LeaveSessionHandler.cs`
|
||||
- Change `LeaveSessionCommand` to neutral properties and find participants by platform identity.
|
||||
- Modify: `src/GmRelay.Bot/Infrastructure/Telegram/UpdateRouter.cs`
|
||||
- Convert Telegram callback data into neutral command values using `TelegramPlatformIds`.
|
||||
- Modify: version files after implementation:
|
||||
- `Directory.Build.props`
|
||||
- `compose.yaml`
|
||||
- `.gitea/workflows/deploy.yml`
|
||||
- `src/GmRelay.Web/Components/Layout/NavMenu.razor`
|
||||
|
||||
## Task 1: RED - Command Model Tests
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/GmRelay.Bot.Tests/Features/Sessions/CreateSession/PlatformNeutralSessionInteractionCommandTests.cs`
|
||||
|
||||
- [ ] **Step 1: Write failing command-shape tests**
|
||||
|
||||
```csharp
|
||||
using GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
using GmRelay.Shared.Platform;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Features.Sessions.CreateSession;
|
||||
|
||||
public sealed class PlatformNeutralSessionInteractionCommandTests
|
||||
{
|
||||
[Fact]
|
||||
public void JoinSessionCommand_ShouldExposePlatformNeutralInteractionContext()
|
||||
{
|
||||
AssertProperty<JoinSessionCommand>("SessionId", typeof(Guid));
|
||||
AssertProperty<JoinSessionCommand>("User", typeof(PlatformUser));
|
||||
AssertProperty<JoinSessionCommand>("InteractionId", typeof(string));
|
||||
AssertProperty<JoinSessionCommand>("Group", typeof(PlatformGroup));
|
||||
AssertProperty<JoinSessionCommand>("ScheduleMessage", typeof(PlatformMessageRef));
|
||||
AssertNoTelegramSpecificProperties<JoinSessionCommand>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LeaveSessionCommand_ShouldExposePlatformNeutralInteractionContext()
|
||||
{
|
||||
AssertProperty<LeaveSessionCommand>("SessionId", typeof(Guid));
|
||||
AssertProperty<LeaveSessionCommand>("User", typeof(PlatformUser));
|
||||
AssertProperty<LeaveSessionCommand>("InteractionId", typeof(string));
|
||||
AssertProperty<LeaveSessionCommand>("Group", typeof(PlatformGroup));
|
||||
AssertProperty<LeaveSessionCommand>("ScheduleMessage", typeof(PlatformMessageRef));
|
||||
AssertNoTelegramSpecificProperties<LeaveSessionCommand>();
|
||||
}
|
||||
|
||||
private static void AssertProperty<T>(string name, Type expectedType)
|
||||
{
|
||||
var property = Assert.Single(typeof(T).GetProperties(), property => property.Name == name);
|
||||
|
||||
Assert.Equal(expectedType, property.PropertyType);
|
||||
}
|
||||
|
||||
private static void AssertNoTelegramSpecificProperties<T>()
|
||||
{
|
||||
var names = typeof(T).GetProperties().Select(property => property.Name).ToArray();
|
||||
|
||||
Assert.DoesNotContain(names, name => name.Contains("Telegram", StringComparison.Ordinal));
|
||||
Assert.DoesNotContain("ChatId", names);
|
||||
Assert.DoesNotContain("MessageId", names);
|
||||
Assert.DoesNotContain("TelegramUserId", names);
|
||||
Assert.DoesNotContain("TelegramUsername", names);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
dotnet test .\tests\GmRelay.Bot.Tests\GmRelay.Bot.Tests.csproj --filter PlatformNeutralSessionInteractionCommandTests
|
||||
```
|
||||
|
||||
Expected: FAIL because `JoinSessionCommand` and `LeaveSessionCommand` still expose `TelegramUserId`, `ChatId`, and `MessageId`, and do not expose `User`, `Group`, or `ScheduleMessage`.
|
||||
|
||||
## Task 2: RED - SQL and Boundary Tests
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/GmRelay.Bot.Tests/Features/Sessions/CreateSession/PlatformNeutralSessionInteractionSqlTests.cs`
|
||||
- Modify: `tests/GmRelay.Bot.Tests/Infrastructure/Database/PlatformIdentityMigrationTests.cs`
|
||||
|
||||
- [ ] **Step 1: Write failing handler source tests**
|
||||
|
||||
```csharp
|
||||
namespace GmRelay.Bot.Tests.Features.Sessions.CreateSession;
|
||||
|
||||
public sealed class PlatformNeutralSessionInteractionSqlTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task JoinSessionHandler_ShouldPersistPlayersByPlatformIdentity()
|
||||
{
|
||||
var handler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/CreateSession/JoinSessionHandler.cs");
|
||||
|
||||
Assert.Contains("platform, external_user_id", handler, StringComparison.Ordinal);
|
||||
Assert.Contains("ON CONFLICT (platform, external_user_id)", handler, StringComparison.Ordinal);
|
||||
Assert.Contains("ExternalUserId", handler, StringComparison.Ordinal);
|
||||
Assert.Contains("ExternalUsername", handler, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("TelegramPlatformIds.", handler, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("command.TelegramUserId", handler, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("command.TelegramUsername", handler, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LeaveSessionHandler_ShouldFindParticipantsByPlatformIdentity()
|
||||
{
|
||||
var handler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/CreateSession/LeaveSessionHandler.cs");
|
||||
|
||||
Assert.Contains("p.platform = @Platform", handler, StringComparison.Ordinal);
|
||||
Assert.Contains("p.external_user_id = @ExternalUserId", handler, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("p.telegram_id = @TelegramUserId", handler, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("TelegramPlatformIds.", handler, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("command.TelegramUserId", handler, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SessionInteractionHandlers_ShouldUpdateSchedulesThroughCommandMessageReference()
|
||||
{
|
||||
var joinHandler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/CreateSession/JoinSessionHandler.cs");
|
||||
var leaveHandler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/CreateSession/LeaveSessionHandler.cs");
|
||||
|
||||
Assert.Contains("new PlatformScheduleMessage(", joinHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("command.Group", joinHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("command.ScheduleMessage", joinHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("new PlatformScheduleMessage(", leaveHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("command.Group", leaveHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("command.ScheduleMessage", leaveHandler, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static async Task<string> ReadRepositoryFileAsync(string relativePath)
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null)
|
||||
{
|
||||
var candidate = Path.Combine(directory.FullName, relativePath);
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return await File.ReadAllTextAsync(candidate);
|
||||
}
|
||||
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
throw new FileNotFoundException($"Could not locate repository file '{relativePath}'.");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add failing migration assertion**
|
||||
|
||||
Append to `PlatformIdentityMigrationTests`:
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public async Task MigrationV017_ShouldAllowPlayersWithoutLegacyTelegramId()
|
||||
{
|
||||
var migration = await ReadRepositoryFileAsync("src/GmRelay.Bot/Migrations/V017__allow_platform_neutral_players.sql");
|
||||
|
||||
Assert.Contains("ALTER TABLE players", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("telegram_id DROP NOT NULL", migration, StringComparison.Ordinal);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify RED**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
dotnet test .\tests\GmRelay.Bot.Tests\GmRelay.Bot.Tests.csproj --filter "PlatformNeutralSessionInteractionSqlTests|MigrationV017_ShouldAllowPlayersWithoutLegacyTelegramId"
|
||||
```
|
||||
|
||||
Expected: FAIL because handlers still use Telegram-specific properties and the V017 migration file does not exist.
|
||||
|
||||
## Task 3: GREEN - Add Migration
|
||||
|
||||
**Files:**
|
||||
- Create: `src/GmRelay.Bot/Migrations/V017__allow_platform_neutral_players.sql`
|
||||
|
||||
- [ ] **Step 1: Create the migration**
|
||||
|
||||
```sql
|
||||
-- =============================================================
|
||||
-- V017: Allow platform-neutral players
|
||||
-- =============================================================
|
||||
-- Legacy Telegram identity columns remain for backward compatibility,
|
||||
-- but non-Telegram platform users do not have Telegram ids.
|
||||
-- =============================================================
|
||||
|
||||
ALTER TABLE players
|
||||
ALTER COLUMN telegram_id DROP NOT NULL;
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify migration test turns green**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
dotnet test .\tests\GmRelay.Bot.Tests\GmRelay.Bot.Tests.csproj --filter MigrationV017_ShouldAllowPlayersWithoutLegacyTelegramId
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
## Task 4: GREEN - Refactor JoinSessionCommand and Handler
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/CreateSession/JoinSessionHandler.cs`
|
||||
|
||||
- [ ] **Step 1: Replace command record**
|
||||
|
||||
Replace the existing `JoinSessionCommand` declaration with:
|
||||
|
||||
```csharp
|
||||
public sealed record JoinSessionCommand(
|
||||
Guid SessionId,
|
||||
PlatformUser User,
|
||||
string InteractionId,
|
||||
PlatformGroup Group,
|
||||
PlatformMessageRef ScheduleMessage);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Replace player upsert**
|
||||
|
||||
Use platform identity parameters:
|
||||
|
||||
```csharp
|
||||
var platform = command.User.Platform.ToString();
|
||||
var legacyTelegramId = command.User.Platform == PlatformKind.Telegram
|
||||
? long.Parse(command.User.ExternalUserId, CultureInfo.InvariantCulture)
|
||||
: (long?)null;
|
||||
var legacyTelegramUsername = command.User.Platform == PlatformKind.Telegram
|
||||
? command.User.ExternalUsername
|
||||
: null;
|
||||
|
||||
var playerId = await connection.ExecuteScalarAsync<Guid>(
|
||||
@"INSERT INTO players (telegram_id, display_name, telegram_username, platform, external_user_id, external_username)
|
||||
VALUES (@LegacyTelegramId, @Name, @LegacyTelegramUsername, @Platform, @ExternalUserId, @ExternalUsername)
|
||||
ON CONFLICT (platform, external_user_id)
|
||||
WHERE platform IS NOT NULL AND external_user_id IS NOT NULL
|
||||
DO UPDATE
|
||||
SET display_name = EXCLUDED.display_name,
|
||||
telegram_username = COALESCE(EXCLUDED.telegram_username, players.telegram_username),
|
||||
platform = EXCLUDED.platform,
|
||||
external_user_id = EXCLUDED.external_user_id,
|
||||
external_username = EXCLUDED.external_username
|
||||
RETURNING id;",
|
||||
new
|
||||
{
|
||||
LegacyTelegramId = legacyTelegramId,
|
||||
Name = command.User.DisplayName,
|
||||
LegacyTelegramUsername = legacyTelegramUsername,
|
||||
Platform = platform,
|
||||
command.User.ExternalUserId,
|
||||
command.User.ExternalUsername
|
||||
},
|
||||
transaction);
|
||||
```
|
||||
|
||||
Add `using System.Globalization;` at the top.
|
||||
|
||||
- [ ] **Step 3: Update participant display query**
|
||||
|
||||
Change the participant projection to prefer platform-neutral username:
|
||||
|
||||
```sql
|
||||
COALESCE(p.external_username, p.telegram_username) as TelegramUsername
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Update schedule message and interaction reply usage**
|
||||
|
||||
Use:
|
||||
|
||||
```csharp
|
||||
await messenger.UpdateScheduleAsync(
|
||||
new PlatformScheduleMessage(
|
||||
command.Group,
|
||||
view,
|
||||
command.ScheduleMessage),
|
||||
ct);
|
||||
```
|
||||
|
||||
and:
|
||||
|
||||
```csharp
|
||||
private Task AnswerAsync(string interactionId, string text, CancellationToken ct) =>
|
||||
messenger.AnswerInteractionAsync(new PlatformInteractionReply(interactionId, text), ct);
|
||||
```
|
||||
|
||||
Replace all `command.CallbackQueryId` calls with `command.InteractionId`.
|
||||
|
||||
- [ ] **Step 5: Verify command and SQL tests for join**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
dotnet test .\tests\GmRelay.Bot.Tests\GmRelay.Bot.Tests.csproj --filter "JoinSessionCommand_ShouldExposePlatformNeutralInteractionContext|JoinSessionHandler_ShouldPersistPlayersByPlatformIdentity"
|
||||
```
|
||||
|
||||
Expected: PASS for join-focused tests.
|
||||
|
||||
## Task 5: GREEN - Refactor LeaveSessionCommand and Handler
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Bot/Features/Sessions/CreateSession/LeaveSessionHandler.cs`
|
||||
|
||||
- [ ] **Step 1: Replace command record**
|
||||
|
||||
Replace the existing `LeaveSessionCommand` declaration with:
|
||||
|
||||
```csharp
|
||||
public sealed record LeaveSessionCommand(
|
||||
Guid SessionId,
|
||||
PlatformUser User,
|
||||
string InteractionId,
|
||||
PlatformGroup Group,
|
||||
PlatformMessageRef ScheduleMessage);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Replace participant lookup**
|
||||
|
||||
Use platform identity instead of Telegram id:
|
||||
|
||||
```csharp
|
||||
var platform = command.User.Platform.ToString();
|
||||
|
||||
var participant = await connection.QuerySingleOrDefaultAsync<LeaveSessionParticipantDto>(
|
||||
"""
|
||||
SELECT sp.id AS ParticipantRowId,
|
||||
p.display_name AS DisplayName,
|
||||
sp.registration_status AS RegistrationStatus
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.session_id = @SessionId
|
||||
AND p.platform = @Platform
|
||||
AND p.external_user_id = @ExternalUserId
|
||||
AND sp.is_gm = false
|
||||
FOR UPDATE OF sp
|
||||
""",
|
||||
new { command.SessionId, Platform = platform, command.User.ExternalUserId },
|
||||
transaction);
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Update participant display query**
|
||||
|
||||
Change the participant projection to:
|
||||
|
||||
```sql
|
||||
COALESCE(p.external_username, p.telegram_username) AS TelegramUsername
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Update schedule message and interaction reply usage**
|
||||
|
||||
Use:
|
||||
|
||||
```csharp
|
||||
await messenger.UpdateScheduleAsync(
|
||||
new PlatformScheduleMessage(
|
||||
command.Group,
|
||||
view,
|
||||
command.ScheduleMessage),
|
||||
ct);
|
||||
```
|
||||
|
||||
Replace all `command.CallbackQueryId` calls with `command.InteractionId`.
|
||||
|
||||
- [ ] **Step 5: Verify leave tests**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
dotnet test .\tests\GmRelay.Bot.Tests\GmRelay.Bot.Tests.csproj --filter "LeaveSessionCommand_ShouldExposePlatformNeutralInteractionContext|LeaveSessionHandler_ShouldFindParticipantsByPlatformIdentity|SessionInteractionHandlers_ShouldUpdateSchedulesThroughCommandMessageReference"
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
## Task 6: GREEN - Convert Telegram Router to Neutral Commands
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.Bot/Infrastructure/Telegram/UpdateRouter.cs`
|
||||
|
||||
- [ ] **Step 1: Add local conversion values in `HandleCallbackQueryAsync`**
|
||||
|
||||
After parsing `action`, add:
|
||||
|
||||
```csharp
|
||||
var user = TelegramPlatformIds.User(
|
||||
query.From.Id,
|
||||
query.From.FirstName + (string.IsNullOrEmpty(query.From.LastName) ? "" : $" {query.From.LastName}"),
|
||||
query.From.Username);
|
||||
var group = TelegramPlatformIds.Group(message.Chat.Id, message.MessageThreadId, message.Chat.Title);
|
||||
var scheduleMessage = TelegramPlatformIds.Message(message.Chat.Id, message.MessageThreadId, message.MessageId);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Update join command construction**
|
||||
|
||||
```csharp
|
||||
var command = new JoinSessionCommand(
|
||||
SessionId: joinSessionId,
|
||||
User: user,
|
||||
InteractionId: query.Id,
|
||||
Group: group,
|
||||
ScheduleMessage: scheduleMessage);
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Update leave command construction**
|
||||
|
||||
```csharp
|
||||
var command = new LeaveSessionCommand(
|
||||
SessionId: leaveSessionId,
|
||||
User: user,
|
||||
InteractionId: query.Id,
|
||||
Group: group,
|
||||
ScheduleMessage: scheduleMessage);
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify compile**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
dotnet test .\tests\GmRelay.Bot.Tests\GmRelay.Bot.Tests.csproj --filter PlatformNeutralSessionInteractionCommandTests
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
## Task 7: REFACTOR - Clean Up and Full Test Pass
|
||||
|
||||
**Files:**
|
||||
- Modify only files already listed if cleanup is needed.
|
||||
|
||||
- [ ] **Step 1: Remove now-unused Telegram handler imports**
|
||||
|
||||
Check `JoinSessionHandler.cs` and `LeaveSessionHandler.cs` for unused:
|
||||
|
||||
```csharp
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
```
|
||||
|
||||
Remove it from handlers if no longer needed.
|
||||
|
||||
- [ ] **Step 2: Run focused tests**
|
||||
|
||||
```powershell
|
||||
dotnet test .\tests\GmRelay.Bot.Tests\GmRelay.Bot.Tests.csproj --filter "PlatformNeutralSessionInteractionCommandTests|PlatformNeutralSessionInteractionSqlTests|PlatformIdentityMigrationTests"
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 3: Run full test suite**
|
||||
|
||||
```powershell
|
||||
dotnet test .\GM-Relay.slnx
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 4: Build solution**
|
||||
|
||||
```powershell
|
||||
dotnet build .\GM-Relay.slnx
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
## Task 8: Version Bump
|
||||
|
||||
**Files:**
|
||||
- Modify: `Directory.Build.props`
|
||||
- Modify: `compose.yaml`
|
||||
- Modify: `.gitea/workflows/deploy.yml`
|
||||
- Modify: `src/GmRelay.Web/Components/Layout/NavMenu.razor`
|
||||
|
||||
- [ ] **Step 1: Update version from `2.1.0` to `2.1.1`**
|
||||
|
||||
Expected exact replacements:
|
||||
|
||||
```xml
|
||||
<Version>2.1.1</Version>
|
||||
```
|
||||
|
||||
```yaml
|
||||
VERSION: 2.1.1
|
||||
```
|
||||
|
||||
```yaml
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-bot:2.1.1
|
||||
image: git.codeanddice.ru/toutsu/gmrelay-web:2.1.1
|
||||
```
|
||||
|
||||
```razor
|
||||
<div class="nav-version">v2.1.1</div>
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify synchronized versions**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
rg "<Version>|image: git.codeanddice.ru/toutsu/gmrelay-|VERSION:|nav-version" Directory.Build.props compose.yaml .gitea\workflows\deploy.yml src\GmRelay.Web\Components\Layout\NavMenu.razor
|
||||
```
|
||||
|
||||
Expected: all project image/app/deploy UI versions show `2.1.1`.
|
||||
|
||||
## Task 9: PR, CI, Review, Merge, Deploy, Release
|
||||
|
||||
**Files:**
|
||||
- No additional source changes expected.
|
||||
|
||||
- [ ] **Step 1: Create branch after approval**
|
||||
|
||||
```powershell
|
||||
git checkout -b refactor/issue-25-platform-neutral-join-leave
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Stage only intended files**
|
||||
|
||||
```powershell
|
||||
git add docs/superpowers/plans/2026-05-18-platform-neutral-join-leave.md tests/GmRelay.Bot.Tests/Features/Sessions/CreateSession/PlatformNeutralSessionInteractionCommandTests.cs tests/GmRelay.Bot.Tests/Features/Sessions/CreateSession/PlatformNeutralSessionInteractionSqlTests.cs tests/GmRelay.Bot.Tests/Infrastructure/Database/PlatformIdentityMigrationTests.cs src/GmRelay.Bot/Migrations/V017__allow_platform_neutral_players.sql src/GmRelay.Bot/Features/Sessions/CreateSession/JoinSessionHandler.cs src/GmRelay.Bot/Features/Sessions/CreateSession/LeaveSessionHandler.cs src/GmRelay.Bot/Infrastructure/Telegram/UpdateRouter.cs Directory.Build.props compose.yaml .gitea/workflows/deploy.yml src/GmRelay.Web/Components/Layout/NavMenu.razor
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```powershell
|
||||
git commit -m "refactor: make session join leave platform-neutral"
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Push and create Gitea PR**
|
||||
|
||||
```powershell
|
||||
git push -u origin refactor/issue-25-platform-neutral-join-leave
|
||||
```
|
||||
|
||||
PR title:
|
||||
|
||||
```text
|
||||
refactor: make session join leave platform-neutral
|
||||
```
|
||||
|
||||
PR body:
|
||||
|
||||
```markdown
|
||||
## Summary
|
||||
- Closes #25.
|
||||
- Converts join/leave session interaction commands from Telegram-specific fields to platform-neutral `PlatformUser`, `PlatformGroup`, and `PlatformMessageRef`.
|
||||
- Persists and looks up session participants by `(platform, external_user_id)`.
|
||||
- Keeps Telegram callback data and schedule update behavior intact.
|
||||
|
||||
## Test plan
|
||||
- `dotnet test .\tests\GmRelay.Bot.Tests\GmRelay.Bot.Tests.csproj --filter "PlatformNeutralSessionInteractionCommandTests|PlatformNeutralSessionInteractionSqlTests|PlatformIdentityMigrationTests"`
|
||||
- `dotnet test .\GM-Relay.slnx`
|
||||
- `dotnet build .\GM-Relay.slnx`
|
||||
|
||||
## Workflow
|
||||
- [ ] CI passes
|
||||
- [ ] Code review approved
|
||||
- [ ] Deployed
|
||||
- [ ] Release published
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Watch CI, request review, merge, deploy, release**
|
||||
|
||||
Use Gitea MCP for PR creation, CI polling, review, merge, deploy monitoring, and release `v2.1.1`. Close issue #25 after release and add a comment linking the PR and release.
|
||||
|
||||
## Self-Review
|
||||
|
||||
- Spec coverage: issue scope is covered by neutral command records, Telegram adapter conversion, platform identity SQL, messenger-based schedule updates, and tests.
|
||||
- Placeholder scan: no `TBD`, `TODO`, or "fill later" steps remain.
|
||||
- Type consistency: commands consistently use `PlatformUser User`, `string InteractionId`, `PlatformGroup Group`, and `PlatformMessageRef ScheduleMessage`.
|
||||
@@ -0,0 +1,984 @@
|
||||
# Discord /newsession и /listsessions — Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:test-driven-development (TDD) for every task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Реализовать slash-команды `/newsession` и `/listsessions` в Discord-боте, позволяющие создавать батчи сессий и просматривать расписание без Web Dashboard.
|
||||
|
||||
**Architecture:** Каждая команда — отдельный vertical slice в `GmRelay.DiscordBot`: парсер входных данных → handler с SQL (через Dapper) → отправка через NetCord REST API. Рендеринг переиспользует существующий `DiscordSessionBatchRenderer`. Данные пишутся в общую PostgreSQL модель через platform-agnostic колонки (`platform`, `external_group_id`, `external_user_id`).
|
||||
|
||||
**Tech Stack:** .NET 10, NetCord 1.0.0-alpha.489, NetCord.Hosting.Services, Dapper, Npgsql, xUnit.
|
||||
|
||||
**Version Bump:** minor (2.3.0 → 2.4.0) — новый функционал.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
| File | Responsibility |
|
||||
|------|--------------|
|
||||
| `src/GmRelay.DiscordBot/Features/Sessions/DiscordNewSessionCommand.cs` | Slash-команда `/newsession` с параметрами (title, time, seats, link) |
|
||||
| `src/GmRelay.DiscordBot/Features/Sessions/DiscordNewSessionHandler.cs` | Handler создания batch + sessions в БД, проверка прав |
|
||||
| `src/GmRelay.DiscordBot/Features/Sessions/DiscordListSessionsCommand.cs` | Slash-команда `/listsessions` |
|
||||
| `src/GmRelay.DiscordBot/Features/Sessions/DiscordListSessionsHandler.cs` | Handler запроса активных сессий и публикации embed |
|
||||
| `src/GmRelay.DiscordBot/Infrastructure/Discord/DiscordPermissionChecker.cs` | Проверка прав пользователя в guild (owner/admin/manager) |
|
||||
| `src/GmRelay.DiscordBot/Infrastructure/Discord/DiscordPlatformMessenger.cs` | Реализация `IPlatformMessenger` для отправки/обновления расписания в Discord |
|
||||
| `tests/GmRelay.Bot.Tests/Discord/DiscordNewSessionHandlerTests.cs` | TDD-тесты создания сессий из Discord |
|
||||
| `tests/GmRelay.Bot.Tests/Discord/DiscordListSessionsHandlerTests.cs` | TDD-тесты вывода расписания |
|
||||
| `tests/GmRelay.Bot.Tests/Discord/DiscordPermissionCheckerTests.cs` | TDD-тесты проверки прав |
|
||||
| `src/GmRelay.DiscordBot/Program.cs` | Регистрация DI: handlers, permission checker, platform messenger |
|
||||
|
||||
---
|
||||
|
||||
## Task 1: DiscordPermissionChecker
|
||||
|
||||
**Files:**
|
||||
- Create: `src/GmRelay.DiscordBot/Infrastructure/Discord/DiscordPermissionChecker.cs`
|
||||
- Test: `tests/GmRelay.Bot.Tests/Discord/DiscordPermissionCheckerTests.cs`
|
||||
|
||||
**Context:** Discord использует guild-роли. Для MVP достаточно проверки: пользователь — owner guild, имеет роль `Administrator`, или записан как `group_managers` в БД для данной `game_groups`.
|
||||
|
||||
### Step 1.1: Write the failing test
|
||||
|
||||
```csharp
|
||||
using GmRelay.DiscordBot.Infrastructure.Discord;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
public sealed class DiscordPermissionCheckerTests
|
||||
{
|
||||
[Fact]
|
||||
public void CanManageSchedule_WhenUserIsGuildOwner_ReturnsTrue()
|
||||
{
|
||||
var checker = new DiscordPermissionChecker();
|
||||
var result = checker.CanManageSchedule(
|
||||
guildOwnerId: 123456789ul,
|
||||
userId: 123456789ul,
|
||||
userRoles: Array.Empty<ulong>(),
|
||||
dbManagerUserIds: Array.Empty<ulong>());
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CanManageSchedule_WhenUserHasAdministratorRole_ReturnsTrue()
|
||||
{
|
||||
var checker = new DiscordPermissionChecker();
|
||||
var adminRole = 999ul;
|
||||
var result = checker.CanManageSchedule(
|
||||
guildOwnerId: 123456789ul,
|
||||
userId: 987654321ul,
|
||||
userRoles: new[] { adminRole },
|
||||
dbManagerUserIds: Array.Empty<ulong>());
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CanManageSchedule_WhenUserIsDbManager_ReturnsTrue()
|
||||
{
|
||||
var checker = new DiscordPermissionChecker();
|
||||
var managerId = 555ul;
|
||||
var result = checker.CanManageSchedule(
|
||||
guildOwnerId: 123456789ul,
|
||||
userId: managerId,
|
||||
userRoles: Array.Empty<ulong>(),
|
||||
dbManagerUserIds: new[] { managerId });
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CanManageSchedule_WhenRegularUser_ReturnsFalse()
|
||||
{
|
||||
var checker = new DiscordPermissionChecker();
|
||||
var result = checker.CanManageSchedule(
|
||||
guildOwnerId: 123456789ul,
|
||||
userId: 111ul,
|
||||
userRoles: Array.Empty<ulong>(),
|
||||
dbManagerUserIds: new[] { 222ul });
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 1.2: Run test to verify it fails
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter "FullyQualifiedName~DiscordPermissionCheckerTests" --verbosity normal`
|
||||
Expected: FAIL — `DiscordPermissionChecker` not found.
|
||||
|
||||
### Step 1.3: Write minimal implementation
|
||||
|
||||
Create `src/GmRelay.DiscordBot/Infrastructure/Discord/DiscordPermissionChecker.cs`:
|
||||
|
||||
```csharp
|
||||
namespace GmRelay.DiscordBot.Infrastructure.Discord;
|
||||
|
||||
public sealed class DiscordPermissionChecker
|
||||
{
|
||||
// Discord Administrator permission bitflag
|
||||
private const ulong AdministratorPermission = 0x8;
|
||||
|
||||
public bool CanManageSchedule(
|
||||
ulong guildOwnerId,
|
||||
ulong userId,
|
||||
IEnumerable<ulong> userRoles,
|
||||
IEnumerable<ulong> dbManagerUserIds)
|
||||
{
|
||||
if (userId == guildOwnerId)
|
||||
return true;
|
||||
|
||||
if (dbManagerUserIds.Contains(userId))
|
||||
return true;
|
||||
|
||||
// NetCord provides permission resolution via GuildUser.Permissions;
|
||||
// here we accept pre-resolved flag for simplicity.
|
||||
// Actual command handler will pass resolved permissions.
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool CanManageSchedule(ulong guildOwnerId, ulong userId, IEnumerable<ulong> dbManagerUserIds, ulong resolvedPermissions)
|
||||
{
|
||||
if (userId == guildOwnerId)
|
||||
return true;
|
||||
|
||||
if (dbManagerUserIds.Contains(userId))
|
||||
return true;
|
||||
|
||||
return (resolvedPermissions & AdministratorPermission) == AdministratorPermission;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 1.4: Run test to verify it passes
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter "FullyQualifiedName~DiscordPermissionCheckerTests" --verbosity normal`
|
||||
Expected: PASS (4/4).
|
||||
|
||||
### Step 1.5: Commit
|
||||
|
||||
```bash
|
||||
git add src/GmRelay.DiscordBot/Infrastructure/Discord/DiscordPermissionChecker.cs tests/GmRelay.Bot.Tests/Discord/DiscordPermissionCheckerTests.cs
|
||||
git commit -m "feat(discord): add DiscordPermissionChecker for session management rights
|
||||
|
||||
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: DiscordListSessionsHandler + Command
|
||||
|
||||
**Files:**
|
||||
- Create: `src/GmRelay.DiscordBot/Features/Sessions/DiscordListSessionsHandler.cs`
|
||||
- Create: `src/GmRelay.DiscordBot/Features/Sessions/DiscordListSessionsCommand.cs`
|
||||
- Test: `tests/GmRelay.Bot.Tests/Discord/DiscordListSessionsHandlerTests.cs`
|
||||
|
||||
**Context:** Handler должен:
|
||||
1. Найти `game_groups` по `external_group_id` = `guild_id`.
|
||||
2. Выбрать предстоящие сессии (`scheduled_at > NOW()`, `status != Cancelled`).
|
||||
3. Собрать участников.
|
||||
4. Построить view через `SessionBatchViewBuilder`.
|
||||
5. Отрендерить через `DiscordSessionBatchRenderer`.
|
||||
6. Отправить embed + buttons в Discord channel.
|
||||
|
||||
### Step 2.1: Write the failing test
|
||||
|
||||
Create `tests/GmRelay.Bot.Tests/Discord/DiscordListSessionsHandlerTests.cs`:
|
||||
|
||||
```csharp
|
||||
using GmRelay.DiscordBot.Features.Sessions;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
public sealed class DiscordListSessionsHandlerTests
|
||||
{
|
||||
[Fact]
|
||||
public void BuildSchedule_WithSessions_ReturnsEmbedsAndButtons()
|
||||
{
|
||||
var sessionId = Guid.NewGuid();
|
||||
var sessions = new[]
|
||||
{
|
||||
new SessionBatchDto(sessionId, DateTime.UtcNow.AddDays(1), SessionStatus.Planned, 4, "https://example.com")
|
||||
};
|
||||
var participants = Array.Empty<ParticipantBatchDto>();
|
||||
|
||||
var view = SessionBatchViewBuilder.Build("Test Campaign", sessions, participants);
|
||||
var (embeds, actionRows) = GmRelay.DiscordBot.Rendering.DiscordSessionBatchRenderer.Render(view);
|
||||
|
||||
Assert.Single(embeds);
|
||||
Assert.Single(actionRows);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildSchedule_WithCancelledSession_SkipsActionRows()
|
||||
{
|
||||
var cancelledSessionId = Guid.NewGuid();
|
||||
var sessions = new[] { new SessionBatchDto(cancelledSessionId, DateTime.UtcNow.AddDays(1), SessionStatus.Cancelled, null, "") };
|
||||
var participants = Array.Empty<ParticipantBatchDto>();
|
||||
|
||||
var view = SessionBatchViewBuilder.Build("Test Campaign", sessions, participants);
|
||||
var (embeds, actionRows) = GmRelay.DiscordBot.Rendering.DiscordSessionBatchRenderer.Render(view);
|
||||
|
||||
Assert.Single(embeds);
|
||||
Assert.Empty(actionRows);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2.2: Run test — verify RED
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter "FullyQualifiedName~DiscordListSessionsHandlerTests" --verbosity normal`
|
||||
Expected: FAIL — `DiscordListSessionsHandler` not found.
|
||||
|
||||
### Step 2.3: Write minimal implementation
|
||||
|
||||
Create `src/GmRelay.DiscordBot/Features/Sessions/DiscordListSessionsHandler.cs`:
|
||||
|
||||
```csharp
|
||||
using Dapper;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using NetCord.Rest;
|
||||
using Npgsql;
|
||||
|
||||
namespace GmRelay.DiscordBot.Features.Sessions;
|
||||
|
||||
internal sealed record DiscordSessionListItemDto(
|
||||
Guid Id, string Title, DateTime ScheduledAt, string Status, int? MaxPlayers,
|
||||
int PlayerCount, int WaitlistCount);
|
||||
|
||||
public sealed class DiscordListSessionsHandler(NpgsqlDataSource dataSource)
|
||||
{
|
||||
public async Task<SessionBatchViewModel?> BuildScheduleAsync(
|
||||
string guildId,
|
||||
string channelId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using var connection = await dataSource.OpenConnectionAsync(cancellationToken);
|
||||
|
||||
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
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON s.group_id = g.id
|
||||
LEFT JOIN session_participants sp ON s.id = sp.session_id
|
||||
WHERE g.platform = 'Discord'
|
||||
AND g.external_group_id = @GuildId
|
||||
AND s.status != @Cancelled
|
||||
AND s.scheduled_at > NOW()
|
||||
GROUP BY s.id, s.title, s.scheduled_at, s.status, s.max_players
|
||||
ORDER BY s.scheduled_at ASC",
|
||||
new
|
||||
{
|
||||
GuildId = guildId,
|
||||
Cancelled = SessionStatus.Cancelled,
|
||||
Active = ParticipantRegistrationStatus.Active,
|
||||
Waitlisted = ParticipantRegistrationStatus.Waitlisted
|
||||
});
|
||||
|
||||
var sessionList = sessions.ToList();
|
||||
if (sessionList.Count == 0)
|
||||
return null;
|
||||
|
||||
var sessionIds = sessionList.Select(s => s.Id).ToList();
|
||||
var participants = await connection.QueryAsync<ParticipantBatchDto>(
|
||||
@"SELECT sp.session_id as SessionId,
|
||||
p.display_name as DisplayName,
|
||||
COALESCE(p.external_username, p.telegram_username) as TelegramUsername,
|
||||
sp.registration_status as RegistrationStatus
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.session_id = ANY(@SessionIds) AND sp.is_gm = false
|
||||
ORDER BY sp.registration_status ASC, sp.created_at ASC",
|
||||
new { SessionIds = sessionIds });
|
||||
|
||||
var firstTitle = sessionList.First().Title;
|
||||
var batchDtos = sessionList.Select(s => new SessionBatchDto(
|
||||
s.Id, s.ScheduledAt, s.Status, s.MaxPlayers, "")).ToList();
|
||||
|
||||
return SessionBatchViewBuilder.Build(firstTitle, batchDtos, participants.ToList());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Create `src/GmRelay.DiscordBot/Features/Sessions/DiscordListSessionsCommand.cs`:
|
||||
|
||||
```csharp
|
||||
using NetCord.Rest;
|
||||
using NetCord.Services.ApplicationCommands;
|
||||
|
||||
namespace GmRelay.DiscordBot.Features.Sessions;
|
||||
|
||||
[SlashCommand("listsessions", "Show upcoming game sessions in this server")]
|
||||
public class DiscordListSessionsCommand : SlashCommandModule<SlashCommandContext>
|
||||
{
|
||||
private readonly DiscordListSessionsHandler _handler;
|
||||
|
||||
public DiscordListSessionsCommand(DiscordListSessionsHandler handler)
|
||||
{
|
||||
_handler = handler;
|
||||
}
|
||||
|
||||
public override async Task ExecuteAsync()
|
||||
{
|
||||
var guildId = Context.Guild?.Id.ToString()
|
||||
?? throw new InvalidOperationException("This command can only be used in a guild.");
|
||||
var channelId = Context.Channel.Id.ToString();
|
||||
|
||||
var view = await _handler.BuildScheduleAsync(guildId, channelId, Context.CancellationToken);
|
||||
|
||||
if (view is null)
|
||||
{
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message("📭 В этом сервере нет предстоящих игр."));
|
||||
return;
|
||||
}
|
||||
|
||||
var (embeds, actionRows) = Rendering.DiscordSessionBatchRenderer.Render(view);
|
||||
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message(new InteractionMessageProperties()
|
||||
.WithEmbeds(embeds)
|
||||
.WithComponents(actionRows)));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2.4: Run test — verify GREEN
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter "FullyQualifiedName~DiscordListSessionsHandlerTests" --verbosity normal`
|
||||
Expected: PASS.
|
||||
|
||||
### Step 2.5: Commit
|
||||
|
||||
```bash
|
||||
git add src/GmRelay.DiscordBot/Features/Sessions/DiscordListSessionsHandler.cs src/GmRelay.DiscordBot/Features/Sessions/DiscordListSessionsCommand.cs tests/GmRelay.Bot.Tests/Discord/DiscordListSessionsHandlerTests.cs
|
||||
git commit -m "feat(discord): add /listsessions slash command and handler
|
||||
|
||||
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: DiscordNewSessionHandler + Command
|
||||
|
||||
**Files:**
|
||||
- Create: `src/GmRelay.DiscordBot/Features/Sessions/DiscordNewSessionHandler.cs`
|
||||
- Create: `src/GmRelay.DiscordBot/Features/Sessions/DiscordNewSessionCommand.cs`
|
||||
- Test: `tests/GmRelay.Bot.Tests/Discord/DiscordNewSessionHandlerTests.cs`
|
||||
|
||||
**Context:** Handler должен:
|
||||
1. Проверить права пользователя (owner/admin/manager).
|
||||
2. Upsert игрока (GM) в `players` с `platform = 'Discord'`.
|
||||
3. Upsert `game_groups` с `platform = 'Discord'`, `external_group_id = guild_id`.
|
||||
4. Создать batch + sessions.
|
||||
5. Отправить rendered schedule в Discord channel.
|
||||
6. Сохранить `platform_messages` reference.
|
||||
|
||||
### Step 3.1: Write the failing test
|
||||
|
||||
Create `tests/GmRelay.Bot.Tests/Discord/DiscordNewSessionHandlerTests.cs`:
|
||||
|
||||
```csharp
|
||||
using GmRelay.DiscordBot.Features.Sessions;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
public sealed class DiscordNewSessionHandlerTests
|
||||
{
|
||||
[Fact]
|
||||
public void ParseTimeInput_ShouldParseDiscordDateFormat()
|
||||
{
|
||||
var result = DiscordNewSessionHandler.ParseTimeInput("2026-05-20 19:30");
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(2026, result.Value.Year);
|
||||
Assert.Equal(5, result.Value.Month);
|
||||
Assert.Equal(20, result.Value.Day);
|
||||
Assert.Equal(19, result.Value.Hour);
|
||||
Assert.Equal(30, result.Value.Minute);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseTimeInput_ShouldRejectPastDate()
|
||||
{
|
||||
var result = DiscordNewSessionHandler.ParseTimeInput("2020-01-01 00:00");
|
||||
Assert.False(result.IsSuccess);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseTimeInput_ShouldParseRussianDateFormat()
|
||||
{
|
||||
var result = DiscordNewSessionHandler.ParseTimeInput("20.05.2026 19:30");
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(2026, result.Value.Year);
|
||||
Assert.Equal(5, result.Value.Month);
|
||||
Assert.Equal(20, result.Value.Day);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseTimeInput_ShouldRejectInvalidFormat()
|
||||
{
|
||||
var result = DiscordNewSessionHandler.ParseTimeInput("not-a-date");
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.NotNull(result.Error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3.2: Run test — verify RED
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter "FullyQualifiedName~DiscordNewSessionHandlerTests" --verbosity normal`
|
||||
Expected: FAIL — `DiscordNewSessionHandler` not found.
|
||||
|
||||
### Step 3.3: Write minimal implementation
|
||||
|
||||
Create `src/GmRelay.DiscordBot/Features/Sessions/DiscordNewSessionHandler.cs`:
|
||||
|
||||
```csharp
|
||||
using Dapper;
|
||||
using GmRelay.DiscordBot.Infrastructure.Discord;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
|
||||
namespace GmRelay.DiscordBot.Features.Sessions;
|
||||
|
||||
public sealed record TimeParseResult(bool IsSuccess, DateTimeOffset Value, string? Error);
|
||||
|
||||
public sealed class DiscordNewSessionHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
DiscordPermissionChecker permissionChecker,
|
||||
IPlatformMessenger messenger,
|
||||
ILogger<DiscordNewSessionHandler> logger)
|
||||
{
|
||||
public static TimeParseResult ParseTimeInput(string input)
|
||||
{
|
||||
if (DateTimeOffset.TryParseExact(
|
||||
input.Trim(),
|
||||
"yyyy-MM-dd HH:mm",
|
||||
System.Globalization.CultureInfo.InvariantCulture,
|
||||
System.Globalization.DateTimeStyles.AssumeUniversal,
|
||||
out var result))
|
||||
{
|
||||
if (result < DateTimeOffset.UtcNow)
|
||||
return new TimeParseResult(false, default, "Дата находится в прошлом.");
|
||||
|
||||
return new TimeParseResult(true, result.ToUniversalTime(), null);
|
||||
}
|
||||
|
||||
if (DateTimeOffset.TryParseExact(
|
||||
input.Trim(),
|
||||
"dd.MM.yyyy HH:mm",
|
||||
System.Globalization.CultureInfo.InvariantCulture,
|
||||
System.Globalization.DateTimeStyles.AssumeUniversal,
|
||||
out var altResult))
|
||||
{
|
||||
if (altResult < DateTimeOffset.UtcNow)
|
||||
return new TimeParseResult(false, default, "Дата находится в прошлом.");
|
||||
|
||||
return new TimeParseResult(true, altResult.ToUniversalTime(), null);
|
||||
}
|
||||
|
||||
return new TimeParseResult(false, default, "Некорректный формат даты. Используйте YYYY-MM-DD HH:mm или DD.MM.YYYY HH:mm");
|
||||
}
|
||||
|
||||
public async Task<SessionBatchViewModel> HandleAsync(
|
||||
string guildId,
|
||||
string channelId,
|
||||
ulong userId,
|
||||
string userDisplayName,
|
||||
IEnumerable<ulong> userRoles,
|
||||
ulong guildOwnerId,
|
||||
string title,
|
||||
DateTimeOffset scheduledAt,
|
||||
int? maxPlayers,
|
||||
string? joinLink,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using var connection = await dataSource.OpenConnectionAsync(cancellationToken);
|
||||
|
||||
// Resolve db managers
|
||||
var dbManagerUserIds = await connection.QueryAsync<ulong>(
|
||||
@"SELECT CAST(p.external_user_id AS BIGINT)
|
||||
FROM group_managers gm
|
||||
JOIN players p ON p.id = gm.player_id
|
||||
JOIN game_groups g ON g.id = gm.group_id
|
||||
WHERE g.platform = 'Discord' AND g.external_group_id = @GuildId",
|
||||
new { GuildId = guildId });
|
||||
|
||||
if (!permissionChecker.CanManageSchedule(guildOwnerId, userId, userRoles, dbManagerUserIds))
|
||||
{
|
||||
throw new UnauthorizedAccessException("⛔ Только owner, администратор или manager могут создавать сессии.");
|
||||
}
|
||||
|
||||
await using var transaction = await connection.BeginTransactionAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
// Upsert player
|
||||
await connection.ExecuteAsync(
|
||||
@"INSERT INTO players (display_name, platform, external_user_id, external_username)
|
||||
VALUES (@Name, 'Discord', @UserId, @Name)
|
||||
ON CONFLICT (platform, external_user_id)
|
||||
WHERE platform IS NOT NULL AND external_user_id IS NOT NULL
|
||||
DO UPDATE SET display_name = EXCLUDED.display_name,
|
||||
external_username = EXCLUDED.external_username",
|
||||
new { Name = userDisplayName, UserId = userId.ToString() },
|
||||
transaction);
|
||||
|
||||
// Upsert group
|
||||
var groupId = await connection.ExecuteScalarAsync<Guid>(
|
||||
@"INSERT INTO game_groups (name, platform, external_group_id, external_channel_id)
|
||||
VALUES (@GuildId, 'Discord', @GuildId, @ChannelId)
|
||||
ON CONFLICT (platform, external_group_id)
|
||||
WHERE platform IS NOT NULL AND external_group_id IS NOT NULL
|
||||
DO UPDATE SET name = EXCLUDED.name,
|
||||
external_channel_id = COALESCE(EXCLUDED.external_channel_id, game_groups.external_channel_id)
|
||||
RETURNING id",
|
||||
new { GuildId = guildId, ChannelId = channelId },
|
||||
transaction);
|
||||
|
||||
// Ensure manager record
|
||||
await connection.ExecuteAsync(
|
||||
@"INSERT INTO group_managers (group_id, player_id, role)
|
||||
SELECT @GroupId, p.id, @OwnerRole
|
||||
FROM players p
|
||||
WHERE p.platform = 'Discord' AND p.external_user_id = @UserId
|
||||
ON CONFLICT (group_id, player_id) DO NOTHING",
|
||||
new { GroupId = groupId, UserId = userId.ToString(), OwnerRole = GroupManagerRoleExtensions.OwnerValue },
|
||||
transaction);
|
||||
|
||||
// Create batch + session
|
||||
var batchId = Guid.NewGuid();
|
||||
var sessionId = await connection.ExecuteScalarAsync<Guid>(
|
||||
@"INSERT INTO sessions (batch_id, group_id, title, join_link, scheduled_at, status, max_players)
|
||||
VALUES (@BatchId, @GroupId, @Title, @Link, @ScheduledAt, @Status, @MaxPlayers)
|
||||
RETURNING id",
|
||||
new
|
||||
{
|
||||
BatchId = batchId,
|
||||
GroupId = groupId,
|
||||
Title = title,
|
||||
Link = joinLink ?? string.Empty,
|
||||
ScheduledAt = scheduledAt.UtcDateTime,
|
||||
Status = SessionStatus.Planned,
|
||||
MaxPlayers = maxPlayers
|
||||
},
|
||||
transaction);
|
||||
|
||||
await transaction.CommitAsync(cancellationToken);
|
||||
|
||||
var sessions = new[] { new SessionBatchDto(sessionId, scheduledAt.UtcDateTime, SessionStatus.Planned, maxPlayers, joinLink ?? string.Empty) };
|
||||
var view = SessionBatchViewBuilder.Build(title, sessions, Array.Empty<ParticipantBatchDto>());
|
||||
|
||||
await messenger.SendScheduleAsync(
|
||||
new PlatformScheduleMessage(
|
||||
new PlatformGroup(PlatformKind.Discord, guildId, guildId, channelId),
|
||||
view,
|
||||
null),
|
||||
cancellationToken);
|
||||
|
||||
return view;
|
||||
}
|
||||
catch
|
||||
{
|
||||
await transaction.RollbackAsync(cancellationToken);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Create `src/GmRelay.DiscordBot/Features/Sessions/DiscordNewSessionCommand.cs`:
|
||||
|
||||
```csharp
|
||||
using NetCord.Rest;
|
||||
using NetCord.Services.ApplicationCommands;
|
||||
|
||||
namespace GmRelay.DiscordBot.Features.Sessions;
|
||||
|
||||
[SlashCommand("newsession", "Create a new game session")]
|
||||
public class DiscordNewSessionCommand : SlashCommandModule<SlashCommandContext>
|
||||
{
|
||||
private readonly DiscordNewSessionHandler _handler;
|
||||
|
||||
public DiscordNewSessionCommand(DiscordNewSessionHandler handler)
|
||||
{
|
||||
_handler = handler;
|
||||
}
|
||||
|
||||
[SlashCommandOption("title", "Game title", Required = true)]
|
||||
public string Title { get; set; } = string.Empty;
|
||||
|
||||
[SlashCommandOption("time", "Session time (YYYY-MM-DD HH:mm or DD.MM.YYYY HH:mm)", Required = true)]
|
||||
public string Time { get; set; } = string.Empty;
|
||||
|
||||
[SlashCommandOption("seats", "Maximum number of players", Required = false)]
|
||||
public long? Seats { get; set; }
|
||||
|
||||
[SlashCommandOption("link", "Join link", Required = false)]
|
||||
public string? Link { get; set; }
|
||||
|
||||
public override async Task ExecuteAsync()
|
||||
{
|
||||
var guild = Context.Guild
|
||||
?? throw new InvalidOperationException("This command can only be used in a guild.");
|
||||
|
||||
var timeResult = DiscordNewSessionHandler.ParseTimeInput(Time);
|
||||
if (!timeResult.IsSuccess)
|
||||
{
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message($"❌ {timeResult.Error}"));
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var view = await _handler.HandleAsync(
|
||||
guildId: guild.Id.ToString(),
|
||||
channelId: Context.Channel.Id.ToString(),
|
||||
userId: Context.User.Id,
|
||||
userDisplayName: Context.User.GlobalName ?? Context.User.Username,
|
||||
userRoles: Context.GuildUser!.RoleIds,
|
||||
guildOwnerId: guild.OwnerId,
|
||||
title: Title,
|
||||
scheduledAt: timeResult.Value,
|
||||
maxPlayers: Seats is null ? null : (int)Seats.Value,
|
||||
joinLink: Link,
|
||||
Context.CancellationToken);
|
||||
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message("✅ Сессия создана!"));
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message($"⛅ {ex.Message}"));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message("💥 Произошла ошибка при создании сессии."));
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3.4: Run test — verify GREEN
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter "FullyQualifiedName~DiscordNewSessionHandlerTests" --verbosity normal`
|
||||
Expected: PASS.
|
||||
|
||||
### Step 3.5: Commit
|
||||
|
||||
```bash
|
||||
git add src/GmRelay.DiscordBot/Features/Sessions/DiscordNewSessionHandler.cs src/GmRelay.DiscordBot/Features/Sessions/DiscordNewSessionCommand.cs tests/GmRelay.Bot.Tests/Discord/DiscordNewSessionHandlerTests.cs
|
||||
git commit -m "feat(discord): add /newsession slash command and handler
|
||||
|
||||
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: DiscordPlatformMessenger
|
||||
|
||||
**Files:**
|
||||
- Create: `src/GmRelay.DiscordBot/Infrastructure/Discord/DiscordPlatformMessenger.cs`
|
||||
- Test: `tests/GmRelay.Bot.Tests/Discord/DiscordPlatformMessengerTests.cs`
|
||||
|
||||
**Context:** Необходима реализация `IPlatformMessenger` для отправки schedule embeds и обновления существующих сообщений в Discord. Для MVP достаточно `SendScheduleAsync` и `UpdateScheduleAsync` (stub для остальных).
|
||||
|
||||
### Step 4.1: Write the failing test
|
||||
|
||||
Create `tests/GmRelay.Bot.Tests/Discord/DiscordPlatformMessengerTests.cs`:
|
||||
|
||||
```csharp
|
||||
using GmRelay.DiscordBot.Infrastructure.Discord;
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
public sealed class DiscordPlatformMessengerTests
|
||||
{
|
||||
[Fact]
|
||||
public void Constructor_ShouldAcceptRestClient()
|
||||
{
|
||||
// DiscordPlatformMessenger requires a NetCord.Rest.RestClient.
|
||||
// We verify the type can be instantiated (RestClient itself is not easily unit-testable without a real token).
|
||||
// This test proves the contract exists and compiles.
|
||||
var constructor = typeof(DiscordPlatformMessenger).GetConstructor(new[] { typeof(NetCord.Rest.RestClient) });
|
||||
Assert.NotNull(constructor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscordPlatformMessenger_ShouldImplementIPlatformMessenger()
|
||||
{
|
||||
Assert.True(typeof(IPlatformMessenger).IsAssignableFrom(typeof(DiscordPlatformMessenger)));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 4.2: Run test — verify RED
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter "FullyQualifiedName~DiscordPlatformMessengerTests" --verbosity normal`
|
||||
Expected: FAIL — `DiscordPlatformMessenger` not found.
|
||||
|
||||
### Step 4.3: Write minimal implementation
|
||||
|
||||
Create `src/GmRelay.DiscordBot/Infrastructure/Discord/DiscordPlatformMessenger.cs`:
|
||||
|
||||
```csharp
|
||||
using GmRelay.DiscordBot.Rendering;
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using NetCord;
|
||||
using NetCord.Rest;
|
||||
|
||||
namespace GmRelay.DiscordBot.Infrastructure.Discord;
|
||||
|
||||
public sealed class DiscordPlatformMessenger(RestClient restClient) : IPlatformMessenger
|
||||
{
|
||||
public async Task<PlatformMessageRef> SendScheduleAsync(PlatformScheduleMessage message, CancellationToken ct)
|
||||
{
|
||||
var (embeds, actionRows) = DiscordSessionBatchRenderer.Render(message.View);
|
||||
|
||||
var channelId = ulong.Parse(message.Group.ExternalChannelId
|
||||
?? message.Group.ExternalGroupId);
|
||||
|
||||
var msg = await restClient.SendMessageAsync(
|
||||
channelId,
|
||||
new MessageProperties()
|
||||
.WithEmbeds(embeds)
|
||||
.WithComponents(actionRows),
|
||||
ct);
|
||||
|
||||
return new PlatformMessageRef(
|
||||
PlatformKind.Discord,
|
||||
message.Group.ExternalGroupId,
|
||||
null,
|
||||
msg.Id.ToString());
|
||||
}
|
||||
|
||||
public async Task UpdateScheduleAsync(PlatformScheduleMessage message, CancellationToken ct)
|
||||
{
|
||||
if (message.ExistingMessage is null)
|
||||
return;
|
||||
|
||||
var (embeds, actionRows) = DiscordSessionBatchRenderer.Render(message.View);
|
||||
|
||||
var channelId = ulong.Parse(message.Group.ExternalChannelId
|
||||
?? message.Group.ExternalGroupId);
|
||||
var messageId = ulong.Parse(message.ExistingMessage.ExternalMessageId);
|
||||
|
||||
await restClient.ModifyMessageAsync(
|
||||
channelId,
|
||||
messageId,
|
||||
new MessageProperties()
|
||||
.WithEmbeds(embeds)
|
||||
.WithComponents(actionRows),
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task SendGroupMessageAsync(PlatformGroup group, string htmlText, CancellationToken ct)
|
||||
{
|
||||
// MVP: not needed for /newsession and /listsessions
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task SendPrivateMessageAsync(PlatformPrivateMessage message, CancellationToken ct)
|
||||
{
|
||||
// MVP: not needed
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task AnswerInteractionAsync(PlatformInteractionReply reply, CancellationToken ct)
|
||||
{
|
||||
// MVP: not needed (commands answer inline via SlashCommandContext)
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task SendCalendarFileAsync(PlatformCalendarFile file, CancellationToken ct)
|
||||
{
|
||||
// MVP: not needed
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 4.4: Run test — verify GREEN
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter "FullyQualifiedName~DiscordPlatformMessengerTests" --verbosity normal`
|
||||
Expected: PASS.
|
||||
|
||||
### Step 4.5: Commit
|
||||
|
||||
```bash
|
||||
git add src/GmRelay.DiscordBot/Infrastructure/Discord/DiscordPlatformMessenger.cs tests/GmRelay.Bot.Tests/Discord/DiscordPlatformMessengerTests.cs
|
||||
git commit -m "feat(discord): add DiscordPlatformMessenger IPlatformMessenger implementation
|
||||
|
||||
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: Wire up DI and Register Commands
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/GmRelay.DiscordBot/Program.cs`
|
||||
|
||||
### Step 5.1: Write the failing test (structure test)
|
||||
|
||||
Modify `tests/GmRelay.Bot.Tests/Discord/DiscordStartupTests.cs` — add test that asserts new handlers are registered:
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void Program_ShouldRegisterDiscordSessionHandlers()
|
||||
{
|
||||
var program = ReadProgram();
|
||||
Assert.Contains("DiscordListSessionsHandler", program);
|
||||
Assert.Contains("DiscordNewSessionHandler", program);
|
||||
Assert.Contains("DiscordPermissionChecker", program);
|
||||
Assert.Contains("DiscordPlatformMessenger", program);
|
||||
Assert.Contains("IPlatformMessenger", program);
|
||||
}
|
||||
```
|
||||
|
||||
### Step 5.2: Run test — verify RED
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter "FullyQualifiedName~DiscordStartupTests" --verbosity normal`
|
||||
Expected: FAIL — asserts not found in Program.cs.
|
||||
|
||||
### Step 5.3: Write minimal implementation
|
||||
|
||||
Modify `src/GmRelay.DiscordBot/Program.cs`:
|
||||
|
||||
```csharp
|
||||
using GmRelay.DiscordBot.Features.Sessions;
|
||||
using GmRelay.DiscordBot.Infrastructure.Discord;
|
||||
using GmRelay.Shared.Platform;
|
||||
|
||||
// ... existing usings ...
|
||||
|
||||
builder.Services.AddSingleton<DiscordPermissionChecker>();
|
||||
builder.Services.AddSingleton<DiscordListSessionsHandler>();
|
||||
builder.Services.AddSingleton<DiscordNewSessionHandler>();
|
||||
builder.Services.AddSingleton<IPlatformMessenger, DiscordPlatformMessenger>();
|
||||
|
||||
// After host.Build():
|
||||
host.AddSlashCommand("listsessions", "Show upcoming game sessions", async (DiscordListSessionsHandler handler, SlashCommandContext context) =>
|
||||
{
|
||||
// NetCord module-based approach preferred; if AddSlashCommand lambda doesn't support DI injection of custom services,
|
||||
// rely on module classes registered via AddApplicationCommands
|
||||
});
|
||||
```
|
||||
|
||||
**Important:** NetCord module classes (`DiscordListSessionsCommand`, `DiscordNewSessionCommand`) автоматически регистрируются через `AddApplicationCommands()` + `AddGatewayHandlers(typeof(Program).Assembly)`. Constructor injection в модулях работает через DI контейнер. Никаких дополнительных `AddSlashCommand` для модулей не требуется.
|
||||
|
||||
Убедиться, что в Program.cs есть:
|
||||
```csharp
|
||||
builder.Services.AddSingleton<DiscordPermissionChecker>();
|
||||
builder.Services.AddSingleton<DiscordListSessionsHandler>();
|
||||
builder.Services.AddSingleton<DiscordNewSessionHandler>();
|
||||
builder.Services.AddSingleton<IPlatformMessenger, DiscordPlatformMessenger>();
|
||||
```
|
||||
|
||||
### Step 5.4: Run test — verify GREEN
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter "FullyQualifiedName~DiscordStartupTests" --verbosity normal`
|
||||
Expected: PASS.
|
||||
|
||||
### Step 5.5: Commit
|
||||
|
||||
```bash
|
||||
git add src/GmRelay.DiscordBot/Program.cs tests/GmRelay.Bot.Tests/Discord/DiscordStartupTests.cs
|
||||
git commit -m "feat(discord): wire up DI registrations for session handlers and messenger
|
||||
|
||||
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Build Verification
|
||||
|
||||
### Step 6.1: Build DiscordBot project
|
||||
|
||||
Run: `dotnet build src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj --no-restore`
|
||||
Expected: Build succeeds (0 errors, 0 warnings).
|
||||
|
||||
### Step 6.2: Run all tests
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --verbosity normal`
|
||||
Expected: All tests pass.
|
||||
|
||||
### Step 6.3: Commit if any fixes needed
|
||||
|
||||
If build or tests required fixes, commit them.
|
||||
|
||||
---
|
||||
|
||||
## Task 7: Version Bump
|
||||
|
||||
**Files to modify:**
|
||||
- `Directory.Build.props`: `<Version>2.4.0</Version>`
|
||||
- `compose.yaml`: обновить теги `gmrelay-bot`, `gmrelay-web`, `gmrelay-discord-bot` → `2.4.0`
|
||||
- `.gitea/workflows/deploy.yml`: `VERSION: 2.4.0`
|
||||
- `src/GmRelay.Web/Components/Layout/NavMenu.razor`: `<div class="nav-version">v2.4.0</div>`
|
||||
|
||||
### Step 7.1: Bump version
|
||||
|
||||
Apply изменения ко всем 4 файлам.
|
||||
|
||||
### Step 7.2: Update version test
|
||||
|
||||
Modify `tests/GmRelay.Bot.Tests/Discord/DiscordProjectStructureTests.cs` — обновить `Version_ShouldBeSynchronizedForDiscordFeatureRelease` ожидаемое значение на `2.4.0`.
|
||||
|
||||
### Step 7.3: Run version test
|
||||
|
||||
Run: `dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --filter "FullyQualifiedName~Version_ShouldBeSynchronizedForDiscordFeatureRelease" --verbosity normal`
|
||||
Expected: PASS.
|
||||
|
||||
### Step 7.4: Commit
|
||||
|
||||
```bash
|
||||
git add Directory.Build.props compose.yaml .gitea/workflows/deploy.yml src/GmRelay.Web/Components/Layout/NavMenu.razor tests/GmRelay.Bot.Tests/Discord/DiscordProjectStructureTests.cs
|
||||
git commit -m "chore: bump version to 2.4.0
|
||||
|
||||
Synchronized across Directory.Build.props, compose.yaml, deploy.yml, NavMenu.razor
|
||||
|
||||
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Spec Coverage Self-Review
|
||||
|
||||
| Issue Requirement | Task |
|
||||
|---|---|
|
||||
| Slash command `/newsession` | Task 3 |
|
||||
| Slash command `/listsessions` | Task 2 |
|
||||
| Сохранение platform group identity (guild/channel) | Task 3 (game_groups.platform, external_group_id, external_channel_id) |
|
||||
| Минимальная проверка прав | Task 1 + Task 3 |
|
||||
| Данные пишутся в общую PostgreSQL без Telegram-only assumptions | Task 2, 3 SQL используют platform-agnostic колонки |
|
||||
| `/listsessions` публикует/обновляет расписание | Task 2 + Task 4 |
|
||||
|
||||
**Placeholder scan:** Нет TBD, TODO, "implement later". Каждый шаг содержит конкретный код.
|
||||
|
||||
**Type consistency:** `DiscordPermissionChecker.CanManageSchedule` перегружен для resolved permissions (ulong bitflag). Handler передает `Context.GuildUser.RoleIds` и `guild.OwnerId`.
|
||||
|
||||
---
|
||||
|
||||
## Execution Handoff
|
||||
|
||||
**Plan complete and saved to `docs/superpowers/plans/2026-05-19-discord-newsession-listsessions.md`.**
|
||||
|
||||
**Two execution options:**
|
||||
|
||||
1. **Subagent-Driven (recommended)** — I dispatch a fresh subagent per task, review between tasks, fast iteration
|
||||
2. **Inline Execution** — Execute tasks in this session using executing-plans, batch execution with checkpoints for review
|
||||
|
||||
**Which approach?**
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\GmRelay.Bot\GmRelay.Bot.csproj" />
|
||||
<ProjectReference Include="..\GmRelay.DiscordBot\GmRelay.DiscordBot.csproj" />
|
||||
<ProjectReference Include="..\GmRelay.Web\GmRelay.Web.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -8,6 +8,10 @@ builder.AddProject<Projects.GmRelay_Bot>("bot")
|
||||
.WithReference(postgres)
|
||||
.WaitFor(postgres);
|
||||
|
||||
builder.AddProject<Projects.GmRelay_DiscordBot>("discord")
|
||||
.WithReference(postgres)
|
||||
.WaitFor(postgres);
|
||||
|
||||
builder.AddProject<Projects.GmRelay_Web>("web")
|
||||
.WithReference(postgres)
|
||||
.WaitFor(postgres);
|
||||
|
||||
@@ -30,9 +30,15 @@ RUN dotnet publish "GmRelay.Bot.csproj" -c Release -a $TARGETARCH -o /app/publis
|
||||
FROM mcr.microsoft.com/dotnet/runtime-deps:10.0-noble AS final
|
||||
WORKDIR /app
|
||||
|
||||
# Устанавливаем wget для healthcheck
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends wget \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Копируем только AOT-результаты из билда
|
||||
COPY --from=build /app/publish .
|
||||
|
||||
EXPOSE 8081
|
||||
|
||||
USER $APP_UID
|
||||
|
||||
# Запуск скомпилированного AOT бинарного файла напрямую
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types.Enums;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
using GmRelay.Shared.Platform;
|
||||
|
||||
namespace GmRelay.Bot.Features.Notifications;
|
||||
|
||||
public sealed record DirectNotificationRecipient(long TelegramId, string DisplayName);
|
||||
|
||||
public sealed class DirectSessionNotificationSender(
|
||||
ITelegramBotClient bot,
|
||||
IPlatformMessenger messenger,
|
||||
ILogger<DirectSessionNotificationSender> logger)
|
||||
{
|
||||
public async Task SendAsync(
|
||||
@@ -20,11 +20,11 @@ public sealed class DirectSessionNotificationSender(
|
||||
{
|
||||
try
|
||||
{
|
||||
await bot.SendMessage(
|
||||
chatId: recipient.TelegramId,
|
||||
text: htmlText,
|
||||
parseMode: ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
await messenger.SendPrivateMessageAsync(
|
||||
new PlatformPrivateMessage(
|
||||
TelegramPlatformIds.User(recipient.TelegramId, recipient.DisplayName),
|
||||
htmlText),
|
||||
ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
using Dapper;
|
||||
using GmRelay.Bot.Features.Notifications;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
@@ -22,7 +21,7 @@ internal sealed record CancelSessionInfoDto(string Title, Guid BatchId, int? Bat
|
||||
|
||||
public sealed class CancelSessionHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient bot,
|
||||
IPlatformMessenger messenger,
|
||||
DirectSessionNotificationSender directSender,
|
||||
ILogger<CancelSessionHandler> logger)
|
||||
{
|
||||
@@ -52,13 +51,13 @@ public sealed class CancelSessionHandler(
|
||||
|
||||
if (session == null)
|
||||
{
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Сессия не найдена.", cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Сессия не найдена.", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!session.CanManage)
|
||||
{
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Только owner или co-GM может отменять сессию.", showAlert: true, cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Только owner или co-GM может отменять сессию.", ct, showAlert: true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -105,27 +104,24 @@ public sealed class CancelSessionHandler(
|
||||
|
||||
// 4. Перерисовываем сообщение
|
||||
var view = SessionBatchViewBuilder.Build(session.Title, batchSessions.ToList(), batchParticipants.ToList());
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
try
|
||||
{
|
||||
await BatchMessageEditor.EditBatchMessageAsync(
|
||||
bot,
|
||||
chatId: command.ChatId,
|
||||
messageId: session.BatchMessageId ?? command.MessageId,
|
||||
text: renderResult.Text,
|
||||
replyMarkup: renderResult.Markup,
|
||||
var messageId = session.BatchMessageId ?? command.MessageId;
|
||||
await messenger.UpdateScheduleAsync(
|
||||
new PlatformScheduleMessage(
|
||||
TelegramPlatformIds.Group(command.ChatId, command.MessageThreadId),
|
||||
view,
|
||||
TelegramPlatformIds.Message(command.ChatId, command.MessageThreadId, messageId)),
|
||||
ct);
|
||||
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Сессия отменена!", cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Сессия отменена!", ct);
|
||||
|
||||
// Опционально: написать отдельное сообщение в чат
|
||||
await bot.SendMessage(
|
||||
chatId: command.ChatId,
|
||||
messageThreadId: command.MessageThreadId,
|
||||
text: $"❌ <b>Внимание!</b> Сессия \"{System.Net.WebUtility.HtmlEncode(session.Title)}\" отменена.",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
await messenger.SendGroupMessageAsync(
|
||||
TelegramPlatformIds.Group(command.ChatId, command.MessageThreadId),
|
||||
$"❌ <b>Внимание!</b> Сессия \"{System.Net.WebUtility.HtmlEncode(session.Title)}\" отменена.",
|
||||
ct);
|
||||
|
||||
var mode = SessionNotificationModeExtensions.FromDatabaseValue(session.NotificationMode);
|
||||
if (mode.ShouldSendDirectMessages())
|
||||
@@ -141,7 +137,10 @@ public sealed class CancelSessionHandler(
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to update batch message after cancelling session {SessionId}", command.SessionId);
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Ошибка при обновлении сообщения.", cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Ошибка при обновлении сообщения.", ct);
|
||||
}
|
||||
}
|
||||
|
||||
private Task AnswerAsync(string callbackQueryId, string text, CancellationToken ct, bool showAlert = false) =>
|
||||
messenger.AnswerInteractionAsync(new PlatformInteractionReply(callbackQueryId, text, showAlert), ct);
|
||||
}
|
||||
|
||||
@@ -77,11 +77,14 @@ public sealed class CreateSessionHandler(
|
||||
{
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
INSERT INTO players (telegram_id, display_name, telegram_username)
|
||||
VALUES (@TgId, @Name, @Username)
|
||||
INSERT INTO players (telegram_id, display_name, telegram_username, platform, external_user_id, external_username)
|
||||
VALUES (@TgId, @Name, @Username, 'Telegram', @TgId::TEXT, @Username)
|
||||
ON CONFLICT (telegram_id) DO UPDATE
|
||||
SET display_name = EXCLUDED.display_name,
|
||||
telegram_username = EXCLUDED.telegram_username;
|
||||
telegram_username = EXCLUDED.telegram_username,
|
||||
platform = COALESCE(players.platform, 'Telegram'),
|
||||
external_user_id = COALESCE(players.external_user_id, EXCLUDED.telegram_id::TEXT),
|
||||
external_username = COALESCE(players.external_username, EXCLUDED.telegram_username);
|
||||
""",
|
||||
new { TgId = gmId, Name = gmName, Username = gmUsername },
|
||||
transaction);
|
||||
@@ -94,10 +97,10 @@ public sealed class CreateSessionHandler(
|
||||
FROM group_managers gm
|
||||
JOIN players p ON p.id = gm.player_id
|
||||
WHERE gm.group_id = g.id
|
||||
AND p.telegram_id = @GmId
|
||||
AND COALESCE(p.external_user_id, p.telegram_id::TEXT) = @GmId::TEXT
|
||||
) AS CanManage
|
||||
FROM game_groups g
|
||||
WHERE g.telegram_chat_id = @ChatId
|
||||
WHERE COALESCE(g.external_group_id, g.telegram_chat_id::TEXT) = @ChatId::TEXT
|
||||
""",
|
||||
new { ChatId = chatId, GmId = gmId },
|
||||
transaction);
|
||||
@@ -107,8 +110,8 @@ public sealed class CreateSessionHandler(
|
||||
{
|
||||
groupId = await connection.ExecuteScalarAsync<Guid>(
|
||||
"""
|
||||
INSERT INTO game_groups (telegram_chat_id, name, gm_telegram_id)
|
||||
VALUES (@ChatId, @ChatName, @GmId)
|
||||
INSERT INTO game_groups (telegram_chat_id, name, gm_telegram_id, platform, external_group_id)
|
||||
VALUES (@ChatId, @ChatName, @GmId, 'Telegram', @ChatId::TEXT)
|
||||
RETURNING id;
|
||||
""",
|
||||
new { ChatId = chatId, ChatName = chatTitle, GmId = gmId },
|
||||
@@ -119,7 +122,7 @@ public sealed class CreateSessionHandler(
|
||||
INSERT INTO group_managers (group_id, player_id, role)
|
||||
SELECT @GroupId, p.id, @OwnerRole
|
||||
FROM players p
|
||||
WHERE p.telegram_id = @GmId
|
||||
WHERE COALESCE(p.external_user_id, p.telegram_id::TEXT) = @GmId::TEXT
|
||||
ON CONFLICT (group_id, player_id) DO NOTHING
|
||||
""",
|
||||
new { GroupId = groupId, GmId = gmId, OwnerRole = GroupManagerRoleExtensions.OwnerValue },
|
||||
|
||||
@@ -1,28 +1,25 @@
|
||||
using System.Globalization;
|
||||
using Dapper;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
|
||||
public sealed record JoinSessionCommand(
|
||||
Guid SessionId,
|
||||
long TelegramUserId,
|
||||
string DisplayName,
|
||||
string? TelegramUsername,
|
||||
string CallbackQueryId,
|
||||
long ChatId,
|
||||
int MessageId);
|
||||
PlatformUser User,
|
||||
string InteractionId,
|
||||
PlatformGroup Group,
|
||||
PlatformMessageRef ScheduleMessage);
|
||||
|
||||
// DTOs for AOT compilation
|
||||
internal sealed record JoinSessionBatchDto(Guid BatchId, string Title, int? MaxPlayers);
|
||||
|
||||
public sealed class JoinSessionHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient bot,
|
||||
IPlatformMessenger messenger,
|
||||
ILogger<JoinSessionHandler> logger)
|
||||
{
|
||||
public async Task HandleAsync(JoinSessionCommand command, CancellationToken ct)
|
||||
@@ -34,12 +31,35 @@ public sealed class JoinSessionHandler(
|
||||
try
|
||||
{
|
||||
// 1. Убеждаемся, что игрок есть в базе
|
||||
var platform = command.User.Platform.ToString();
|
||||
var legacyTelegramId = command.User.Platform == PlatformKind.Telegram
|
||||
? long.Parse(command.User.ExternalUserId, CultureInfo.InvariantCulture)
|
||||
: (long?)null;
|
||||
var legacyTelegramUsername = command.User.Platform == PlatformKind.Telegram
|
||||
? command.User.ExternalUsername
|
||||
: null;
|
||||
|
||||
var playerId = await connection.ExecuteScalarAsync<Guid>(
|
||||
@"INSERT INTO players (telegram_id, display_name, telegram_username)
|
||||
VALUES (@TgId, @Name, @Username)
|
||||
ON CONFLICT (telegram_id) DO UPDATE SET display_name = EXCLUDED.display_name, telegram_username = EXCLUDED.telegram_username
|
||||
@"INSERT INTO players (telegram_id, display_name, telegram_username, platform, external_user_id, external_username)
|
||||
VALUES (@LegacyTelegramId, @Name, @LegacyTelegramUsername, @Platform, @ExternalUserId, @ExternalUsername)
|
||||
ON CONFLICT (platform, external_user_id)
|
||||
WHERE platform IS NOT NULL AND external_user_id IS NOT NULL
|
||||
DO UPDATE
|
||||
SET display_name = EXCLUDED.display_name,
|
||||
telegram_username = COALESCE(EXCLUDED.telegram_username, players.telegram_username),
|
||||
platform = EXCLUDED.platform,
|
||||
external_user_id = EXCLUDED.external_user_id,
|
||||
external_username = EXCLUDED.external_username
|
||||
RETURNING id;",
|
||||
new { TgId = command.TelegramUserId, Name = command.DisplayName, Username = command.TelegramUsername },
|
||||
new
|
||||
{
|
||||
LegacyTelegramId = legacyTelegramId,
|
||||
Name = command.User.DisplayName,
|
||||
LegacyTelegramUsername = legacyTelegramUsername,
|
||||
Platform = platform,
|
||||
command.User.ExternalUserId,
|
||||
command.User.ExternalUsername
|
||||
},
|
||||
transaction);
|
||||
|
||||
// 2. Блокируем сессию на время расчета мест, чтобы параллельные нажатия не переполнили состав.
|
||||
@@ -54,7 +74,7 @@ public sealed class JoinSessionHandler(
|
||||
if (batchInfo is null)
|
||||
{
|
||||
await transaction.RollbackAsync(ct);
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Сессия не найдена.", cancellationToken: ct);
|
||||
await AnswerAsync(command.InteractionId, "Сессия не найдена.", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -75,7 +95,7 @@ public sealed class JoinSessionHandler(
|
||||
var alreadyText = existingRegistrationStatus == ParticipantRegistrationStatus.Waitlisted
|
||||
? "Вы уже в листе ожидания!"
|
||||
: "Вы уже записаны!";
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, alreadyText, cancellationToken: ct);
|
||||
await AnswerAsync(command.InteractionId, alreadyText, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -109,7 +129,7 @@ public sealed class JoinSessionHandler(
|
||||
if (inserted == 0)
|
||||
{
|
||||
await transaction.RollbackAsync(ct);
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Вы уже записаны!", cancellationToken: ct);
|
||||
await AnswerAsync(command.InteractionId, "Вы уже записаны!", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -124,7 +144,7 @@ public sealed class JoinSessionHandler(
|
||||
var batchParticipants = await connection.QueryAsync<ParticipantBatchDto>(
|
||||
@"SELECT sp.session_id as SessionId,
|
||||
p.display_name as DisplayName,
|
||||
p.telegram_username as TelegramUsername,
|
||||
COALESCE(p.external_username, p.telegram_username) as TelegramUsername,
|
||||
sp.registration_status as RegistrationStatus
|
||||
FROM session_participants sp
|
||||
JOIN players p ON sp.player_id = p.id
|
||||
@@ -138,20 +158,17 @@ public sealed class JoinSessionHandler(
|
||||
|
||||
// 4. Перерисовываем сообщение
|
||||
var view = SessionBatchViewBuilder.Build(batchInfo.Title, batchSessions.ToList(), batchParticipants.ToList());
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
await BatchMessageEditor.EditBatchMessageAsync(
|
||||
bot,
|
||||
chatId: command.ChatId,
|
||||
messageId: command.MessageId,
|
||||
text: renderResult.Text,
|
||||
replyMarkup: renderResult.Markup,
|
||||
await messenger.UpdateScheduleAsync(
|
||||
new PlatformScheduleMessage(
|
||||
command.Group,
|
||||
view,
|
||||
command.ScheduleMessage),
|
||||
ct);
|
||||
|
||||
var callbackText = registrationStatus == ParticipantRegistrationStatus.Waitlisted
|
||||
? "Основной состав заполнен. Вы добавлены в лист ожидания."
|
||||
: "Вы успешно записаны!";
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, callbackText, cancellationToken: ct);
|
||||
await AnswerAsync(command.InteractionId, callbackText, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -164,7 +181,10 @@ public sealed class JoinSessionHandler(
|
||||
var errorText = transactionCommitted
|
||||
? "Регистрация сохранена, но не удалось обновить сообщение расписания."
|
||||
: "Произошла ошибка при регистрации.";
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, errorText, cancellationToken: ct);
|
||||
await AnswerAsync(command.InteractionId, errorText, ct);
|
||||
}
|
||||
}
|
||||
|
||||
private Task AnswerAsync(string interactionId, string text, CancellationToken ct) =>
|
||||
messenger.AnswerInteractionAsync(new PlatformInteractionReply(interactionId, text), ct);
|
||||
}
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
using Dapper;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
|
||||
public sealed record LeaveSessionCommand(
|
||||
Guid SessionId,
|
||||
long TelegramUserId,
|
||||
string CallbackQueryId,
|
||||
long ChatId,
|
||||
int MessageId);
|
||||
PlatformUser User,
|
||||
string InteractionId,
|
||||
PlatformGroup Group,
|
||||
PlatformMessageRef ScheduleMessage);
|
||||
|
||||
internal sealed record LeaveSessionInfoDto(string Title, Guid BatchId, string Status, int? MaxPlayers);
|
||||
internal sealed record LeaveSessionParticipantDto(Guid ParticipantRowId, string DisplayName, string RegistrationStatus);
|
||||
@@ -20,7 +19,7 @@ internal sealed record LeaveSessionPromotionDto(Guid ParticipantRowId, string Di
|
||||
|
||||
public sealed class LeaveSessionHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient bot,
|
||||
IPlatformMessenger messenger,
|
||||
ILogger<LeaveSessionHandler> logger)
|
||||
{
|
||||
public async Task HandleAsync(LeaveSessionCommand command, CancellationToken ct)
|
||||
@@ -47,17 +46,19 @@ public sealed class LeaveSessionHandler(
|
||||
if (session is null)
|
||||
{
|
||||
await transaction.RollbackAsync(ct);
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Сессия не найдена.", cancellationToken: ct);
|
||||
await AnswerAsync(command.InteractionId, "Сессия не найдена.", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
if (SessionStatus.IsCancelled(session.Status))
|
||||
{
|
||||
await transaction.RollbackAsync(ct);
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Сессия уже отменена.", cancellationToken: ct);
|
||||
await AnswerAsync(command.InteractionId, "Сессия уже отменена.", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
var platform = command.User.Platform.ToString();
|
||||
|
||||
var participant = await connection.QuerySingleOrDefaultAsync<LeaveSessionParticipantDto>(
|
||||
"""
|
||||
SELECT sp.id AS ParticipantRowId,
|
||||
@@ -66,17 +67,18 @@ public sealed class LeaveSessionHandler(
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.session_id = @SessionId
|
||||
AND p.telegram_id = @TelegramUserId
|
||||
AND p.platform = @Platform
|
||||
AND p.external_user_id = @ExternalUserId
|
||||
AND sp.is_gm = false
|
||||
FOR UPDATE OF sp
|
||||
""",
|
||||
new { command.SessionId, command.TelegramUserId },
|
||||
new { command.SessionId, Platform = platform, command.User.ExternalUserId },
|
||||
transaction);
|
||||
|
||||
if (participant is null)
|
||||
{
|
||||
await transaction.RollbackAsync(ct);
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Вы не записаны на эту сессию.", cancellationToken: ct);
|
||||
await AnswerAsync(command.InteractionId, "Вы не записаны на эту сессию.", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -170,7 +172,7 @@ public sealed class LeaveSessionHandler(
|
||||
"""
|
||||
SELECT sp.session_id AS SessionId,
|
||||
p.display_name AS DisplayName,
|
||||
p.telegram_username AS TelegramUsername,
|
||||
COALESCE(p.external_username, p.telegram_username) AS TelegramUsername,
|
||||
sp.registration_status AS RegistrationStatus
|
||||
FROM session_participants sp
|
||||
JOIN players p ON sp.player_id = p.id
|
||||
@@ -185,14 +187,11 @@ public sealed class LeaveSessionHandler(
|
||||
transactionCommitted = true;
|
||||
|
||||
var view = SessionBatchViewBuilder.Build(session.Title, batchSessions, batchParticipants);
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
await BatchMessageEditor.EditBatchMessageAsync(
|
||||
bot,
|
||||
chatId: command.ChatId,
|
||||
messageId: command.MessageId,
|
||||
text: renderResult.Text,
|
||||
replyMarkup: renderResult.Markup,
|
||||
await messenger.UpdateScheduleAsync(
|
||||
new PlatformScheduleMessage(
|
||||
command.Group,
|
||||
view,
|
||||
command.ScheduleMessage),
|
||||
ct);
|
||||
|
||||
var callbackText = participant.RegistrationStatus == ParticipantRegistrationStatus.Waitlisted
|
||||
@@ -201,7 +200,7 @@ public sealed class LeaveSessionHandler(
|
||||
? "Вы отписались от сессии."
|
||||
: $"Вы отписались от сессии. Место получил(а) {promotedDisplayName}.";
|
||||
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, callbackText, cancellationToken: ct);
|
||||
await AnswerAsync(command.InteractionId, callbackText, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -214,7 +213,10 @@ public sealed class LeaveSessionHandler(
|
||||
var errorText = transactionCommitted
|
||||
? "Запись снята, но не удалось обновить сообщение расписания."
|
||||
: "Произошла ошибка при отмене записи.";
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, errorText, cancellationToken: ct);
|
||||
await AnswerAsync(command.InteractionId, errorText, ct);
|
||||
}
|
||||
}
|
||||
|
||||
private Task AnswerAsync(string interactionId, string text, CancellationToken ct) =>
|
||||
messenger.AnswerInteractionAsync(new PlatformInteractionReply(interactionId, text), ct);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
using Dapper;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
@@ -19,7 +19,7 @@ internal sealed record WaitlistedParticipantDto(Guid ParticipantRowId, string Di
|
||||
|
||||
public sealed class PromoteWaitlistedPlayerHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient bot,
|
||||
IPlatformMessenger messenger,
|
||||
ILogger<PromoteWaitlistedPlayerHandler> logger)
|
||||
{
|
||||
public async Task HandleAsync(PromoteWaitlistedPlayerCommand command, CancellationToken ct)
|
||||
@@ -53,14 +53,14 @@ public sealed class PromoteWaitlistedPlayerHandler(
|
||||
if (session is null)
|
||||
{
|
||||
await transaction.RollbackAsync(ct);
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Сессия не найдена.", cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Сессия не найдена.", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!session.CanManage)
|
||||
{
|
||||
await transaction.RollbackAsync(ct);
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Только owner или co-GM может поднимать игроков из листа ожидания.", showAlert: true, cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Только owner или co-GM может поднимать игроков из листа ожидания.", ct, showAlert: true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -89,14 +89,14 @@ public sealed class PromoteWaitlistedPlayerHandler(
|
||||
if (waitlistedParticipants == 0)
|
||||
{
|
||||
await transaction.RollbackAsync(ct);
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Лист ожидания пуст.", cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Лист ожидания пуст.", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!SessionCapacityRules.CanPromoteWaitlistedPlayer(session.MaxPlayers, activeParticipants, waitlistedParticipants))
|
||||
{
|
||||
await transaction.RollbackAsync(ct);
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Нет свободных мест. Увеличьте лимит перед повышением игрока.", showAlert: true, cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Нет свободных мест. Увеличьте лимит перед повышением игрока.", ct, showAlert: true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -165,17 +165,15 @@ public sealed class PromoteWaitlistedPlayerHandler(
|
||||
transactionCommitted = true;
|
||||
|
||||
var view = SessionBatchViewBuilder.Build(session.Title, batchSessions, batchParticipants);
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
await BatchMessageEditor.EditBatchMessageAsync(
|
||||
bot,
|
||||
chatId: command.ChatId,
|
||||
messageId: session.BatchMessageId ?? command.MessageId,
|
||||
text: renderResult.Text,
|
||||
replyMarkup: renderResult.Markup,
|
||||
var messageId = session.BatchMessageId ?? command.MessageId;
|
||||
await messenger.UpdateScheduleAsync(
|
||||
new PlatformScheduleMessage(
|
||||
TelegramPlatformIds.Group(command.ChatId),
|
||||
view,
|
||||
TelegramPlatformIds.Message(command.ChatId, threadId: null, messageId)),
|
||||
ct);
|
||||
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, $"{promoted.DisplayName} переведен(а) в основной состав.", cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, $"{promoted.DisplayName} переведен(а) в основной состав.", ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -188,7 +186,10 @@ public sealed class PromoteWaitlistedPlayerHandler(
|
||||
var errorText = transactionCommitted
|
||||
? "Игрок повышен, но не удалось обновить сообщение расписания."
|
||||
: "Ошибка при обновлении листа ожидания.";
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, errorText, cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, errorText, ct);
|
||||
}
|
||||
}
|
||||
|
||||
private Task AnswerAsync(string callbackQueryId, string text, CancellationToken ct, bool showAlert = false) =>
|
||||
messenger.AnswerInteractionAsync(new PlatformInteractionReply(callbackQueryId, text, showAlert), ct);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
using System.Text;
|
||||
using Dapper;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Platform;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.ExportCalendar;
|
||||
|
||||
@@ -13,7 +13,7 @@ internal sealed record CalendarSessionDto(Guid Id, string Title, DateTime Schedu
|
||||
|
||||
public sealed class ExportCalendarHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient botClient,
|
||||
IPlatformMessenger messenger,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
public async Task HandleAsync(Message message, CancellationToken cancellationToken)
|
||||
@@ -34,10 +34,10 @@ public sealed class ExportCalendarHandler(
|
||||
|
||||
if (sessionsList.Count == 0)
|
||||
{
|
||||
await botClient.SendMessage(
|
||||
chatId: message.Chat.Id,
|
||||
text: "📭 У этой группы нет запланированных сессий для экспорта.",
|
||||
cancellationToken: cancellationToken);
|
||||
await messenger.SendGroupMessageAsync(
|
||||
TelegramPlatformIds.Group(message.Chat.Id, message.MessageThreadId),
|
||||
"📭 У этой группы нет запланированных сессий для экспорта.",
|
||||
cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -63,9 +63,7 @@ public sealed class ExportCalendarHandler(
|
||||
sb.AppendLine("END:VCALENDAR");
|
||||
|
||||
var bytes = Encoding.UTF8.GetBytes(sb.ToString());
|
||||
using var stream = new MemoryStream(bytes);
|
||||
|
||||
var inputFile = InputFile.FromStream(stream, "schedule.ics");
|
||||
|
||||
// Create calendar subscription
|
||||
string? subscriptionUrl = null;
|
||||
@@ -93,20 +91,23 @@ public sealed class ExportCalendarHandler(
|
||||
}
|
||||
}
|
||||
|
||||
var replyMarkup = subscriptionUrl is not null
|
||||
? new InlineKeyboardMarkup(new[]
|
||||
var actions = subscriptionUrl is not null
|
||||
? new[]
|
||||
{
|
||||
new[] { InlineKeyboardButton.WithUrl("🔗 Подписаться на календарь", subscriptionUrl) }
|
||||
})
|
||||
: null;
|
||||
new PlatformMessageAction(
|
||||
"calendar-subscription",
|
||||
"🔗 Подписаться на календарь",
|
||||
subscriptionUrl)
|
||||
}
|
||||
: Array.Empty<PlatformMessageAction>();
|
||||
|
||||
await botClient.SendDocument(
|
||||
chatId: message.Chat.Id,
|
||||
document: inputFile,
|
||||
caption: "📅 <b>Ваш календарь игр!</b>\nОткройте файл на устройстве, чтобы добавить события в свой календарь.",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
replyMarkup: replyMarkup,
|
||||
messageThreadId: message.MessageThreadId,
|
||||
cancellationToken: cancellationToken);
|
||||
await messenger.SendCalendarFileAsync(
|
||||
new PlatformCalendarFile(
|
||||
TelegramPlatformIds.Group(message.Chat.Id, message.MessageThreadId),
|
||||
"schedule.ics",
|
||||
bytes,
|
||||
"📅 <b>Ваш календарь игр!</b>\nОткройте файл на устройстве, чтобы добавить события в свой календарь.",
|
||||
actions),
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
+15
-19
@@ -1,6 +1,7 @@
|
||||
using Dapper;
|
||||
using GmRelay.Bot.Features.Notifications;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
@@ -33,6 +34,7 @@ internal sealed record VoteParticipantDto(
|
||||
public sealed class HandleRescheduleTimeInputHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient bot,
|
||||
IPlatformMessenger messenger,
|
||||
DirectSessionNotificationSender directSender,
|
||||
ILogger<HandleRescheduleTimeInputHandler> logger)
|
||||
{
|
||||
@@ -83,12 +85,10 @@ public sealed class HandleRescheduleTimeInputHandler(
|
||||
// 2. Parse voting input
|
||||
if (!RescheduleVotingInput.TryParse(text, DateTimeOffset.UtcNow, out var votingInput, out var parseError))
|
||||
{
|
||||
await bot.SendMessage(
|
||||
chatId: chatId,
|
||||
messageThreadId: proposal.ThreadId,
|
||||
text: $"⚠️ {parseError}\n\nИспользуйте формат:\n<code>25.04.2026 19:30\n26.04.2026 18:00\nДедлайн: 25.04.2026 12:00</code>",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
await messenger.SendGroupMessageAsync(
|
||||
TelegramPlatformIds.Group(chatId, proposal.ThreadId),
|
||||
$"⚠️ {parseError}\n\nИспользуйте формат:\n<code>25.04.2026 19:30\n26.04.2026 18:00\nДедлайн: 25.04.2026 12:00</code>",
|
||||
ct);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -243,12 +243,10 @@ public sealed class HandleRescheduleTimeInputHandler(
|
||||
|
||||
await transaction.CommitAsync(ct);
|
||||
|
||||
await bot.SendMessage(
|
||||
chatId: chatId,
|
||||
messageThreadId: proposal.ThreadId,
|
||||
text: $"✅ Сессия «{proposal.Title}» перенесена!\n\n📅 Новое время: <b>{newTime.ToOffset(TimeSpan.FromHours(3)).ToString("d MMMM yyyy, HH:mm", System.Globalization.CultureInfo.GetCultureInfo("ru-RU"))}</b> (МСК)\n\n<i>Участников нет — голосование не требуется.</i>",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
await messenger.SendGroupMessageAsync(
|
||||
TelegramPlatformIds.Group(chatId, proposal.ThreadId),
|
||||
$"✅ Сессия «{proposal.Title}» перенесена!\n\n📅 Новое время: <b>{newTime.ToOffset(TimeSpan.FromHours(3)).ToString("d MMMM yyyy, HH:mm", System.Globalization.CultureInfo.GetCultureInfo("ru-RU"))}</b> (МСК)\n\n<i>Участников нет — голосование не требуется.</i>",
|
||||
ct);
|
||||
|
||||
// Re-render batch message with updated time
|
||||
await TryUpdateBatchMessage(proposal, ct);
|
||||
@@ -383,14 +381,12 @@ public sealed class HandleRescheduleTimeInputHandler(
|
||||
if (proposal.BatchMessageId.HasValue)
|
||||
{
|
||||
var view = SessionBatchViewBuilder.Build(proposal.Title, batchSessions, batchParticipants);
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
await BatchMessageEditor.EditBatchMessageAsync(
|
||||
bot,
|
||||
chatId: proposal.TelegramChatId,
|
||||
messageId: proposal.BatchMessageId.Value,
|
||||
text: renderResult.Text,
|
||||
replyMarkup: renderResult.Markup,
|
||||
await messenger.UpdateScheduleAsync(
|
||||
new PlatformScheduleMessage(
|
||||
TelegramPlatformIds.Group(proposal.TelegramChatId, proposal.ThreadId),
|
||||
view,
|
||||
TelegramPlatformIds.Message(proposal.TelegramChatId, proposal.ThreadId, proposal.BatchMessageId.Value)),
|
||||
ct);
|
||||
}
|
||||
else
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Dapper;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Platform;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
|
||||
@@ -22,6 +23,7 @@ internal sealed record VoteProposalDto(
|
||||
public sealed class HandleRescheduleVoteHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient bot,
|
||||
IPlatformMessenger messenger,
|
||||
ILogger<HandleRescheduleVoteHandler> logger)
|
||||
{
|
||||
public async Task HandleAsync(HandleRescheduleVoteCommand command, CancellationToken ct)
|
||||
@@ -46,20 +48,13 @@ public sealed class HandleRescheduleVoteHandler(
|
||||
|
||||
if (proposal is null)
|
||||
{
|
||||
await bot.AnswerCallbackQuery(
|
||||
command.CallbackQueryId,
|
||||
"Голосование уже завершено или не найдено.",
|
||||
cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Голосование уже завершено или не найдено.", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
if (proposal.VotingDeadlineAt <= DateTimeOffset.UtcNow)
|
||||
{
|
||||
await bot.AnswerCallbackQuery(
|
||||
command.CallbackQueryId,
|
||||
"Дедлайн уже прошёл. Результаты скоро будут применены.",
|
||||
showAlert: true,
|
||||
cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Дедлайн уже прошёл. Результаты скоро будут применены.", ct, showAlert: true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -78,10 +73,7 @@ public sealed class HandleRescheduleVoteHandler(
|
||||
|
||||
if (playerId is null)
|
||||
{
|
||||
await bot.AnswerCallbackQuery(
|
||||
command.CallbackQueryId,
|
||||
"Вы не являетесь участником этой сессии.",
|
||||
cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Вы не являетесь участником этой сессии.", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -169,9 +161,9 @@ public sealed class HandleRescheduleVoteHandler(
|
||||
logger.LogWarning(ex, "Failed to update reschedule vote message for proposal {ProposalId}", proposal.Id);
|
||||
}
|
||||
|
||||
await bot.AnswerCallbackQuery(
|
||||
command.CallbackQueryId,
|
||||
"Ваш голос учтён. До дедлайна его можно изменить.",
|
||||
cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Ваш голос учтён. До дедлайна его можно изменить.", ct);
|
||||
}
|
||||
|
||||
private Task AnswerAsync(string callbackQueryId, string text, CancellationToken ct, bool showAlert = false) =>
|
||||
messenger.AnswerInteractionAsync(new PlatformInteractionReply(callbackQueryId, text, showAlert), ct);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
using Dapper;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Platform;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
|
||||
namespace GmRelay.Bot.Features.Sessions.RescheduleSession;
|
||||
|
||||
@@ -28,7 +29,7 @@ internal sealed record RescheduleSessionInfoDto(string Title, bool CanManage);
|
||||
/// </summary>
|
||||
public sealed class InitiateRescheduleHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient bot,
|
||||
IPlatformMessenger messenger,
|
||||
ILogger<InitiateRescheduleHandler> logger)
|
||||
{
|
||||
public async Task HandleAsync(InitiateRescheduleCommand command, CancellationToken ct)
|
||||
@@ -53,14 +54,13 @@ public sealed class InitiateRescheduleHandler(
|
||||
|
||||
if (session is null)
|
||||
{
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId, "Сессия не найдена.", cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Сессия не найдена.", ct);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!session.CanManage)
|
||||
{
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId,
|
||||
"Только owner или co-GM может переносить сессию.", showAlert: true, cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Только owner или co-GM может переносить сессию.", ct, showAlert: true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -76,8 +76,7 @@ public sealed class InitiateRescheduleHandler(
|
||||
|
||||
if (hasActive)
|
||||
{
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId,
|
||||
"Уже есть активный запрос на перенос этой сессии.", showAlert: true, cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Уже есть активный запрос на перенос этой сессии.", ct, showAlert: true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -92,23 +91,28 @@ public sealed class InitiateRescheduleHandler(
|
||||
logger.LogInformation("Reschedule initiated for session {SessionId} by GM {GmId}", command.SessionId, command.TelegramUserId);
|
||||
|
||||
// 4. Prompt GM in chat
|
||||
await bot.AnswerCallbackQuery(command.CallbackQueryId,
|
||||
"Введите 2-3 варианта времени и дедлайн голосования.", cancellationToken: ct);
|
||||
await AnswerAsync(command.CallbackQueryId, "Введите 2-3 варианта времени и дедлайн голосования.", ct);
|
||||
|
||||
await bot.SendMessage(
|
||||
chatId: command.ChatId,
|
||||
messageThreadId: command.MessageThreadId,
|
||||
text: $"""
|
||||
⏰ Укажите 2-3 варианта времени для сессии «{session.Title}» и дедлайн голосования.
|
||||
var prompt = string.Join(
|
||||
"\n",
|
||||
new[]
|
||||
{
|
||||
$"⏰ Укажите 2-3 варианта времени для сессии «{session.Title}» и дедлайн голосования.",
|
||||
"",
|
||||
"Формат:",
|
||||
"<code>25.04.2026 19:30",
|
||||
"26.04.2026 18:00",
|
||||
"Дедлайн: 25.04.2026 12:00</code>",
|
||||
"",
|
||||
"Дедлайн должен быть в будущем и раньше первого предложенного времени."
|
||||
});
|
||||
|
||||
Формат:
|
||||
<code>25.04.2026 19:30
|
||||
26.04.2026 18:00
|
||||
Дедлайн: 25.04.2026 12:00</code>
|
||||
|
||||
Дедлайн должен быть в будущем и раньше первого предложенного времени.
|
||||
""",
|
||||
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
await messenger.SendGroupMessageAsync(
|
||||
TelegramPlatformIds.Group(command.ChatId, command.MessageThreadId),
|
||||
prompt,
|
||||
ct);
|
||||
}
|
||||
|
||||
private Task AnswerAsync(string callbackQueryId, string text, CancellationToken ct, bool showAlert = false) =>
|
||||
messenger.AnswerInteractionAsync(new PlatformInteractionReply(callbackQueryId, text, showAlert), ct);
|
||||
}
|
||||
|
||||
+11
-13
@@ -2,6 +2,7 @@ using Dapper;
|
||||
using GmRelay.Bot.Features.Notifications;
|
||||
using GmRelay.Bot.Infrastructure.Scheduling;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
@@ -26,6 +27,7 @@ internal sealed record DueRescheduleProposalDto(
|
||||
public sealed class RescheduleVotingDeadlineService(
|
||||
NpgsqlDataSource dataSource,
|
||||
ITelegramBotClient bot,
|
||||
IPlatformMessenger messenger,
|
||||
DirectSessionNotificationSender directSender,
|
||||
ISystemClock clock,
|
||||
ILogger<RescheduleVotingDeadlineService> logger) : BackgroundService
|
||||
@@ -312,24 +314,20 @@ public sealed class RescheduleVotingDeadlineService(
|
||||
if (proposal.BatchMessageId.HasValue)
|
||||
{
|
||||
var view = SessionBatchViewBuilder.Build(proposal.Title, batchSessions, batchParticipants);
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(view);
|
||||
|
||||
await BatchMessageEditor.EditBatchMessageAsync(
|
||||
bot,
|
||||
chatId: proposal.TelegramChatId,
|
||||
messageId: proposal.BatchMessageId.Value,
|
||||
text: renderResult.Text,
|
||||
replyMarkup: renderResult.Markup,
|
||||
await messenger.UpdateScheduleAsync(
|
||||
new PlatformScheduleMessage(
|
||||
TelegramPlatformIds.Group(proposal.TelegramChatId, proposal.ThreadId),
|
||||
view,
|
||||
TelegramPlatformIds.Message(proposal.TelegramChatId, proposal.ThreadId, proposal.BatchMessageId.Value)),
|
||||
ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
await bot.SendMessage(
|
||||
chatId: proposal.TelegramChatId,
|
||||
messageThreadId: proposal.ThreadId,
|
||||
text: $"📣 Расписание обновлено после голосования за перенос сессии «{System.Net.WebUtility.HtmlEncode(proposal.Title)}».",
|
||||
parseMode: ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
await messenger.SendGroupMessageAsync(
|
||||
TelegramPlatformIds.Group(proposal.TelegramChatId, proposal.ThreadId),
|
||||
$"📣 Расписание обновлено после голосования за перенос сессии «{System.Net.WebUtility.HtmlEncode(proposal.Title)}».",
|
||||
ct);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
using System.Net;
|
||||
|
||||
namespace GmRelay.Bot.Infrastructure.Health;
|
||||
|
||||
public sealed class BotHealthCheckHostedService : IHostedService
|
||||
{
|
||||
private readonly ILogger<BotHealthCheckHostedService> _logger;
|
||||
private readonly string _prefix;
|
||||
private HttpListener? _listener;
|
||||
private CancellationTokenSource? _cts;
|
||||
private Task? _listenerTask;
|
||||
|
||||
public BotHealthCheckHostedService(
|
||||
ILogger<BotHealthCheckHostedService> logger,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
_logger = logger;
|
||||
_prefix = configuration.GetValue("HealthCheck:Prefix", "http://+:8081/")!;
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_cts = new CancellationTokenSource();
|
||||
_listener = new HttpListener();
|
||||
_listener.Prefixes.Add(_prefix);
|
||||
_listener.Start();
|
||||
|
||||
_logger.LogInformation("Health check server started on {Prefix}", _prefix);
|
||||
|
||||
_listenerTask = Task.Run(async () => await ListenAsync(_cts.Token), cancellationToken);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_cts?.Cancel();
|
||||
_listener?.Stop();
|
||||
|
||||
if (_listenerTask != null)
|
||||
{
|
||||
await Task.WhenAny(_listenerTask, Task.Delay(TimeSpan.FromSeconds(5), cancellationToken));
|
||||
}
|
||||
|
||||
_listener?.Close();
|
||||
_logger.LogInformation("Health check server stopped");
|
||||
}
|
||||
|
||||
private async Task ListenAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (_listener?.IsListening == true && !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var context = await _listener.GetContextAsync();
|
||||
_ = Task.Run(() => HandleRequestAsync(context), cancellationToken);
|
||||
}
|
||||
catch (HttpListenerException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error in health check listener");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleRequestAsync(HttpListenerContext context)
|
||||
{
|
||||
var response = context.Response;
|
||||
try
|
||||
{
|
||||
var request = context.Request;
|
||||
|
||||
if (request.Url?.AbsolutePath == "/health")
|
||||
{
|
||||
response.StatusCode = (int)HttpStatusCode.OK;
|
||||
response.ContentType = "application/json";
|
||||
var body = "{\"status\":\"healthy\"}"u8.ToArray();
|
||||
await response.OutputStream.WriteAsync(body);
|
||||
}
|
||||
else
|
||||
{
|
||||
response.StatusCode = (int)HttpStatusCode.NotFound;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error handling health check request");
|
||||
}
|
||||
finally
|
||||
{
|
||||
response.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System.Globalization;
|
||||
using GmRelay.Shared.Platform;
|
||||
|
||||
namespace GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
internal static class TelegramPlatformIds
|
||||
{
|
||||
public static PlatformGroup Group(long chatId, int? threadId = null, string? displayName = null) =>
|
||||
new(
|
||||
PlatformKind.Telegram,
|
||||
chatId.ToString(CultureInfo.InvariantCulture),
|
||||
displayName ?? "Telegram chat",
|
||||
ExternalChannelId: chatId.ToString(CultureInfo.InvariantCulture),
|
||||
ExternalThreadId: threadId?.ToString(CultureInfo.InvariantCulture));
|
||||
|
||||
public static PlatformUser User(long telegramId, string displayName, string? username = null) =>
|
||||
new(
|
||||
PlatformKind.Telegram,
|
||||
telegramId.ToString(CultureInfo.InvariantCulture),
|
||||
displayName,
|
||||
username);
|
||||
|
||||
public static PlatformMessageRef Message(long chatId, int? threadId, int messageId) =>
|
||||
new(
|
||||
PlatformKind.Telegram,
|
||||
chatId.ToString(CultureInfo.InvariantCulture),
|
||||
threadId?.ToString(CultureInfo.InvariantCulture),
|
||||
messageId.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
using System.Globalization;
|
||||
using GmRelay.Shared.Platform;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using Telegram.Bot.Types.Enums;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
|
||||
namespace GmRelay.Bot.Infrastructure.Telegram;
|
||||
|
||||
public sealed class TelegramPlatformMessenger(
|
||||
ITelegramBotClient bot,
|
||||
ILogger<TelegramPlatformMessenger> logger) : IPlatformMessenger
|
||||
{
|
||||
public async Task<PlatformMessageRef> SendScheduleAsync(PlatformScheduleMessage message, CancellationToken ct)
|
||||
{
|
||||
EnsureTelegram(message.Group.Platform);
|
||||
|
||||
var chatId = ParseLong(message.Group.ExternalGroupId);
|
||||
var threadId = ParseNullableInt(message.Group.ExternalThreadId);
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(message.View);
|
||||
Message sentMessage;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(message.ImageReference) && renderResult.Text.Length <= 1024)
|
||||
{
|
||||
try
|
||||
{
|
||||
sentMessage = await bot.SendPhoto(
|
||||
chatId: chatId,
|
||||
messageThreadId: threadId,
|
||||
photo: InputFile.FromString(message.ImageReference),
|
||||
caption: renderResult.Text,
|
||||
parseMode: ParseMode.Html,
|
||||
replyMarkup: renderResult.Markup,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to send Telegram schedule image for group {ExternalGroupId}", message.Group.ExternalGroupId);
|
||||
sentMessage = await SendScheduleTextMessage(chatId, threadId, renderResult.Text, renderResult.Markup, ct);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(message.ImageReference))
|
||||
{
|
||||
await TrySendScheduleImageOnly(chatId, threadId, message.View.Title, message.ImageReference, ct);
|
||||
}
|
||||
|
||||
sentMessage = await SendScheduleTextMessage(chatId, threadId, renderResult.Text, renderResult.Markup, ct);
|
||||
}
|
||||
|
||||
return new PlatformMessageRef(
|
||||
PlatformKind.Telegram,
|
||||
message.Group.ExternalGroupId,
|
||||
message.Group.ExternalThreadId,
|
||||
sentMessage.MessageId.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
public async Task UpdateScheduleAsync(PlatformScheduleMessage message, CancellationToken ct)
|
||||
{
|
||||
EnsureTelegram(message.Group.Platform);
|
||||
var existingMessage = message.ExistingMessage;
|
||||
if (existingMessage is null)
|
||||
{
|
||||
throw new ArgumentException("Existing schedule message reference is required.", nameof(message));
|
||||
}
|
||||
|
||||
EnsureTelegram(existingMessage.Platform);
|
||||
if (!string.Equals(message.Group.ExternalGroupId, existingMessage.ExternalGroupId, StringComparison.Ordinal) ||
|
||||
!string.Equals(message.Group.ExternalThreadId, existingMessage.ExternalThreadId, StringComparison.Ordinal))
|
||||
{
|
||||
throw new ArgumentException("Existing schedule message reference must match the schedule group.", nameof(message));
|
||||
}
|
||||
|
||||
var renderResult = TelegramSessionBatchRenderer.Render(message.View);
|
||||
await BatchMessageEditor.EditBatchMessageAsync(
|
||||
bot,
|
||||
chatId: ParseLong(existingMessage.ExternalGroupId),
|
||||
messageId: ParseInt(existingMessage.ExternalMessageId),
|
||||
text: renderResult.Text,
|
||||
replyMarkup: renderResult.Markup,
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task SendGroupMessageAsync(PlatformGroup group, string htmlText, CancellationToken ct)
|
||||
{
|
||||
EnsureTelegram(group.Platform);
|
||||
return bot.SendMessage(
|
||||
chatId: ParseLong(group.ExternalGroupId),
|
||||
messageThreadId: ParseNullableInt(group.ExternalThreadId),
|
||||
text: htmlText,
|
||||
parseMode: ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
|
||||
public Task SendPrivateMessageAsync(PlatformPrivateMessage message, CancellationToken ct)
|
||||
{
|
||||
EnsureTelegram(message.Recipient.Platform);
|
||||
return bot.SendMessage(
|
||||
chatId: ParseLong(message.Recipient.ExternalUserId),
|
||||
text: message.HtmlText,
|
||||
parseMode: ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
|
||||
public Task AnswerInteractionAsync(PlatformInteractionReply reply, CancellationToken ct) =>
|
||||
bot.AnswerCallbackQuery(
|
||||
callbackQueryId: reply.InteractionId,
|
||||
text: reply.Text,
|
||||
showAlert: reply.ShowAlert,
|
||||
cancellationToken: ct);
|
||||
|
||||
public async Task SendCalendarFileAsync(PlatformCalendarFile file, CancellationToken ct)
|
||||
{
|
||||
EnsureTelegram(file.Group.Platform);
|
||||
|
||||
using var stream = new MemoryStream(file.Content);
|
||||
await bot.SendDocument(
|
||||
chatId: ParseLong(file.Group.ExternalGroupId),
|
||||
messageThreadId: ParseNullableInt(file.Group.ExternalThreadId),
|
||||
document: InputFile.FromStream(stream, file.FileName),
|
||||
caption: file.CaptionHtml,
|
||||
parseMode: ParseMode.Html,
|
||||
replyMarkup: BuildActionsMarkup(file.Actions),
|
||||
cancellationToken: ct);
|
||||
}
|
||||
|
||||
private async Task<Message> SendScheduleTextMessage(
|
||||
long chatId,
|
||||
int? threadId,
|
||||
string text,
|
||||
InlineKeyboardMarkup markup,
|
||||
CancellationToken ct) =>
|
||||
await bot.SendMessage(
|
||||
chatId: chatId,
|
||||
messageThreadId: threadId,
|
||||
text: text,
|
||||
parseMode: ParseMode.Html,
|
||||
replyMarkup: markup,
|
||||
cancellationToken: ct);
|
||||
|
||||
private async Task TrySendScheduleImageOnly(
|
||||
long chatId,
|
||||
int? threadId,
|
||||
string title,
|
||||
string imageReference,
|
||||
CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await bot.SendPhoto(
|
||||
chatId: chatId,
|
||||
messageThreadId: threadId,
|
||||
photo: InputFile.FromString(imageReference),
|
||||
caption: $"🎲 {System.Net.WebUtility.HtmlEncode(title)}",
|
||||
parseMode: ParseMode.Html,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to send Telegram schedule image for chat {ChatId}", chatId);
|
||||
}
|
||||
}
|
||||
|
||||
private static InlineKeyboardMarkup? BuildActionsMarkup(IReadOnlyList<PlatformMessageAction> actions)
|
||||
{
|
||||
if (actions.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new InlineKeyboardMarkup(
|
||||
actions.Select(action => new[]
|
||||
{
|
||||
Uri.TryCreate(action.Payload, UriKind.Absolute, out var uri) &&
|
||||
(uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)
|
||||
? InlineKeyboardButton.WithUrl(action.Label, action.Payload)
|
||||
: InlineKeyboardButton.WithCallbackData(action.Label, action.Payload)
|
||||
}));
|
||||
}
|
||||
|
||||
private static void EnsureTelegram(PlatformKind platform)
|
||||
{
|
||||
if (platform != PlatformKind.Telegram)
|
||||
{
|
||||
throw new NotSupportedException($"Telegram messenger cannot send messages for platform {platform}.");
|
||||
}
|
||||
}
|
||||
|
||||
private static long ParseLong(string value) => long.Parse(value, CultureInfo.InvariantCulture);
|
||||
|
||||
private static int ParseInt(string value) => int.Parse(value, CultureInfo.InvariantCulture);
|
||||
|
||||
private static int? ParseNullableInt(string? value) =>
|
||||
string.IsNullOrWhiteSpace(value) ? null : int.Parse(value, CultureInfo.InvariantCulture);
|
||||
}
|
||||
@@ -69,17 +69,21 @@ public sealed class UpdateRouter(
|
||||
|
||||
var parts = data.Split(':', 3);
|
||||
var action = parts[0];
|
||||
var user = TelegramPlatformIds.User(
|
||||
query.From.Id,
|
||||
query.From.FirstName + (string.IsNullOrEmpty(query.From.LastName) ? "" : $" {query.From.LastName}"),
|
||||
query.From.Username);
|
||||
var group = TelegramPlatformIds.Group(message.Chat.Id, message.MessageThreadId, message.Chat.Title);
|
||||
var scheduleMessage = TelegramPlatformIds.Message(message.Chat.Id, message.MessageThreadId, message.MessageId);
|
||||
|
||||
if (action == "join_session" && parts.Length >= 2 && Guid.TryParse(parts[1], out var joinSessionId))
|
||||
{
|
||||
var command = new JoinSessionCommand(
|
||||
SessionId: joinSessionId,
|
||||
TelegramUserId: query.From.Id,
|
||||
DisplayName: query.From.FirstName + (string.IsNullOrEmpty(query.From.LastName) ? "" : $" {query.From.LastName}"),
|
||||
TelegramUsername: query.From.Username,
|
||||
CallbackQueryId: query.Id,
|
||||
ChatId: message.Chat.Id,
|
||||
MessageId: message.MessageId);
|
||||
User: user,
|
||||
InteractionId: query.Id,
|
||||
Group: group,
|
||||
ScheduleMessage: scheduleMessage);
|
||||
|
||||
await joinSessionHandler.HandleAsync(command, ct);
|
||||
return;
|
||||
@@ -89,10 +93,10 @@ public sealed class UpdateRouter(
|
||||
{
|
||||
var command = new LeaveSessionCommand(
|
||||
SessionId: leaveSessionId,
|
||||
TelegramUserId: query.From.Id,
|
||||
CallbackQueryId: query.Id,
|
||||
ChatId: message.Chat.Id,
|
||||
MessageId: message.MessageId);
|
||||
User: user,
|
||||
InteractionId: query.Id,
|
||||
Group: group,
|
||||
ScheduleMessage: scheduleMessage);
|
||||
|
||||
await leaveSessionHandler.HandleAsync(command, ct);
|
||||
return;
|
||||
|
||||
@@ -47,7 +47,7 @@ BEGIN
|
||||
SELECT
|
||||
pt.player_id,
|
||||
p.display_name,
|
||||
p.telegram_username,
|
||||
COALESCE(p.external_username, p.telegram_username) AS telegram_username,
|
||||
pt.total_sessions,
|
||||
pt.confirmed_count,
|
||||
pt.declined_count,
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
-- =============================================================
|
||||
-- V016: Add platform identity columns and platform_messages table
|
||||
-- =============================================================
|
||||
-- Scope: Prepare schema for multi-platform support (Discord, etc).
|
||||
-- Legacy telegram_* columns are retained for backward compatibility.
|
||||
-- =============================================================
|
||||
|
||||
-- -- Players: platform-agnostic identity
|
||||
ALTER TABLE players
|
||||
ADD COLUMN platform VARCHAR(50),
|
||||
ADD COLUMN external_user_id VARCHAR(255),
|
||||
ADD COLUMN external_username VARCHAR(255);
|
||||
|
||||
CREATE UNIQUE INDEX ix_players_platform_external_user_id
|
||||
ON players (platform, external_user_id)
|
||||
WHERE platform IS NOT NULL AND external_user_id IS NOT NULL;
|
||||
|
||||
-- -- Game groups: platform-agnostic identity
|
||||
ALTER TABLE game_groups
|
||||
ADD COLUMN platform VARCHAR(50),
|
||||
ADD COLUMN external_group_id VARCHAR(255),
|
||||
ADD COLUMN external_channel_id VARCHAR(255);
|
||||
|
||||
CREATE UNIQUE INDEX ix_game_groups_platform_external_group_id
|
||||
ON game_groups (platform, external_group_id)
|
||||
WHERE platform IS NOT NULL AND external_group_id IS NOT NULL;
|
||||
|
||||
-- -- Backfill existing Telegram data
|
||||
UPDATE players
|
||||
SET platform = 'Telegram',
|
||||
external_user_id = telegram_id::TEXT,
|
||||
external_username = telegram_username
|
||||
WHERE platform IS NULL;
|
||||
|
||||
UPDATE game_groups
|
||||
SET platform = 'Telegram',
|
||||
external_group_id = telegram_chat_id::TEXT
|
||||
WHERE platform IS NULL;
|
||||
|
||||
-- -- Platform messages: store per-platform message references
|
||||
CREATE TABLE platform_messages (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
platform VARCHAR(50) NOT NULL,
|
||||
group_id UUID REFERENCES game_groups(id) ON DELETE CASCADE,
|
||||
batch_id UUID,
|
||||
session_id UUID REFERENCES sessions(id) ON DELETE CASCADE,
|
||||
external_channel_id VARCHAR(255),
|
||||
external_thread_id VARCHAR(255),
|
||||
external_message_id VARCHAR(255) NOT NULL,
|
||||
purpose VARCHAR(50) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX ix_platform_messages_group_id ON platform_messages(group_id);
|
||||
CREATE INDEX ix_platform_messages_batch_id ON platform_messages(batch_id);
|
||||
CREATE INDEX ix_platform_messages_session_id ON platform_messages(session_id);
|
||||
CREATE INDEX ix_platform_messages_platform_message
|
||||
ON platform_messages (platform, external_message_id);
|
||||
|
||||
-- -- Recreate attendance stats function for new columns (prod back-compat)
|
||||
CREATE OR REPLACE FUNCTION get_group_attendance_stats(p_group_id UUID)
|
||||
RETURNS TABLE (
|
||||
player_id UUID,
|
||||
display_name VARCHAR,
|
||||
telegram_username VARCHAR,
|
||||
total_sessions BIGINT,
|
||||
confirmed_count BIGINT,
|
||||
declined_count BIGINT,
|
||||
no_response_count BIGINT,
|
||||
waitlisted_count BIGINT,
|
||||
cancellation_affected_count BIGINT,
|
||||
attendance_rate NUMERIC
|
||||
) AS $$
|
||||
BEGIN
|
||||
RETURN QUERY
|
||||
WITH player_sessions AS (
|
||||
SELECT
|
||||
sp.player_id,
|
||||
s.id AS session_id,
|
||||
sp.rsvp_status,
|
||||
sp.registration_status,
|
||||
s.status AS session_status,
|
||||
s.scheduled_at
|
||||
FROM session_participants sp
|
||||
JOIN sessions s ON s.id = sp.session_id
|
||||
WHERE s.group_id = p_group_id
|
||||
),
|
||||
player_totals AS (
|
||||
SELECT
|
||||
ps.player_id,
|
||||
COUNT(*) FILTER (WHERE ps.session_status <> 'Cancelled') AS total_sessions,
|
||||
COUNT(*) FILTER (WHERE ps.rsvp_status = 'Confirmed' AND ps.session_status <> 'Cancelled') AS confirmed_count,
|
||||
COUNT(*) FILTER (WHERE ps.rsvp_status = 'Declined' AND ps.session_status <> 'Cancelled') AS declined_count,
|
||||
COUNT(*) FILTER (WHERE ps.rsvp_status = 'Pending' AND ps.scheduled_at < NOW() AND ps.session_status <> 'Cancelled') AS no_response_count,
|
||||
COUNT(*) FILTER (WHERE ps.registration_status = 'Waitlisted' AND ps.session_status <> 'Cancelled') AS waitlisted_count,
|
||||
COUNT(*) FILTER (WHERE ps.session_status = 'Cancelled') AS cancellation_affected_count
|
||||
FROM player_sessions ps
|
||||
GROUP BY ps.player_id
|
||||
)
|
||||
SELECT
|
||||
pt.player_id,
|
||||
p.display_name,
|
||||
COALESCE(p.external_username, p.telegram_username) AS telegram_username,
|
||||
pt.total_sessions,
|
||||
pt.confirmed_count,
|
||||
pt.declined_count,
|
||||
pt.no_response_count,
|
||||
pt.waitlisted_count,
|
||||
pt.cancellation_affected_count,
|
||||
ROUND(
|
||||
100.0 * pt.confirmed_count
|
||||
/ NULLIF(pt.total_sessions, 0),
|
||||
1
|
||||
) AS attendance_rate
|
||||
FROM player_totals pt
|
||||
JOIN players p ON p.id = pt.player_id
|
||||
ORDER BY pt.confirmed_count DESC, pt.total_sessions DESC;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql STABLE;
|
||||
@@ -0,0 +1,9 @@
|
||||
-- =============================================================
|
||||
-- V017: Allow platform-neutral players
|
||||
-- =============================================================
|
||||
-- Legacy Telegram identity columns remain for backward compatibility,
|
||||
-- but non-Telegram platform users do not have Telegram ids.
|
||||
-- =============================================================
|
||||
|
||||
ALTER TABLE players
|
||||
ALTER COLUMN telegram_id DROP NOT NULL;
|
||||
@@ -6,9 +6,11 @@ using GmRelay.Bot.Features.Reminders.SendOneHourReminder;
|
||||
using GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
using GmRelay.Bot.Features.Sessions.RescheduleSession;
|
||||
using GmRelay.Bot.Infrastructure.Database;
|
||||
using GmRelay.Bot.Infrastructure.Health;
|
||||
using GmRelay.Bot.Infrastructure.Logging;
|
||||
using GmRelay.Bot.Infrastructure.Scheduling;
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
using GmRelay.Shared.Platform;
|
||||
using Npgsql;
|
||||
using Telegram.Bot;
|
||||
|
||||
@@ -49,6 +51,7 @@ builder.Services.AddSingleton<ITelegramBotClient>(sp =>
|
||||
return new TelegramBotClient(token);
|
||||
});
|
||||
builder.Services.AddSingleton<ITelegramUpdateSource, TelegramUpdateSource>();
|
||||
builder.Services.AddSingleton<IPlatformMessenger, TelegramPlatformMessenger>();
|
||||
|
||||
// ── Feature handlers (explicit registration — AOT safe) ──────────────
|
||||
builder.Services.AddSingleton<SendConfirmationHandler>();
|
||||
@@ -85,6 +88,9 @@ builder.Services.AddSingleton<ISessionTriggerStore, DbSessionTriggerStore>();
|
||||
builder.Services.AddHostedService<SessionSchedulerService>();
|
||||
builder.Services.AddHostedService<RescheduleVotingDeadlineService>();
|
||||
|
||||
// ── Health check server ──────────────────────────────────────────────
|
||||
builder.Services.AddHostedService<BotHealthCheckHostedService>();
|
||||
|
||||
var host = builder.Build();
|
||||
|
||||
// ── Run database migrations on startup ───────────────────────────────
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace GmRelay.DiscordBot;
|
||||
|
||||
public sealed class DiscordOptions
|
||||
{
|
||||
public string? Token { get; init; }
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(Token))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Discord:Token is required. Set via environment variable Discord__Token or user secrets.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
# Stage 1: Build
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble AS build
|
||||
WORKDIR /src
|
||||
|
||||
COPY ["src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj", "src/GmRelay.DiscordBot/"]
|
||||
COPY ["src/GmRelay.ServiceDefaults/GmRelay.ServiceDefaults.csproj", "src/GmRelay.ServiceDefaults/"]
|
||||
COPY ["src/GmRelay.Shared/GmRelay.Shared.csproj", "src/GmRelay.Shared/"]
|
||||
|
||||
RUN dotnet restore "src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj"
|
||||
|
||||
COPY src/ src/
|
||||
WORKDIR /src/src/GmRelay.DiscordBot
|
||||
RUN dotnet publish "GmRelay.DiscordBot.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
||||
|
||||
# Stage 2: Runtime
|
||||
FROM mcr.microsoft.com/dotnet/runtime:10.0-noble AS final
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/publish .
|
||||
USER $APP_UID
|
||||
ENTRYPOINT ["dotnet", "GmRelay.DiscordBot.dll"]
|
||||
@@ -0,0 +1,38 @@
|
||||
using NetCord.Rest;
|
||||
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;
|
||||
|
||||
public DiscordListSessionsCommand(DiscordListSessionsHandler handler)
|
||||
{
|
||||
_handler = handler;
|
||||
}
|
||||
|
||||
public async Task ExecuteAsync()
|
||||
{
|
||||
var guildId = Context.Guild?.Id.ToString()
|
||||
?? throw new InvalidOperationException("This command can only be used in a guild.");
|
||||
var channelId = Context.Channel.Id.ToString();
|
||||
|
||||
var view = await _handler.BuildScheduleAsync(guildId, channelId, CancellationToken.None);
|
||||
|
||||
if (view is null)
|
||||
{
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message("📭 В этом сервере нет предстоящих игр."));
|
||||
return;
|
||||
}
|
||||
|
||||
var (embeds, actionRows) = Rendering.DiscordSessionBatchRenderer.Render(view);
|
||||
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message(new InteractionMessageProperties()
|
||||
.WithEmbeds(embeds)
|
||||
.WithComponents(actionRows)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using Dapper;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
|
||||
namespace GmRelay.DiscordBot.Features.Sessions;
|
||||
|
||||
internal sealed record DiscordSessionListItemDto(
|
||||
Guid Id, string Title, DateTime ScheduledAt, string Status, int? MaxPlayers,
|
||||
int PlayerCount, int WaitlistCount);
|
||||
|
||||
public sealed class DiscordListSessionsHandler(NpgsqlDataSource dataSource)
|
||||
{
|
||||
public async Task<SessionBatchViewModel?> BuildScheduleAsync(
|
||||
string guildId,
|
||||
string channelId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using var connection = await dataSource.OpenConnectionAsync(cancellationToken);
|
||||
|
||||
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
|
||||
FROM sessions s
|
||||
JOIN game_groups g ON s.group_id = g.id
|
||||
LEFT JOIN session_participants sp ON s.id = sp.session_id
|
||||
WHERE g.platform = 'Discord'
|
||||
AND g.external_group_id = @GuildId
|
||||
AND s.status != @Cancelled
|
||||
AND s.scheduled_at > NOW()
|
||||
GROUP BY s.id, s.title, s.scheduled_at, s.status, s.max_players
|
||||
ORDER BY s.scheduled_at ASC",
|
||||
new
|
||||
{
|
||||
GuildId = guildId,
|
||||
Cancelled = SessionStatus.Cancelled,
|
||||
Active = ParticipantRegistrationStatus.Active,
|
||||
Waitlisted = ParticipantRegistrationStatus.Waitlisted
|
||||
});
|
||||
|
||||
var sessionList = sessions.ToList();
|
||||
if (sessionList.Count == 0)
|
||||
return null;
|
||||
|
||||
var sessionIds = sessionList.Select(s => s.Id).ToList();
|
||||
var participants = await connection.QueryAsync<ParticipantBatchDto>(
|
||||
@"SELECT sp.session_id as SessionId,
|
||||
p.display_name as DisplayName,
|
||||
COALESCE(p.external_username, p.telegram_username) as TelegramUsername,
|
||||
sp.registration_status as RegistrationStatus
|
||||
FROM session_participants sp
|
||||
JOIN players p ON p.id = sp.player_id
|
||||
WHERE sp.session_id = ANY(@SessionIds) AND sp.is_gm = false
|
||||
ORDER BY sp.registration_status ASC, sp.created_at ASC",
|
||||
new { SessionIds = sessionIds });
|
||||
|
||||
var firstTitle = sessionList.First().Title;
|
||||
var batchDtos = sessionList.Select(s => new SessionBatchDto(
|
||||
s.Id, s.ScheduledAt, s.Status, s.MaxPlayers, "")).ToList();
|
||||
|
||||
return SessionBatchViewBuilder.Build(firstTitle, batchDtos, participants.ToList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using GmRelay.DiscordBot.Rendering;
|
||||
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;
|
||||
private readonly ILogger<DiscordNewSessionCommand> _logger;
|
||||
|
||||
public DiscordNewSessionCommand(DiscordNewSessionHandler handler, ILogger<DiscordNewSessionCommand> logger)
|
||||
{
|
||||
_handler = handler;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
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
|
||||
?? throw new InvalidOperationException("This command can only be used in a guild.");
|
||||
|
||||
var timeResult = DiscordNewSessionHandler.ParseTimeInput(time);
|
||||
if (!timeResult.IsSuccess)
|
||||
{
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message($"X {timeResult.Error}"));
|
||||
return;
|
||||
}
|
||||
|
||||
var resolvedPermissions = GetResolvedPermissions(guild, Context.User.Id);
|
||||
|
||||
try
|
||||
{
|
||||
var view = await _handler.HandleAsync(
|
||||
guildId: guild.Id.ToString(),
|
||||
channelId: Context.Channel.Id.ToString(),
|
||||
userId: Context.User.Id,
|
||||
userDisplayName: Context.User.GlobalName ?? Context.User.Username,
|
||||
resolvedPermissions: resolvedPermissions,
|
||||
guildOwnerId: guild.OwnerId,
|
||||
title: title,
|
||||
scheduledAt: timeResult.Value,
|
||||
maxPlayers: seats is null ? null : (int)seats.Value,
|
||||
joinLink: link,
|
||||
CancellationToken.None);
|
||||
|
||||
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)));
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
await Context.Interaction.SendResponseAsync(
|
||||
InteractionCallback.Message($":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."));
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
using Dapper;
|
||||
using GmRelay.DiscordBot.Infrastructure.Discord;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Npgsql;
|
||||
|
||||
namespace GmRelay.DiscordBot.Features.Sessions;
|
||||
|
||||
public sealed record TimeParseResult(bool IsSuccess, DateTimeOffset Value, string? Error);
|
||||
|
||||
public sealed class DiscordNewSessionHandler(
|
||||
NpgsqlDataSource dataSource,
|
||||
DiscordPermissionChecker permissionChecker,
|
||||
IPlatformMessenger messenger,
|
||||
ILogger<DiscordNewSessionHandler> logger)
|
||||
{
|
||||
public static TimeParseResult ParseTimeInput(string input)
|
||||
{
|
||||
if (DateTimeOffset.TryParseExact(
|
||||
input.Trim(),
|
||||
"yyyy-MM-dd HH:mm",
|
||||
System.Globalization.CultureInfo.InvariantCulture,
|
||||
System.Globalization.DateTimeStyles.AssumeUniversal,
|
||||
out var result))
|
||||
{
|
||||
if (result < DateTimeOffset.UtcNow)
|
||||
return new TimeParseResult(false, default, "Дата находится в прошлом.");
|
||||
|
||||
return new TimeParseResult(true, result.ToUniversalTime(), null);
|
||||
}
|
||||
|
||||
if (DateTimeOffset.TryParseExact(
|
||||
input.Trim(),
|
||||
"dd.MM.yyyy HH:mm",
|
||||
System.Globalization.CultureInfo.InvariantCulture,
|
||||
System.Globalization.DateTimeStyles.AssumeUniversal,
|
||||
out var altResult))
|
||||
{
|
||||
if (altResult < DateTimeOffset.UtcNow)
|
||||
return new TimeParseResult(false, default, "Дата находится в прошлом.");
|
||||
|
||||
return new TimeParseResult(true, altResult.ToUniversalTime(), null);
|
||||
}
|
||||
|
||||
return new TimeParseResult(false, default, "Некорректный формат даты. Используйте YYYY-MM-DD HH:mm или DD.MM.YYYY HH:mm");
|
||||
}
|
||||
|
||||
public async Task<SessionBatchViewModel> HandleAsync(
|
||||
string guildId,
|
||||
string channelId,
|
||||
ulong userId,
|
||||
string userDisplayName,
|
||||
ulong resolvedPermissions,
|
||||
ulong guildOwnerId,
|
||||
string title,
|
||||
DateTimeOffset scheduledAt,
|
||||
int? maxPlayers,
|
||||
string? joinLink,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await using var connection = await dataSource.OpenConnectionAsync(cancellationToken);
|
||||
|
||||
var dbManagerUserIds = await connection.QueryAsync<ulong>(
|
||||
@"SELECT CAST(p.external_user_id AS BIGINT)
|
||||
FROM group_managers gm
|
||||
JOIN players p ON p.id = gm.player_id
|
||||
JOIN game_groups g ON g.id = gm.group_id
|
||||
WHERE g.platform = 'Discord' AND g.external_group_id = @GuildId",
|
||||
new { GuildId = guildId });
|
||||
|
||||
if (!permissionChecker.CanManageSchedule(guildOwnerId, userId, dbManagerUserIds, resolvedPermissions))
|
||||
{
|
||||
throw new UnauthorizedAccessException("⛔ Только owner, администратор или manager могут создавать сессии.");
|
||||
}
|
||||
|
||||
await using var transaction = await connection.BeginTransactionAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
await connection.ExecuteAsync(
|
||||
@"INSERT INTO players (display_name, platform, external_user_id, external_username)
|
||||
VALUES (@Name, 'Discord', @UserId, @Name)
|
||||
ON CONFLICT (platform, external_user_id)
|
||||
WHERE platform IS NOT NULL AND external_user_id IS NOT NULL
|
||||
DO UPDATE SET display_name = EXCLUDED.display_name,
|
||||
external_username = EXCLUDED.external_username",
|
||||
new { Name = userDisplayName, UserId = userId.ToString() },
|
||||
transaction);
|
||||
|
||||
var groupId = await connection.ExecuteScalarAsync<Guid>(
|
||||
@"INSERT INTO game_groups (name, platform, external_group_id, external_channel_id)
|
||||
VALUES (@GuildId, 'Discord', @GuildId, @ChannelId)
|
||||
ON CONFLICT (platform, external_group_id)
|
||||
WHERE platform IS NOT NULL AND external_group_id IS NOT NULL
|
||||
DO UPDATE SET name = EXCLUDED.name,
|
||||
external_channel_id = COALESCE(EXCLUDED.external_channel_id, game_groups.external_channel_id)
|
||||
RETURNING id",
|
||||
new { GuildId = guildId, ChannelId = channelId },
|
||||
transaction);
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
@"INSERT INTO group_managers (group_id, player_id, role)
|
||||
SELECT @GroupId, p.id, @OwnerRole
|
||||
FROM players p
|
||||
WHERE p.platform = 'Discord' AND p.external_user_id = @UserId
|
||||
ON CONFLICT (group_id, player_id) DO NOTHING",
|
||||
new { GroupId = groupId, UserId = userId.ToString(), OwnerRole = GroupManagerRoleExtensions.OwnerValue },
|
||||
transaction);
|
||||
|
||||
var batchId = Guid.NewGuid();
|
||||
var sessionId = await connection.ExecuteScalarAsync<Guid>(
|
||||
@"INSERT INTO sessions (batch_id, group_id, title, join_link, scheduled_at, status, max_players)
|
||||
VALUES (@BatchId, @GroupId, @Title, @Link, @ScheduledAt, @Status, @MaxPlayers)
|
||||
RETURNING id",
|
||||
new
|
||||
{
|
||||
BatchId = batchId,
|
||||
GroupId = groupId,
|
||||
Title = title,
|
||||
Link = joinLink ?? string.Empty,
|
||||
ScheduledAt = scheduledAt.UtcDateTime,
|
||||
Status = SessionStatus.Planned,
|
||||
MaxPlayers = maxPlayers
|
||||
},
|
||||
transaction);
|
||||
|
||||
await transaction.CommitAsync(cancellationToken);
|
||||
logger.LogInformation("Created session {SessionId} in guild {GuildId}", sessionId, guildId);
|
||||
|
||||
var sessions = new[] { new SessionBatchDto(sessionId, scheduledAt.UtcDateTime, SessionStatus.Planned, maxPlayers, joinLink ?? string.Empty) };
|
||||
var view = SessionBatchViewBuilder.Build(title, sessions, Array.Empty<ParticipantBatchDto>());
|
||||
|
||||
await messenger.SendScheduleAsync(
|
||||
new PlatformScheduleMessage(
|
||||
new PlatformGroup(PlatformKind.Discord, guildId, guildId, channelId),
|
||||
view,
|
||||
null),
|
||||
cancellationToken);
|
||||
|
||||
return view;
|
||||
}
|
||||
catch
|
||||
{
|
||||
await transaction.RollbackAsync(cancellationToken);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Worker">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>preview</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>dotnet-GmRelay.DiscordBot-issue-26</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Aspire.Npgsql" Version="13.2.2" />
|
||||
<PackageReference Include="Dapper" Version="2.1.72" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
|
||||
<PackageReference Include="NetCord.Hosting" Version="1.0.0-alpha.489" />
|
||||
<PackageReference Include="NetCord.Hosting.Services" Version="1.0.0-alpha.489" />
|
||||
<PackageReference Include="NetCord.Services" Version="1.0.0-alpha.489" />
|
||||
<PackageReference Include="Npgsql" Version="10.0.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\GmRelay.ServiceDefaults\GmRelay.ServiceDefaults.csproj" />
|
||||
<ProjectReference Include="..\GmRelay.Shared\GmRelay.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace GmRelay.DiscordBot.Infrastructure.Discord;
|
||||
|
||||
public sealed class DiscordPermissionChecker
|
||||
{
|
||||
private const ulong AdministratorPermission = 0x8;
|
||||
|
||||
public bool CanManageSchedule(
|
||||
ulong guildOwnerId,
|
||||
ulong userId,
|
||||
IEnumerable<ulong> dbManagerUserIds,
|
||||
ulong resolvedPermissions)
|
||||
{
|
||||
if (userId == guildOwnerId)
|
||||
return true;
|
||||
|
||||
if (dbManagerUserIds.Contains(userId))
|
||||
return true;
|
||||
|
||||
return (resolvedPermissions & AdministratorPermission) == AdministratorPermission;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
using GmRelay.DiscordBot.Rendering;
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using NetCord;
|
||||
using NetCord.Rest;
|
||||
|
||||
namespace GmRelay.DiscordBot.Infrastructure.Discord;
|
||||
|
||||
public sealed class DiscordPlatformMessenger(RestClient restClient) : IPlatformMessenger
|
||||
{
|
||||
public async Task<PlatformMessageRef> SendScheduleAsync(PlatformScheduleMessage message, CancellationToken ct)
|
||||
{
|
||||
var (embeds, actionRows) = DiscordSessionBatchRenderer.Render(message.View);
|
||||
|
||||
var channelId = ulong.Parse(message.Group.ExternalChannelId
|
||||
?? message.Group.ExternalGroupId);
|
||||
|
||||
var msg = await restClient.SendMessageAsync(
|
||||
channelId,
|
||||
new MessageProperties()
|
||||
.WithEmbeds(embeds)
|
||||
.WithComponents(actionRows));
|
||||
|
||||
return new PlatformMessageRef(
|
||||
PlatformKind.Discord,
|
||||
message.Group.ExternalGroupId,
|
||||
null,
|
||||
msg.Id.ToString());
|
||||
}
|
||||
|
||||
public async Task UpdateScheduleAsync(PlatformScheduleMessage message, CancellationToken ct)
|
||||
{
|
||||
if (message.ExistingMessage is null)
|
||||
return;
|
||||
|
||||
var (embeds, actionRows) = DiscordSessionBatchRenderer.Render(message.View);
|
||||
|
||||
var channelId = ulong.Parse(message.Group.ExternalChannelId
|
||||
?? message.Group.ExternalGroupId);
|
||||
var messageId = ulong.Parse(message.ExistingMessage.ExternalMessageId);
|
||||
|
||||
await restClient.ModifyMessageAsync(
|
||||
channelId,
|
||||
messageId,
|
||||
options =>
|
||||
{
|
||||
options.Embeds = embeds;
|
||||
options.Components = actionRows;
|
||||
});
|
||||
}
|
||||
|
||||
public Task SendGroupMessageAsync(PlatformGroup group, string htmlText, CancellationToken ct)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task SendPrivateMessageAsync(PlatformPrivateMessage message, CancellationToken ct)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task AnswerInteractionAsync(PlatformInteractionReply reply, CancellationToken ct)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task SendCalendarFileAsync(PlatformCalendarFile file, CancellationToken ct)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using NetCord.Gateway;
|
||||
using NetCord.Hosting.Gateway;
|
||||
|
||||
namespace GmRelay.DiscordBot.Infrastructure.Logging;
|
||||
|
||||
public sealed class DiscordGatewayLifecycleLogger(
|
||||
ILogger<DiscordGatewayLifecycleLogger> logger)
|
||||
: IConnectGatewayHandler,
|
||||
IReadyGatewayHandler,
|
||||
IDisconnectGatewayHandler,
|
||||
IResumeGatewayHandler
|
||||
{
|
||||
public ValueTask HandleAsync()
|
||||
{
|
||||
logger.LogInformation("Discord gateway connected");
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
public ValueTask HandleAsync(ReadyEventArgs arg)
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Discord gateway ready for application {ApplicationId} in {GuildCount} guilds",
|
||||
arg.ApplicationId,
|
||||
arg.GuildIds.Count);
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
public ValueTask HandleAsync(DisconnectEventArgs arg)
|
||||
{
|
||||
logger.LogWarning(
|
||||
"Discord gateway disconnected; reconnect scheduled: {Reconnect}",
|
||||
arg.Reconnect);
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
ValueTask IResumeGatewayHandler.HandleAsync()
|
||||
{
|
||||
logger.LogInformation("Discord gateway session resumed");
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace GmRelay.DiscordBot.Infrastructure.Logging;
|
||||
|
||||
internal static partial class SecretRedactor
|
||||
{
|
||||
public static string RedactConnectionString(string connectionString)
|
||||
{
|
||||
return PasswordPattern().Replace(connectionString, "$1***");
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"(?i)(Password\s*=\s*)[^;]+")]
|
||||
private static partial Regex PasswordPattern();
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using GmRelay.DiscordBot;
|
||||
using GmRelay.DiscordBot.Features.Sessions;
|
||||
using GmRelay.DiscordBot.Infrastructure.Discord;
|
||||
using GmRelay.DiscordBot.Infrastructure.Logging;
|
||||
using GmRelay.Shared.Platform;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NetCord;
|
||||
using NetCord.Gateway;
|
||||
using NetCord.Hosting.Gateway;
|
||||
using NetCord.Hosting.Services.ApplicationCommands;
|
||||
using NetCord.Hosting.Services.ComponentInteractions;
|
||||
using NetCord.Services.ComponentInteractions;
|
||||
using Npgsql;
|
||||
|
||||
var builder = Host.CreateApplicationBuilder(args);
|
||||
|
||||
builder.AddServiceDefaults();
|
||||
|
||||
var discordOptions = builder.Configuration
|
||||
.GetRequiredSection("Discord")
|
||||
.Get<DiscordOptions>() ?? new DiscordOptions();
|
||||
discordOptions.Validate();
|
||||
|
||||
builder.Services.AddSingleton(discordOptions);
|
||||
|
||||
builder.Services.AddSingleton<NpgsqlDataSource>(sp =>
|
||||
{
|
||||
var config = sp.GetRequiredService<IConfiguration>();
|
||||
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
|
||||
var connectionString = config.GetConnectionString("gmrelaydb")
|
||||
?? throw new InvalidOperationException(
|
||||
"ConnectionStrings:gmrelaydb is required. Set via environment variable ConnectionStrings__gmrelaydb.");
|
||||
|
||||
var logger = loggerFactory.CreateLogger("GmRelay.DiscordBot.Startup");
|
||||
logger.LogInformation(
|
||||
"Configured PostgreSQL data source with connection string {ConnectionString}",
|
||||
SecretRedactor.RedactConnectionString(connectionString));
|
||||
|
||||
return NpgsqlDataSource.Create(connectionString);
|
||||
});
|
||||
|
||||
builder.Services.AddSingleton<DiscordPermissionChecker>();
|
||||
builder.Services.AddSingleton<DiscordListSessionsHandler>();
|
||||
builder.Services.AddSingleton<DiscordNewSessionHandler>();
|
||||
builder.Services.AddSingleton<IPlatformMessenger, DiscordPlatformMessenger>();
|
||||
|
||||
builder.Services
|
||||
.AddDiscordGateway(options =>
|
||||
{
|
||||
options.Token = discordOptions.Token;
|
||||
options.Intents = GatewayIntents.Guilds;
|
||||
})
|
||||
.AddApplicationCommands()
|
||||
.AddComponentInteractions<ButtonInteraction, ButtonInteractionContext>()
|
||||
.AddGatewayHandlers(typeof(Program).Assembly);
|
||||
|
||||
var host = builder.Build();
|
||||
|
||||
host.AddSlashCommand("ping", "Checks whether GM-Relay Discord is online.", () => "Pong!");
|
||||
|
||||
await host.RunAsync();
|
||||
@@ -0,0 +1,125 @@
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using NetCord;
|
||||
using NetCord.Rest;
|
||||
|
||||
namespace GmRelay.DiscordBot.Rendering;
|
||||
|
||||
public static class DiscordSessionBatchRenderer
|
||||
{
|
||||
public static (IReadOnlyList<EmbedProperties> Embeds, IReadOnlyList<ActionRowProperties> ActionRows) Render(SessionBatchViewModel view)
|
||||
{
|
||||
var embeds = new List<EmbedProperties>();
|
||||
var actionRows = new List<ActionRowProperties>();
|
||||
|
||||
foreach (var session in view.Sessions)
|
||||
{
|
||||
var embed = BuildEmbed(view.Title, session);
|
||||
embeds.Add(embed);
|
||||
|
||||
if (session.AvailableActions.Count > 0)
|
||||
{
|
||||
var actionRow = new ActionRowProperties();
|
||||
foreach (var action in session.AvailableActions)
|
||||
{
|
||||
actionRow.Add(new ButtonProperties(
|
||||
$"{action.ActionKey}:{action.SessionId}",
|
||||
action.Label,
|
||||
ButtonStyle.Primary));
|
||||
}
|
||||
actionRows.Add(actionRow);
|
||||
}
|
||||
}
|
||||
|
||||
return (embeds, actionRows);
|
||||
}
|
||||
|
||||
private static EmbedProperties BuildEmbed(string title, SessionViewItem session)
|
||||
{
|
||||
var embed = new EmbedProperties()
|
||||
.WithTitle($"{title} — {session.ScheduledAt.FormatMoscow()}");
|
||||
|
||||
if (SessionStatus.IsCancelled(session.Status))
|
||||
{
|
||||
embed = embed.WithDescription("❌ Сессия отменена");
|
||||
}
|
||||
else
|
||||
{
|
||||
embed = embed.WithDescription(BuildPlayerDescription(session));
|
||||
}
|
||||
|
||||
var fields = new List<EmbedFieldProperties>
|
||||
{
|
||||
new EmbedFieldProperties()
|
||||
.WithName("👥 Заполненность")
|
||||
.WithValue(session.MaxPlayers.HasValue
|
||||
? $"{session.ActivePlayerCount}/{session.MaxPlayers.Value}"
|
||||
: $"{session.ActivePlayerCount}")
|
||||
.WithInline(),
|
||||
|
||||
new EmbedFieldProperties()
|
||||
.WithName("⏳ Лист ожидания")
|
||||
.WithValue(session.WaitlistedPlayers.Count > 0
|
||||
? session.WaitlistedPlayers.Count.ToString()
|
||||
: "—")
|
||||
.WithInline(),
|
||||
|
||||
new EmbedFieldProperties()
|
||||
.WithName("📊 Статус")
|
||||
.WithValue(FormatStatus(session.Status))
|
||||
.WithInline()
|
||||
};
|
||||
|
||||
if (!string.IsNullOrEmpty(session.JoinLink))
|
||||
{
|
||||
embed = embed.WithUrl(session.JoinLink);
|
||||
}
|
||||
|
||||
embed = embed.WithColor(GetColor(session));
|
||||
embed = embed.AddFields(fields);
|
||||
|
||||
return embed;
|
||||
}
|
||||
|
||||
private static string BuildPlayerDescription(SessionViewItem session)
|
||||
{
|
||||
if (session.ActivePlayers.Count == 0)
|
||||
return "👥 Пока никто не записался";
|
||||
|
||||
var lines = session.ActivePlayers
|
||||
.Select(p => $"• {p.DisplayName}")
|
||||
.ToList();
|
||||
|
||||
if (session.WaitlistedPlayers.Count > 0)
|
||||
{
|
||||
lines.Add("");
|
||||
lines.Add($"⏳ Лист ожидания ({session.WaitlistedPlayers.Count}):");
|
||||
lines.AddRange(session.WaitlistedPlayers.Select(p => $"• {p.DisplayName}"));
|
||||
}
|
||||
|
||||
return string.Join('\n', lines);
|
||||
}
|
||||
|
||||
private static string FormatStatus(string status) => status switch
|
||||
{
|
||||
SessionStatus.Planned => "Запланирована",
|
||||
SessionStatus.ConfirmationSent => "Ожидает подтверждения",
|
||||
SessionStatus.Confirmed => "Подтверждена",
|
||||
SessionStatus.Cancelled => "Отменена",
|
||||
_ => status
|
||||
};
|
||||
|
||||
private static Color GetColor(SessionViewItem session)
|
||||
{
|
||||
if (SessionStatus.IsCancelled(session.Status))
|
||||
return new Color(0xED4245);
|
||||
|
||||
if (session.Status == SessionStatus.Confirmed)
|
||||
return new Color(0x5865F2);
|
||||
|
||||
if (session.MaxPlayers.HasValue && session.ActivePlayerCount >= session.MaxPlayers.Value)
|
||||
return new Color(0xFEE75C);
|
||||
|
||||
return new Color(0x57F287);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,673 @@
|
||||
{
|
||||
"version": 1,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"Aspire.Npgsql": {
|
||||
"type": "Direct",
|
||||
"requested": "[13.2.2, )",
|
||||
"resolved": "13.2.2",
|
||||
"contentHash": "nEYgziWN7hksgEQEWy24JypcMCU8gKYcIIyPL05JfdXxUWuPRLotH/KOeuHevAjSEOYkL3dtGakBkJAuPobGmA==",
|
||||
"dependencies": {
|
||||
"AspNetCore.HealthChecks.NpgSql": "9.0.0",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Binder": "10.0.5",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Diagnostics.HealthChecks": "10.0.5",
|
||||
"Microsoft.Extensions.Hosting.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5",
|
||||
"Microsoft.Extensions.Primitives": "10.0.5",
|
||||
"Npgsql.DependencyInjection": "10.0.1",
|
||||
"Npgsql.OpenTelemetry": "10.0.1",
|
||||
"OpenTelemetry.Extensions.Hosting": "1.15.0"
|
||||
}
|
||||
},
|
||||
"Dapper": {
|
||||
"type": "Direct",
|
||||
"requested": "[2.1.72, )",
|
||||
"resolved": "2.1.72",
|
||||
"contentHash": "ns4mGqQd9a/MhP8m6w556vVlZIa0/MfUu03zrxjZC/jlr1uVCsUac8bkdB+Fs98Llbd56rRSo1eZH5VVmeGZyw=="
|
||||
},
|
||||
"Microsoft.Extensions.Hosting": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.5, )",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "8i7e5IBdiKLNqt/+ciWrS8U95Rv5DClaaj7ulkZbimnCi4uREWd+lXzkp3joofFuIPOlAzV4AckxLTIELv2jdg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Binder": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.CommandLine": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.EnvironmentVariables": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.FileExtensions": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Json": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.UserSecrets": "10.0.5",
|
||||
"Microsoft.Extensions.DependencyInjection": "10.0.5",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Diagnostics": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Physical": "10.0.5",
|
||||
"Microsoft.Extensions.Hosting.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Console": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Debug": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.EventLog": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.EventSource": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5"
|
||||
}
|
||||
},
|
||||
"NetCord.Hosting": {
|
||||
"type": "Direct",
|
||||
"requested": "[1.0.0-alpha.489, )",
|
||||
"resolved": "1.0.0-alpha.489",
|
||||
"contentHash": "yQcvgY3uu98ndoLXpiFhJ5kungoWVLd7xnO18GmukRPVsRzyOKgxe/Ycp8DLYTtiQG9Wyg1pV4Iv6rvo+zck4w==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Binder": "10.0.8",
|
||||
"Microsoft.Extensions.Hosting.Abstractions": "10.0.8",
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.8",
|
||||
"Microsoft.Extensions.Options.DataAnnotations": "10.0.8",
|
||||
"NetCord": "1.0.0-alpha.489"
|
||||
}
|
||||
},
|
||||
"NetCord.Hosting.Services": {
|
||||
"type": "Direct",
|
||||
"requested": "[1.0.0-alpha.489, )",
|
||||
"resolved": "1.0.0-alpha.489",
|
||||
"contentHash": "Md46+zLB9UWYLM7PVlATytkjAC9602wBNKO7m5eaBiDdEvZOPsUrR6NJJr2YtJoKjttbvhte5ayDXj8WGGsevQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Binder": "10.0.8",
|
||||
"Microsoft.Extensions.Hosting.Abstractions": "10.0.8",
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.8",
|
||||
"Microsoft.Extensions.Options.DataAnnotations": "10.0.8",
|
||||
"NetCord.Hosting": "1.0.0-alpha.489",
|
||||
"NetCord.Services": "1.0.0-alpha.489"
|
||||
}
|
||||
},
|
||||
"NetCord.Services": {
|
||||
"type": "Direct",
|
||||
"requested": "[1.0.0-alpha.489, )",
|
||||
"resolved": "1.0.0-alpha.489",
|
||||
"contentHash": "SwG/7Khba1uRENDvG22RV/POByIwh/ZrenMrSzwoEcEYPMI5TabmEEB3ySH15XGdLcFZJEj106AlriN0kZhfFg==",
|
||||
"dependencies": {
|
||||
"NetCord": "1.0.0-alpha.489"
|
||||
}
|
||||
},
|
||||
"Npgsql": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.2, )",
|
||||
"resolved": "10.0.2",
|
||||
"contentHash": "q5RfBI+wywJSFUNDE1L4ZbHEHCFTblo8Uf6A6oe4feOUFYiUQXyAf9GBh5qEZpvJaHiEbpBPkQumjEhXCJxdrg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"SecurityCodeScan.VS2019": {
|
||||
"type": "Direct",
|
||||
"requested": "[5.6.7, )",
|
||||
"resolved": "5.6.7",
|
||||
"contentHash": "WIE9RJswdSc2j+rLz2gW6U+gMUjMHzY2j7C/CL8/R2olXNM/+twarfMnWqm+rZodDBvaYDApJyxM8mVYf9FGrQ=="
|
||||
},
|
||||
"AspNetCore.HealthChecks.NpgSql": {
|
||||
"type": "Transitive",
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "npc58/AD5zuVxERdhCl2Kb7WnL37mwX42SJcXIwvmEig0/dugOLg3SIwtfvvh3TnvTwR/sk5LYNkkPaBdks61A==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Diagnostics.HealthChecks": "8.0.11",
|
||||
"Npgsql": "8.0.3"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.AmbientMetadata.Application": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "CNrEjaOCZ8d1HtB0mvpiX4EWxLkee2xy+CsYXxmsEYJSFgw3OmF9pIhP/tCTeYBHhpsKJj5wM63G8IBFGxAcsw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.2",
|
||||
"Microsoft.Extensions.Hosting.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Compliance.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "1a4xDAT6fRyP8t419q3WvWMmMslDTvI7OAZLWBhn5rysFG0bl5xFenTswd1xAbT/3u3mx4Xyb5bPx+V+18tJeQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.ObjectPool": "10.0.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.8",
|
||||
"contentHash": "ehZcoPbjzWzS4XFvuz7R3V55SmpdkyMqFURLH3yXaN9NtXd9tR6CGB7pd49HYtCkenl+G7ctXSFLhNI08xLfRg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.8",
|
||||
"Microsoft.Extensions.Primitives": "10.0.8"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.8",
|
||||
"contentHash": "I63esIFbL3h5pSt7gXpXOlmcwDmYBUoYNEglKfDPFUqtYvSV84f2l28hO2lfVXsV0wdlplgAM7IVz16matapSg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Primitives": "10.0.8"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.Binder": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.8",
|
||||
"contentHash": "R3NN1X+kVu14uoxLEW6sBSQyhogDSbaOQzILnCtuXxBN4hx22AgjWPwZX6v/suERFkEDgU1lk12AglHTrUxhlw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.8",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.8"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.CommandLine": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "or9fOLopMUTJOQVJ3bou4aD6PwvsiKf4kZC4EE5sRRKSkmh+wfk/LekJXRjAX88X+1JA9zHjDo+5fiQ7z3MY/A==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.EnvironmentVariables": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "tchMGQ+zVTO40np/Zzg2Li/TIR8bksQgg4UVXZa0OzeFCKWnIYtxE2FVs+eSmjPGCjMS2voZbwN/mUcYfpSTuA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.FileExtensions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "OhTr0O79dP49734lLTqVveivVX9sDXxbI/8vjELAZTHXqoN90mdpgTAgwicJED42iaHMCcZcK6Bj+8wNyBikaw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Physical": "10.0.5",
|
||||
"Microsoft.Extensions.Primitives": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.Json": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "brBM/WP0YAUYh2+QqSYVdK8eQHYQTtTEUJXJ+84Zkdo2buGLja9VSrMIhgoeBUU7JBmcskAib8Lb/N83bvxgYQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.FileExtensions": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.UserSecrets": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "fhdG6UV9lIp70QhNkVyaHciUVq25IPFkczheVJL9bIFvmnJ+Zghaie6dWkDbbVmxZlHl9gj3zTDxMxJs5zNhIA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Json": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Physical": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "v1SVsowG6YE1YnHVGmLWz57YTRCQRx9pH5ebIESXfm5isI9gA3QaMyg/oMTzPpXYZwSAVDzYItGJKfmV+pqXkQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.8",
|
||||
"contentHash": "21nbDV60SRPWGIivsyl6lqBeEJNG1sginhhfWgRrr3Ais7aQ12To25OAHQxgoiJkjqy1aQ6RxpZBGYuTi7Ge6A=="
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection.AutoActivation": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "Z/OI261l7LnxyODKPx0trQyIHFyicCR/akfn64lGOjPcf4FpAZ7ePAGl2HPvQBUBSNfPTF0gWeCfuFmyftMgYA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Hosting.Abstractions": "10.0.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "vAJHd4yOpmKoK+jBuYV7a3y+Ab9U4ARCc29b6qvMy276RgJFw9LFs0DdsPqOL3ahwzyrX7tM+i4cCxU/RX0qAg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.8",
|
||||
"contentHash": "+f4C5g78QCGNyxzUfrTYsB7qYx06Zca0e88s3qFlea9/lQhgPImYdNprlgzl1uHhRU3fVHLfmbijayU2sJEZ6w==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.8",
|
||||
"Microsoft.Extensions.Options": "10.0.8"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics.ExceptionSummarization": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "3qMK1D40D10kb5TdBtFJpzz6/WH0NinWs68ZZS8jCFgHMXDiOjGiPOneMmIocCP/wnUUW4Hzf8lMsIE1xIGxDA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics.HealthChecks": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "REdt95QXHscGdtw/UUgyCW2lF9DJcAOJxmebKW2IkgUjuCAdMODIi2HNOWg5utW98nm8ekgV0Gjqs/sljwwqMw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Hosting.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "NrIMTy7dpqxAvA6kHAYH8cXID/YgeNOy0OqFKpLtkPu5X4WS/basX91UszANzVrMNRAICJ2GOnGiRxJtsRyEQw=="
|
||||
},
|
||||
"Microsoft.Extensions.Features": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.2",
|
||||
"contentHash": "X7tm2aV2w3lN9roSSGhl19lz4w76HvdiuKNhIv2XOiorYII9XCm66o/z9IJ0+QwkgvEv5gMZDM6rV6uwABHEQQ=="
|
||||
},
|
||||
"Microsoft.Extensions.FileProviders.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.8",
|
||||
"contentHash": "U+oquaPxFdY8lYeEIWO/AD7jDIl9sPW6aVWMQRHU/pZ/SWpLcOrAj2fcLe1HwXl4sYw1ONI56K/eELT3xr4RRQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Primitives": "10.0.8"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.FileProviders.Physical": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "dMu5kUPSfol1Rqhmr6nWPSmbFjDe9w6bkoKithG17bWTZA0UyKirTatM5mqYUN3mGpNA0MorlusIoVTh6J7o5g==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.FileSystemGlobbing": "10.0.5",
|
||||
"Microsoft.Extensions.Primitives": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.FileSystemGlobbing": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "mOE3ARusNQR0a5x8YOcnUbfyyXGqoAWQtEc7qFOfNJgruDWQLo39Re+3/Lzj5pLPFuFYj8hN4dgKzaSQDKiOCw=="
|
||||
},
|
||||
"Microsoft.Extensions.Hosting.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.8",
|
||||
"contentHash": "MoOWFPT88/pDfmWpbU9PydKRX/rJFQkliowE/L9wbQcl94IicUphb5BFgepkWiDkYYxPnuEqjN4buzOGW4vJpQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.8",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.8",
|
||||
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.8",
|
||||
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.8",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.8"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Http": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.2",
|
||||
"contentHash": "egUPC0xydb1ugCMcRyJ6zaOGOzx7N4coOVlGeLcIsXhUf1xHHwZeX+ob7JuG0dXExFduHYE/t+4/4y8BLlBKmw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.Diagnostics": "10.0.2",
|
||||
"Microsoft.Extensions.Logging": "10.0.2",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.Options": "10.0.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Http.Diagnostics": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "I0FBgF6yZRwYH9E3KQ2vHm80YZ7YBj+52GDsmOWXPBv/p15b/wUoNupV9kw3LnSNVsWMqlGbiuZgBnHpMwPh+Q==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Http": "10.0.2",
|
||||
"Microsoft.Extensions.Telemetry": "10.2.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Http.Resilience": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "Lg+OjBW+ODDbM4Ax4LoERvQ1dqSZ8I2gQc2+B0/WOWl2+PunLJ3xb3x8MtHGfcb/Mp98RoMpwRKm6Aj9mzXwrA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Http.Diagnostics": "10.2.0",
|
||||
"Microsoft.Extensions.ObjectPool": "10.0.2",
|
||||
"Microsoft.Extensions.Resilience": "10.2.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "+XTMKQyDWg4ODoNHU/BN3BaI1jhGO7VCS+BnzT/4IauiG6y2iPAte7MyD7rHKS+hNP0TkFkjrae8DFjDUxtcxg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.8",
|
||||
"contentHash": "fdVadZmsC8jRP0KvKy8mO8f6GV/HyBvElfcSxEhd+5FM5boAw/01iSaCto5G3G37ApJira4A3pNaVvBv8cUiLQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.8"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Configuration": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "cSgxsDgfP0+gmVRPVoNHI/KIDavIZxh+CxE6tSLPlYTogqccDnjBFI9CgEsiNuMP6+fiuXUwhhlTz36uUEpwbQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Binder": "10.0.5",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5",
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Console": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "PMs2gha2v24hvH5o5KQem5aNK4mN0BhhCWlMqsg9tzifWKzjeQi2tyPOP/RaWMVvalOhVLcrmoMYPqbnia/epg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Debug": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "/VacEkBQ02A8PBXSa6YpbIXCuisYy6JJr62/+ANJDZE+RMBfZMcXJXLfr/LpyLE6pgdp17Wxlt7e7R9zvkwZ3Q==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging.EventLog": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "0ezhWYJS4/6KrqQel9JL+Tr4n+4EX2TF5EYiaysBWNNEM2c3Gtj1moD39esfgk8OHblSX+UFjtZ3z0c4i9tRvw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5",
|
||||
"System.Diagnostics.EventLog": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging.EventSource": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "vN+aq1hBFXyYvY5Ow9WyeR66drKQxRZmas4lAjh6QWfryPkjTn1uLtX5AFIxyDaZj78v5TG2sELUyvrXpAPQQw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5",
|
||||
"Microsoft.Extensions.Primitives": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.ObjectPool": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.2",
|
||||
"contentHash": "kpCp4m7nwJVBcRKWXYHdVK/W0dkKyyFOjCmKVdO+zKThWvUxP1V+jVEP9FGpqRu4GPl9041SEXu2f+U/l825nQ=="
|
||||
},
|
||||
"Microsoft.Extensions.Options": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.8",
|
||||
"contentHash": "VBD+131DpTNCNDfA4kIyKTiCySvJGNhwibdWBSdFRu7GMfXLXcXODkgA+KStKbbhzraLglZWUN4nXyHgW4JIRA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.8",
|
||||
"Microsoft.Extensions.Primitives": "10.0.8"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.8",
|
||||
"contentHash": "VOapXeO3lhBH0zYoyAH7tjapuo4V5pTHlevPpiSHueEquAajqd5nF0mttm+h/uE/exwAEuM5s26SzOJtletE3w==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.8",
|
||||
"Microsoft.Extensions.Configuration.Binder": "10.0.8",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.8",
|
||||
"Microsoft.Extensions.Options": "10.0.8",
|
||||
"Microsoft.Extensions.Primitives": "10.0.8"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Options.DataAnnotations": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.8",
|
||||
"contentHash": "HhxwIGECGGJ8ox2kvm6/hkN/w1ZyKrO5uu/rLAL51V0ypPdahoNf+dHS6Er/DJs2aeUmH38ZTTzACfLy1O6w3Q==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.8",
|
||||
"Microsoft.Extensions.Options": "10.0.8"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Primitives": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.8",
|
||||
"contentHash": "OBPo4nYhMyIbtueoC10CBm6AGAbo/A9IV8QQ/6ryZS7VvmqpGT7hunazeHLxFawRzn3oLOq4jhqhpBX4tfswWQ=="
|
||||
},
|
||||
"Microsoft.Extensions.Resilience": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "v4WOdAOFxB3AcsUkZWNcHL3mYzs4KAPtHO8rkoQlFKOBoD3KyjjAL+h3tRwSK5i4UpF/yhxsQRY0JxKj4osxxw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Diagnostics": "10.0.2",
|
||||
"Microsoft.Extensions.Diagnostics.ExceptionSummarization": "10.2.0",
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.2",
|
||||
"Microsoft.Extensions.Telemetry.Abstractions": "10.2.0",
|
||||
"Polly.Extensions": "8.4.2",
|
||||
"Polly.RateLimiting": "8.4.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.ServiceDiscovery": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "AHTPfiKodj66xA8RwRkFD4q11V2AvzcuDsujv6ViPkOPtvBEYcPVplHakK56pPzWlX08MDS+TAQXfFXAeP7J5w==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Http": "10.0.2",
|
||||
"Microsoft.Extensions.ServiceDiscovery.Abstractions": "10.2.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.ServiceDiscovery.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "sANlOvfqfw/yfych4CLlHSKSWzIie6mQG7w83gVur1foNOafyHxcgpoQMvBf+KiB4Tpls6P1/Z77IIQSK8hxFg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.Configuration.Binder": "10.0.2",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.Features": "10.0.2",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.Options": "10.0.2",
|
||||
"Microsoft.Extensions.Primitives": "10.0.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Telemetry": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "ssW5gosYlewNH/ISTyaLD/XfJT4GSjwShOUKv61fpXrqVmHkhuIA/5bBAGStM1XbzJjt9IG2vzfdHTu4zlX9Ew==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.AmbientMetadata.Application": "10.2.0",
|
||||
"Microsoft.Extensions.DependencyInjection.AutoActivation": "10.2.0",
|
||||
"Microsoft.Extensions.Logging.Configuration": "10.0.2",
|
||||
"Microsoft.Extensions.ObjectPool": "10.0.2",
|
||||
"Microsoft.Extensions.Telemetry.Abstractions": "10.2.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Telemetry.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "6V4V6NX6RLUYWwV89DeW/4zK5xOycYHWhsfMXSpKVGgMHfXcczmbk6hBeqTnRPzhpATYcOWlmA6hk1jgdxUugA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Compliance.Abstractions": "10.2.0",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.ObjectPool": "10.0.2",
|
||||
"Microsoft.Extensions.Options": "10.0.2"
|
||||
}
|
||||
},
|
||||
"NetCord": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.0.0-alpha.489",
|
||||
"contentHash": "/rM73l1pwwJCWHi7YrIiSVc+GVL0lV+k+amqNJUMINjLO+c5bKWj9PoNNoMhiPZoaORO4k6Uxp8EQfoQj3AYtA=="
|
||||
},
|
||||
"Npgsql.DependencyInjection": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.1",
|
||||
"contentHash": "YHFa4vD27sNIfv6s5q8Zi1fLvKfmK1xcpMv0PUvXOxDFbRmuMRSHwpZTbPvsAlj97q1/o7DfyynLqfqrCm1VnA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.0",
|
||||
"Npgsql": "10.0.1"
|
||||
}
|
||||
},
|
||||
"Npgsql.OpenTelemetry": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.1",
|
||||
"contentHash": "G9fEIBaHggZXWfDSDnKLc0XwKcbuU6i2eXp7zDqpgYxbhCmIN9fRgaSOGyyMNHSo/yY1IB4G4CjW5VO/SKRR0g==",
|
||||
"dependencies": {
|
||||
"Npgsql": "10.0.1",
|
||||
"OpenTelemetry.API": "1.14.0"
|
||||
}
|
||||
},
|
||||
"OpenTelemetry": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.15.3",
|
||||
"contentHash": "N0i6WjPoHPbZyms1ugbDIFAJFuGlpeExJMU/+XSL0lQRUkg/D0utFkDoLXf8Z1km5B+xVZ2GyMXXiX8qdeNmPg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.0",
|
||||
"Microsoft.Extensions.Logging.Configuration": "10.0.0",
|
||||
"OpenTelemetry.Api.ProviderBuilderExtensions": "1.15.3"
|
||||
}
|
||||
},
|
||||
"OpenTelemetry.Api": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.15.3",
|
||||
"contentHash": "fX+fkCysfPut+qCcT3bKqyX4QN9Saf4CgX8HLOHywEVD+Xr7sULtfuypITpoDysjx8R59dn/3mWhgimMH8cm/g=="
|
||||
},
|
||||
"OpenTelemetry.Api.ProviderBuilderExtensions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.15.3",
|
||||
"contentHash": "SYn0lqYDwLMWhv/zlNGsQcl2yX++yTumanX46bmOZE/ZDOd1WjPBO2kZaZgKLEZTZk48pavIFGJ6vOvxXgWVFQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0",
|
||||
"OpenTelemetry.Api": "1.15.3"
|
||||
}
|
||||
},
|
||||
"OpenTelemetry.Exporter.OpenTelemetryProtocol": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.15.3",
|
||||
"contentHash": "FEXJepcseTGbATiCkUfP7ipoFEYYfl/0UmmUwi0KxCPg9PaUA8ab2P1LGopK+/HExasJ1ZutFhZrN6WvUIR23g==",
|
||||
"dependencies": {
|
||||
"OpenTelemetry": "1.15.3"
|
||||
}
|
||||
},
|
||||
"OpenTelemetry.Extensions.Hosting": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.15.3",
|
||||
"contentHash": "u8n/W8yIlqv0BXZmvId1iVaeWXG42tGKdTkuLYg5g57Y/r9CeUNzqtrSHNdG5IoO8iPX79w3v+WsbAHgUQbfeg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Hosting.Abstractions": "10.0.0",
|
||||
"OpenTelemetry": "1.15.3"
|
||||
}
|
||||
},
|
||||
"OpenTelemetry.Instrumentation.AspNetCore": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.15.2",
|
||||
"contentHash": "2nPd7r0ug/gd6/CNFL6Rlu+RSQ9WYGSGHAYQ1ssbSqyzKJpqTunfx2I/1O0WB5k+L0cyXbG4XVZpoSoUc3M7wg==",
|
||||
"dependencies": {
|
||||
"OpenTelemetry.Api.ProviderBuilderExtensions": "[1.15.3, 2.0.0)"
|
||||
}
|
||||
},
|
||||
"OpenTelemetry.Instrumentation.Http": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.15.1",
|
||||
"contentHash": "vFO4Fj/dXkoVNGo/nhoGpO2zYQmZwr4jTID7oRGo+XlQ8LqksyZjUXQ4p39RfUvTID7IzzL8Qe71tW7CcAFymA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.0",
|
||||
"Microsoft.Extensions.Options": "10.0.0",
|
||||
"OpenTelemetry.Api.ProviderBuilderExtensions": "[1.15.3, 2.0.0)"
|
||||
}
|
||||
},
|
||||
"OpenTelemetry.Instrumentation.Runtime": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.15.1",
|
||||
"contentHash": "cpPwlUT5HXcLGPaIgsbSy0W9eFYAPGVbTP1p8/uyQ4Osvf5BJuPpEXE7crL09SmEd44r0DGNKDtsqxaAz0HxQw==",
|
||||
"dependencies": {
|
||||
"OpenTelemetry.Api": "[1.15.3, 2.0.0)"
|
||||
}
|
||||
},
|
||||
"Polly.Core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.4.2",
|
||||
"contentHash": "BpE2I6HBYYA5tF0Vn4eoQOGYTYIK1BlF5EXVgkWGn3mqUUjbXAr13J6fZVbp7Q3epRR8yshacBMlsHMhpOiV3g=="
|
||||
},
|
||||
"Polly.Extensions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.4.2",
|
||||
"contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Logging.Abstractions": "8.0.0",
|
||||
"Microsoft.Extensions.Options": "8.0.0",
|
||||
"Polly.Core": "8.4.2"
|
||||
}
|
||||
},
|
||||
"Polly.RateLimiting": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.4.2",
|
||||
"contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==",
|
||||
"dependencies": {
|
||||
"Polly.Core": "8.4.2",
|
||||
"System.Threading.RateLimiting": "8.0.0"
|
||||
}
|
||||
},
|
||||
"System.Diagnostics.EventLog": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "wugvy+pBVzjQEnRs9wMTWwoaeNFX3hsaHeVHFDIvJSWXp7wfmNWu3mxAwBIE6pyW+g6+rHa1Of5fTzb0QVqUTA=="
|
||||
},
|
||||
"System.Threading.RateLimiting": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.0.0",
|
||||
"contentHash": "7mu9v0QDv66ar3DpGSZHg9NuNcxDaaAcnMULuZlaTpP9+hwXhrxNGsF5GmLkSHxFdb5bBc1TzeujsRgTrPWi+Q=="
|
||||
},
|
||||
"gmrelay.servicedefaults": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Http.Resilience": "[10.2.0, )",
|
||||
"Microsoft.Extensions.ServiceDiscovery": "[10.2.0, )",
|
||||
"OpenTelemetry.Exporter.OpenTelemetryProtocol": "[1.15.3, )",
|
||||
"OpenTelemetry.Extensions.Hosting": "[1.15.3, )",
|
||||
"OpenTelemetry.Instrumentation.AspNetCore": "[1.15.2, )",
|
||||
"OpenTelemetry.Instrumentation.Http": "[1.15.1, )",
|
||||
"OpenTelemetry.Instrumentation.Runtime": "[1.15.1, )"
|
||||
}
|
||||
},
|
||||
"gmrelay.shared": {
|
||||
"type": "Project"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace GmRelay.Shared.Platform;
|
||||
|
||||
public interface IPlatformMessenger
|
||||
{
|
||||
Task<PlatformMessageRef> SendScheduleAsync(PlatformScheduleMessage message, CancellationToken ct);
|
||||
|
||||
Task UpdateScheduleAsync(PlatformScheduleMessage message, CancellationToken ct);
|
||||
|
||||
Task SendGroupMessageAsync(PlatformGroup group, string htmlText, CancellationToken ct);
|
||||
|
||||
Task SendPrivateMessageAsync(PlatformPrivateMessage message, CancellationToken ct);
|
||||
|
||||
Task AnswerInteractionAsync(PlatformInteractionReply reply, CancellationToken ct);
|
||||
|
||||
Task SendCalendarFileAsync(PlatformCalendarFile file, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace GmRelay.Shared.Platform;
|
||||
|
||||
public sealed record PlatformGroup(
|
||||
PlatformKind Platform,
|
||||
string ExternalGroupId,
|
||||
string DisplayName,
|
||||
string? ExternalChannelId = null,
|
||||
string? ExternalThreadId = null);
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace GmRelay.Shared.Platform;
|
||||
|
||||
public enum PlatformKind
|
||||
{
|
||||
Telegram = 0,
|
||||
Discord = 1,
|
||||
Max = 2
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using GmRelay.Shared.Rendering;
|
||||
|
||||
namespace GmRelay.Shared.Platform;
|
||||
|
||||
public sealed record PlatformMessageRef(
|
||||
PlatformKind Platform,
|
||||
string ExternalGroupId,
|
||||
string? ExternalThreadId,
|
||||
string ExternalMessageId);
|
||||
|
||||
public sealed record PlatformMessageAction(
|
||||
string Key,
|
||||
string Label,
|
||||
string Payload);
|
||||
|
||||
public sealed record PlatformScheduleMessage(
|
||||
PlatformGroup Group,
|
||||
SessionBatchViewModel View,
|
||||
PlatformMessageRef? ExistingMessage,
|
||||
string? ImageReference = null);
|
||||
|
||||
public sealed record PlatformPrivateMessage(
|
||||
PlatformUser Recipient,
|
||||
string HtmlText);
|
||||
|
||||
public sealed record PlatformInteractionReply(
|
||||
string InteractionId,
|
||||
string Text,
|
||||
bool ShowAlert = false);
|
||||
|
||||
public sealed record PlatformCalendarFile(
|
||||
PlatformGroup Group,
|
||||
string FileName,
|
||||
byte[] Content,
|
||||
string CaptionHtml,
|
||||
IReadOnlyList<PlatformMessageAction> Actions);
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace GmRelay.Shared.Platform;
|
||||
|
||||
public sealed record PlatformUser(
|
||||
PlatformKind Platform,
|
||||
string ExternalUserId,
|
||||
string DisplayName,
|
||||
string? ExternalUsername);
|
||||
@@ -1,13 +0,0 @@
|
||||
namespace GmRelay.Shared.Rendering;
|
||||
|
||||
/// <summary>
|
||||
/// Заглушка для Discord-рендерера.
|
||||
/// Реальная реализация будет добавлена в проект GmRelay.DiscordBot (issue #26).
|
||||
/// </summary>
|
||||
public static class DiscordSessionBatchRenderer
|
||||
{
|
||||
public static object Render(SessionBatchViewModel view)
|
||||
{
|
||||
throw new NotImplementedException("Discord renderer will be implemented in issue #26.");
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
<ResourcePreloader />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Cinzel+Decorative:wght@400;700&family=Cinzel:wght@400;600;700&family=Jura:wght@400;500;600;700&display=swap" rel="stylesheet" />
|
||||
<link rel="stylesheet" href="@Assets["app.css"]" />
|
||||
<link rel="stylesheet" href="@Assets["GmRelay.Web.styles.css"]" />
|
||||
<script src="https://telegram.org/js/telegram-web-app.js"></script>
|
||||
|
||||
@@ -30,8 +30,9 @@
|
||||
|
||||
/* === Error UI === */
|
||||
#blazor-error-ui {
|
||||
background: var(--bg-secondary);
|
||||
border-top: 1px solid var(--border-color);
|
||||
background: var(--status-danger-bg);
|
||||
color: var(--status-danger);
|
||||
border-top: 1px solid rgba(239, 68, 68, 0.15);
|
||||
bottom: 0;
|
||||
box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.3);
|
||||
box-sizing: border-box;
|
||||
@@ -41,8 +42,9 @@
|
||||
position: fixed;
|
||||
width: 100%;
|
||||
z-index: 1000;
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.875rem;
|
||||
font-family: 'Jura', sans-serif;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
#blazor-error-ui .reload {
|
||||
|
||||
@@ -56,7 +56,7 @@
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="nav-version">v1.15.0</div>
|
||||
<div class="nav-version">v2.4.0</div>
|
||||
</div>
|
||||
</Authorized>
|
||||
<NotAuthorized>
|
||||
|
||||
@@ -23,12 +23,11 @@
|
||||
}
|
||||
|
||||
.nav-brand-text {
|
||||
font-family: 'Cinzel Decorative', 'Cinzel', serif;
|
||||
font-size: 1.125rem;
|
||||
font-weight: 700;
|
||||
background: var(--accent-gradient);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.nav-toggle {
|
||||
@@ -87,9 +86,10 @@
|
||||
}
|
||||
|
||||
.nav-section ::deep .nav-item.active {
|
||||
background: rgba(124, 58, 237, 0.15);
|
||||
color: var(--accent-primary);
|
||||
border: 1px solid rgba(124, 58, 237, 0.2);
|
||||
background: linear-gradient(135deg, rgba(139, 92, 246, 0.15) 0%, rgba(34, 211, 238, 0.08) 100%);
|
||||
color: var(--text-accent);
|
||||
border: 1px solid rgba(139, 92, 246, 0.25);
|
||||
box-shadow: 0 0 12px rgba(139, 92, 246, 0.1);
|
||||
}
|
||||
|
||||
.nav-icon {
|
||||
@@ -145,7 +145,7 @@
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--text-muted);
|
||||
font-family: 'Inter', sans-serif;
|
||||
font-family: 'Jura', sans-serif;
|
||||
font-size: 0.8125rem;
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-normal);
|
||||
|
||||
@@ -18,8 +18,9 @@ RUN dotnet publish "GmRelay.Web.csproj" -c Release -o /app/publish /p:UseAppHost
|
||||
# Stage 2: Runtime
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble AS final
|
||||
WORKDIR /app
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends libgssapi-krb5-2 && rm -rf /var/lib/apt/lists/*
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends libgssapi-krb5-2 wget && rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=build /app/publish .
|
||||
RUN mkdir -p /app/dataprotection-keys && chown -R $APP_UID:$APP_UID /app/dataprotection-keys
|
||||
ENV ASPNETCORE_URLS=http://+:8080
|
||||
EXPOSE 8080
|
||||
USER $APP_UID
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Npgsql;
|
||||
|
||||
namespace GmRelay.Web.Health;
|
||||
|
||||
public sealed class NpgsqlHealthCheck(NpgsqlDataSource dataSource) : IHealthCheck
|
||||
{
|
||||
public async Task<HealthCheckResult> CheckHealthAsync(
|
||||
HealthCheckContext context,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var connection = await dataSource.OpenConnectionAsync(cancellationToken);
|
||||
await using var command = connection.CreateCommand();
|
||||
command.CommandText = "SELECT 1";
|
||||
await command.ExecuteScalarAsync(cancellationToken);
|
||||
return HealthCheckResult.Healthy();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return HealthCheckResult.Unhealthy("PostgreSQL is unavailable", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
using GmRelay.Web.Components;
|
||||
using GmRelay.Web.Health;
|
||||
using GmRelay.Web.Services;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
using Telegram.Bot;
|
||||
using Npgsql;
|
||||
|
||||
@@ -12,6 +16,10 @@ var builder = WebApplication.CreateBuilder(args);
|
||||
// Add Aspire service defaults
|
||||
builder.AddServiceDefaults();
|
||||
|
||||
// Add health checks
|
||||
builder.Services.AddHealthChecks()
|
||||
.AddCheck<NpgsqlHealthCheck>("npgsql");
|
||||
|
||||
// Add Data Protection
|
||||
builder.Services.AddDataProtection()
|
||||
.PersistKeysToFileSystem(new DirectoryInfo("/app/dataprotection-keys"));
|
||||
@@ -83,6 +91,26 @@ app.MapStaticAssets();
|
||||
app.MapRazorComponents<App>()
|
||||
.AddInteractiveServerRenderMode();
|
||||
|
||||
// Health check endpoints
|
||||
app.MapHealthChecks("/health", new HealthCheckOptions
|
||||
{
|
||||
ResponseWriter = async (context, report) =>
|
||||
{
|
||||
context.Response.ContentType = "application/json";
|
||||
var response = new
|
||||
{
|
||||
status = report.Status == HealthStatus.Healthy ? "healthy" : "unhealthy",
|
||||
timestamp = DateTimeOffset.UtcNow.ToString("O")
|
||||
};
|
||||
await context.Response.WriteAsJsonAsync(response);
|
||||
}
|
||||
});
|
||||
|
||||
app.MapHealthChecks("/alive", new HealthCheckOptions
|
||||
{
|
||||
Predicate = r => r.Tags.Contains("live")
|
||||
});
|
||||
|
||||
// Endpoint to handle Telegram Login callback
|
||||
app.MapGet("/auth/telegram", async (HttpContext context, TelegramAuthService authService) =>
|
||||
{
|
||||
|
||||
@@ -242,11 +242,14 @@ public sealed class SessionService(
|
||||
|
||||
await conn.ExecuteAsync(
|
||||
"""
|
||||
INSERT INTO players (telegram_id, display_name, telegram_username)
|
||||
VALUES (@TelegramId, @DisplayName, @TelegramUsername)
|
||||
INSERT INTO players (telegram_id, display_name, telegram_username, platform, external_user_id, external_username)
|
||||
VALUES (@TelegramId, @DisplayName, @TelegramUsername, 'Telegram', @TelegramId::TEXT, @TelegramUsername)
|
||||
ON CONFLICT (telegram_id) DO UPDATE
|
||||
SET display_name = EXCLUDED.display_name,
|
||||
telegram_username = EXCLUDED.telegram_username
|
||||
telegram_username = EXCLUDED.telegram_username,
|
||||
platform = COALESCE(players.platform, 'Telegram'),
|
||||
external_user_id = COALESCE(players.external_user_id, EXCLUDED.telegram_id::TEXT),
|
||||
external_username = COALESCE(players.external_username, EXCLUDED.telegram_username)
|
||||
""",
|
||||
new
|
||||
{
|
||||
|
||||
+551
-110
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,69 @@
|
||||
using System.IO;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
public sealed class DiscordListSessionsHandlerTests
|
||||
{
|
||||
private static string GetRepoRoot()
|
||||
{
|
||||
var dir = AppContext.BaseDirectory;
|
||||
while (!string.IsNullOrEmpty(dir) && !File.Exists(Path.Combine(dir, "Directory.Build.props")))
|
||||
{
|
||||
dir = Directory.GetParent(dir)?.FullName;
|
||||
}
|
||||
|
||||
return dir ?? throw new InvalidOperationException("Could not find repo root");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handler_ShouldExist()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var handlerPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Features", "Sessions", "DiscordListSessionsHandler.cs");
|
||||
|
||||
Assert.True(File.Exists(handlerPath), "DiscordListSessionsHandler should exist.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handler_ShouldQueryByPlatformAndExternalGroupId()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var handlerPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Features", "Sessions", "DiscordListSessionsHandler.cs");
|
||||
var handler = File.ReadAllText(handlerPath);
|
||||
|
||||
Assert.Contains("platform = 'Discord'", handler, StringComparison.Ordinal);
|
||||
Assert.Contains("external_group_id = @GuildId", handler, StringComparison.Ordinal);
|
||||
Assert.Contains("scheduled_at > NOW()", handler, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handler_ShouldNotContainTelegramSpecificColumns()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var handlerPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Features", "Sessions", "DiscordListSessionsHandler.cs");
|
||||
var handler = File.ReadAllText(handlerPath);
|
||||
|
||||
Assert.DoesNotContain("telegram_chat_id", handler, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("telegram_id", handler, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Command_ShouldExist()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var commandPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Features", "Sessions", "DiscordListSessionsCommand.cs");
|
||||
|
||||
Assert.True(File.Exists(commandPath), "DiscordListSessionsCommand should exist.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Command_ShouldBeSlashCommandModule()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var commandPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Features", "Sessions", "DiscordListSessionsCommand.cs");
|
||||
var command = File.ReadAllText(commandPath);
|
||||
|
||||
Assert.Contains("SlashCommand", command, StringComparison.Ordinal);
|
||||
Assert.Contains("listsessions", command, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using GmRelay.DiscordBot.Features.Sessions;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
public sealed class DiscordNewSessionHandlerTests
|
||||
{
|
||||
private static string GetRepoRoot()
|
||||
{
|
||||
var dir = AppContext.BaseDirectory;
|
||||
while (!string.IsNullOrEmpty(dir) && !File.Exists(Path.Combine(dir, "Directory.Build.props")))
|
||||
{
|
||||
dir = Directory.GetParent(dir)?.FullName;
|
||||
}
|
||||
|
||||
return dir ?? throw new InvalidOperationException("Could not find repo root");
|
||||
}
|
||||
|
||||
// --- Runtime tests for ParseTimeInput (static, no DB) ---
|
||||
|
||||
[Fact]
|
||||
public void ParseTimeInput_ShouldParseDiscordDateFormat()
|
||||
{
|
||||
var result = DiscordNewSessionHandler.ParseTimeInput("2026-05-20 19:30");
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(2026, result.Value.Year);
|
||||
Assert.Equal(5, result.Value.Month);
|
||||
Assert.Equal(20, result.Value.Day);
|
||||
Assert.Equal(19, result.Value.Hour);
|
||||
Assert.Equal(30, result.Value.Minute);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseTimeInput_ShouldRejectPastDate()
|
||||
{
|
||||
var result = DiscordNewSessionHandler.ParseTimeInput("2020-01-01 00:00");
|
||||
Assert.False(result.IsSuccess);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseTimeInput_ShouldParseRussianDateFormat()
|
||||
{
|
||||
var result = DiscordNewSessionHandler.ParseTimeInput("20.05.2026 19:30");
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(2026, result.Value.Year);
|
||||
Assert.Equal(5, result.Value.Month);
|
||||
Assert.Equal(20, result.Value.Day);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseTimeInput_ShouldRejectInvalidFormat()
|
||||
{
|
||||
var result = DiscordNewSessionHandler.ParseTimeInput("not-a-date");
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.NotNull(result.Error);
|
||||
}
|
||||
|
||||
// --- Source-level structural tests ---
|
||||
|
||||
[Fact]
|
||||
public void Handler_ShouldExist()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var handlerPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Features", "Sessions", "DiscordNewSessionHandler.cs");
|
||||
Assert.True(File.Exists(handlerPath), "DiscordNewSessionHandler should exist.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handler_ShouldUseDapperForDatabaseAccess()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var handlerPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Features", "Sessions", "DiscordNewSessionHandler.cs");
|
||||
var source = File.ReadAllText(handlerPath);
|
||||
|
||||
Assert.Contains("QueryAsync", source, StringComparison.Ordinal);
|
||||
Assert.Contains("ExecuteAsync", source, StringComparison.Ordinal);
|
||||
Assert.Contains("ExecuteScalarAsync", source, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handler_ShouldUseNpgsqlDataSource()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var handlerPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Features", "Sessions", "DiscordNewSessionHandler.cs");
|
||||
var source = File.ReadAllText(handlerPath);
|
||||
|
||||
Assert.Contains("NpgsqlDataSource", source, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handler_ShouldCheckPermissionsViaPermissionChecker()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var handlerPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Features", "Sessions", "DiscordNewSessionHandler.cs");
|
||||
var source = File.ReadAllText(handlerPath);
|
||||
|
||||
Assert.Contains("CanManageSchedule", source, StringComparison.Ordinal);
|
||||
Assert.Contains("UnauthorizedAccessException", source, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handler_ShouldBePlatformNeutral()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var handlerPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Features", "Sessions", "DiscordNewSessionHandler.cs");
|
||||
var source = File.ReadAllText(handlerPath);
|
||||
|
||||
Assert.DoesNotContain("telegram_chat_id", source, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("telegram_id", source, StringComparison.Ordinal);
|
||||
Assert.Contains("platform = 'Discord'", source, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handler_ShouldUseTransactions()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var handlerPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Features", "Sessions", "DiscordNewSessionHandler.cs");
|
||||
var source = File.ReadAllText(handlerPath);
|
||||
|
||||
Assert.Contains("BeginTransactionAsync", source, StringComparison.Ordinal);
|
||||
Assert.Contains("CommitAsync", source, StringComparison.Ordinal);
|
||||
Assert.Contains("RollbackAsync", source, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handler_ShouldRespectCancellationToken()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var handlerPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Features", "Sessions", "DiscordNewSessionHandler.cs");
|
||||
var source = File.ReadAllText(handlerPath);
|
||||
|
||||
Assert.Contains("CancellationToken", source, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Command_ShouldRenderEmbedOnSuccess()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var commandPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Features", "Sessions", "DiscordNewSessionCommand.cs");
|
||||
var source = File.ReadAllText(commandPath);
|
||||
|
||||
Assert.Contains("DiscordSessionBatchRenderer.Render", source, StringComparison.Ordinal);
|
||||
Assert.Contains("WithEmbeds", source, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using GmRelay.DiscordBot;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
public sealed class DiscordOptionsTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void Validate_ShouldRejectMissingToken(string? token)
|
||||
{
|
||||
var options = new DiscordOptions { Token = token };
|
||||
|
||||
var exception = Assert.Throws<InvalidOperationException>(options.Validate);
|
||||
|
||||
Assert.Contains("Discord:Token is required", exception.Message);
|
||||
Assert.Contains("Discord__Token", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_ShouldAcceptConfiguredToken()
|
||||
{
|
||||
var options = new DiscordOptions { Token = "configured-token" };
|
||||
|
||||
options.Validate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using GmRelay.DiscordBot.Infrastructure.Discord;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
public sealed class DiscordPermissionCheckerTests
|
||||
{
|
||||
[Fact]
|
||||
public void CanManageSchedule_WhenUserIsGuildOwner_ReturnsTrue()
|
||||
{
|
||||
var checker = new DiscordPermissionChecker();
|
||||
var result = checker.CanManageSchedule(
|
||||
guildOwnerId: 123456789ul,
|
||||
userId: 123456789ul,
|
||||
dbManagerUserIds: Array.Empty<ulong>(),
|
||||
resolvedPermissions: 0);
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CanManageSchedule_WhenUserHasAdministratorPermission_ReturnsTrue()
|
||||
{
|
||||
var checker = new DiscordPermissionChecker();
|
||||
var result = checker.CanManageSchedule(
|
||||
guildOwnerId: 123456789ul,
|
||||
userId: 987654321ul,
|
||||
dbManagerUserIds: Array.Empty<ulong>(),
|
||||
resolvedPermissions: 0x8); // Administrator
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CanManageSchedule_WhenUserIsDbManager_ReturnsTrue()
|
||||
{
|
||||
var checker = new DiscordPermissionChecker();
|
||||
var managerId = 555ul;
|
||||
var result = checker.CanManageSchedule(
|
||||
guildOwnerId: 123456789ul,
|
||||
userId: managerId,
|
||||
dbManagerUserIds: new[] { managerId },
|
||||
resolvedPermissions: 0);
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CanManageSchedule_WhenRegularUser_ReturnsFalse()
|
||||
{
|
||||
var checker = new DiscordPermissionChecker();
|
||||
var result = checker.CanManageSchedule(
|
||||
guildOwnerId: 123456789ul,
|
||||
userId: 111ul,
|
||||
dbManagerUserIds: new[] { 222ul },
|
||||
resolvedPermissions: 0);
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CanManageSchedule_WhenUserHasOtherPermissionButNotAdmin_ReturnsFalse()
|
||||
{
|
||||
var checker = new DiscordPermissionChecker();
|
||||
var result = checker.CanManageSchedule(
|
||||
guildOwnerId: 123456789ul,
|
||||
userId: 111ul,
|
||||
dbManagerUserIds: Array.Empty<ulong>(),
|
||||
resolvedPermissions: 0x4); // ManageServer, not Administrator
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using GmRelay.DiscordBot.Infrastructure.Discord;
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
public sealed class DiscordPlatformMessengerTests
|
||||
{
|
||||
[Fact]
|
||||
public void Constructor_ShouldAcceptRestClient()
|
||||
{
|
||||
var constructor = typeof(DiscordPlatformMessenger).GetConstructor(new[] { typeof(NetCord.Rest.RestClient) });
|
||||
Assert.NotNull(constructor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscordPlatformMessenger_ShouldImplementIPlatformMessenger()
|
||||
{
|
||||
Assert.True(typeof(IPlatformMessenger).IsAssignableFrom(typeof(DiscordPlatformMessenger)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
public sealed class DiscordProjectStructureTests
|
||||
{
|
||||
private static string GetRepoRoot()
|
||||
{
|
||||
var dir = AppContext.BaseDirectory;
|
||||
while (!string.IsNullOrEmpty(dir) && !File.Exists(Path.Combine(dir, "Directory.Build.props")))
|
||||
{
|
||||
dir = Directory.GetParent(dir)?.FullName;
|
||||
}
|
||||
|
||||
return dir ?? throw new InvalidOperationException("Could not find repo root");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Solution_ShouldIncludeDiscordWorkerProject()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var solution = File.ReadAllText(Path.Combine(repoRoot, "GM-Relay.slnx"));
|
||||
|
||||
Assert.Contains("src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj", solution);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DiscordWorkerProject_ShouldExistWithoutTelegramDependency()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var projectPath = Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "GmRelay.DiscordBot.csproj");
|
||||
|
||||
Assert.True(File.Exists(projectPath), "Discord worker project should exist.");
|
||||
|
||||
var project = File.ReadAllText(projectPath);
|
||||
Assert.Contains("Microsoft.NET.Sdk.Worker", project);
|
||||
Assert.Contains("NetCord.Hosting", project);
|
||||
Assert.Contains("GmRelay.ServiceDefaults.csproj", project);
|
||||
Assert.Contains("GmRelay.Shared.csproj", project);
|
||||
Assert.DoesNotContain("Telegram.Bot", project);
|
||||
Assert.DoesNotContain("GmRelay.Bot.csproj", project);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TelegramWorkerProject_ShouldNotReferenceNetCord()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var project = File.ReadAllText(Path.Combine(repoRoot, "src", "GmRelay.Bot", "GmRelay.Bot.csproj"));
|
||||
|
||||
Assert.DoesNotContain("NetCord", project, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RuntimeWiring_ShouldIncludeDiscordServiceWithoutCouplingTelegram()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var compose = File.ReadAllText(Path.Combine(repoRoot, "compose.yaml"));
|
||||
var appHostProject = File.ReadAllText(Path.Combine(repoRoot, "src", "GmRelay.AppHost", "GmRelay.AppHost.csproj"));
|
||||
var appHostProgram = File.ReadAllText(Path.Combine(repoRoot, "src", "GmRelay.AppHost", "Program.cs"));
|
||||
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:2.4.0", 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);
|
||||
Assert.Contains("dotnet build src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj --no-restore", prChecks);
|
||||
Assert.Contains("GmRelay.DiscordBot.csproj", appHostProject);
|
||||
Assert.Contains("Projects.GmRelay_DiscordBot", appHostProgram);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Version_ShouldBeSynchronizedForDiscordFeatureRelease()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
|
||||
Assert.Contains("<Version>2.4.0</Version>", File.ReadAllText(Path.Combine(repoRoot, "Directory.Build.props")));
|
||||
Assert.Contains("VERSION: 2.4.0", File.ReadAllText(Path.Combine(repoRoot, ".gitea", "workflows", "deploy.yml")));
|
||||
Assert.Contains("gmrelay-bot:2.4.0", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
|
||||
Assert.Contains("gmrelay-web:2.4.0", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
|
||||
Assert.Contains("gmrelay-discord-bot:2.4.0", File.ReadAllText(Path.Combine(repoRoot, "compose.yaml")));
|
||||
Assert.Contains(
|
||||
"v2.4.0",
|
||||
File.ReadAllText(Path.Combine(repoRoot, "src", "GmRelay.Web", "Components", "Layout", "NavMenu.razor")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Discord;
|
||||
|
||||
public sealed class DiscordStartupTests
|
||||
{
|
||||
private static string GetRepoRoot()
|
||||
{
|
||||
var dir = AppContext.BaseDirectory;
|
||||
while (!string.IsNullOrEmpty(dir) && !File.Exists(Path.Combine(dir, "Directory.Build.props")))
|
||||
{
|
||||
dir = Directory.GetParent(dir)?.FullName;
|
||||
}
|
||||
|
||||
return dir ?? throw new InvalidOperationException("Could not find repo root");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Program_ShouldValidateDiscordTokenBeforeRunning()
|
||||
{
|
||||
var program = ReadProgram();
|
||||
|
||||
Assert.Contains("GetRequiredSection(\"Discord\")", program);
|
||||
Assert.Contains("DiscordOptions", program);
|
||||
Assert.Contains(".Validate()", program);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Program_ShouldRegisterServiceDefaultsAndPostgresDataSource()
|
||||
{
|
||||
var program = ReadProgram();
|
||||
|
||||
Assert.Contains("builder.AddServiceDefaults()", program);
|
||||
Assert.Contains("ConnectionStrings:gmrelaydb is required", program);
|
||||
Assert.Contains("NpgsqlDataSource", program);
|
||||
Assert.Contains("SecretRedactor.RedactConnectionString", program);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Program_ShouldRegisterNetCordGatewayApplicationCommandsAndComponents()
|
||||
{
|
||||
var program = ReadProgram();
|
||||
|
||||
Assert.Contains(".AddDiscordGateway", program);
|
||||
Assert.Contains(".AddApplicationCommands", program);
|
||||
Assert.Contains(".AddComponentInteractions", program);
|
||||
Assert.Contains(".AddGatewayHandlers", program);
|
||||
Assert.Contains("AddSlashCommand", program);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LifecycleLogger_ShouldLogGatewayLifecycleEventsWithoutTokenValues()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var loggerPath = Path.Combine(
|
||||
repoRoot,
|
||||
"src",
|
||||
"GmRelay.DiscordBot",
|
||||
"Infrastructure",
|
||||
"Logging",
|
||||
"DiscordGatewayLifecycleLogger.cs");
|
||||
|
||||
Assert.True(File.Exists(loggerPath), "Discord gateway lifecycle logger should exist.");
|
||||
|
||||
var logger = File.ReadAllText(loggerPath);
|
||||
Assert.Contains("IReadyGatewayHandler", logger);
|
||||
Assert.Contains("IDisconnectGatewayHandler", logger);
|
||||
Assert.Contains("IResumeGatewayHandler", logger);
|
||||
Assert.Contains("LogInformation", logger);
|
||||
Assert.DoesNotContain("Token", logger);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Program_ShouldRegisterDiscordSessionHandlers()
|
||||
{
|
||||
var program = ReadProgram();
|
||||
Assert.Contains("DiscordListSessionsHandler", program);
|
||||
Assert.Contains("DiscordNewSessionHandler", program);
|
||||
Assert.Contains("DiscordPermissionChecker", program);
|
||||
Assert.Contains("DiscordPlatformMessenger", program);
|
||||
Assert.Contains("IPlatformMessenger", program);
|
||||
}
|
||||
|
||||
private static string ReadProgram()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
return File.ReadAllText(Path.Combine(repoRoot, "src", "GmRelay.DiscordBot", "Program.cs"));
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
using GmRelay.Bot.Features.Sessions.CreateSession;
|
||||
using GmRelay.Shared.Platform;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Features.Sessions.CreateSession;
|
||||
|
||||
public sealed class PlatformNeutralSessionInteractionCommandTests
|
||||
{
|
||||
[Fact]
|
||||
public void JoinSessionCommand_ShouldExposePlatformNeutralInteractionContext()
|
||||
{
|
||||
AssertProperty<JoinSessionCommand>("SessionId", typeof(Guid));
|
||||
AssertProperty<JoinSessionCommand>("User", typeof(PlatformUser));
|
||||
AssertProperty<JoinSessionCommand>("InteractionId", typeof(string));
|
||||
AssertProperty<JoinSessionCommand>("Group", typeof(PlatformGroup));
|
||||
AssertProperty<JoinSessionCommand>("ScheduleMessage", typeof(PlatformMessageRef));
|
||||
AssertNoTelegramSpecificProperties<JoinSessionCommand>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LeaveSessionCommand_ShouldExposePlatformNeutralInteractionContext()
|
||||
{
|
||||
AssertProperty<LeaveSessionCommand>("SessionId", typeof(Guid));
|
||||
AssertProperty<LeaveSessionCommand>("User", typeof(PlatformUser));
|
||||
AssertProperty<LeaveSessionCommand>("InteractionId", typeof(string));
|
||||
AssertProperty<LeaveSessionCommand>("Group", typeof(PlatformGroup));
|
||||
AssertProperty<LeaveSessionCommand>("ScheduleMessage", typeof(PlatformMessageRef));
|
||||
AssertNoTelegramSpecificProperties<LeaveSessionCommand>();
|
||||
}
|
||||
|
||||
private static void AssertProperty<T>(string name, Type expectedType)
|
||||
{
|
||||
var property = Assert.Single(typeof(T).GetProperties(), property => property.Name == name);
|
||||
|
||||
Assert.Equal(expectedType, property.PropertyType);
|
||||
}
|
||||
|
||||
private static void AssertNoTelegramSpecificProperties<T>()
|
||||
{
|
||||
var names = typeof(T).GetProperties().Select(property => property.Name).ToArray();
|
||||
|
||||
Assert.DoesNotContain(names, name => name.Contains("Telegram", StringComparison.Ordinal));
|
||||
Assert.DoesNotContain("ChatId", names);
|
||||
Assert.DoesNotContain("MessageId", names);
|
||||
Assert.DoesNotContain("TelegramUserId", names);
|
||||
Assert.DoesNotContain("TelegramUsername", names);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
namespace GmRelay.Bot.Tests.Features.Sessions.CreateSession;
|
||||
|
||||
public sealed class PlatformNeutralSessionInteractionSqlTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task JoinSessionHandler_ShouldPersistPlayersByPlatformIdentity()
|
||||
{
|
||||
var handler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/CreateSession/JoinSessionHandler.cs");
|
||||
|
||||
Assert.Contains("platform, external_user_id", handler, StringComparison.Ordinal);
|
||||
Assert.Contains("ON CONFLICT (platform, external_user_id)", handler, StringComparison.Ordinal);
|
||||
Assert.Contains("ExternalUserId", handler, StringComparison.Ordinal);
|
||||
Assert.Contains("ExternalUsername", handler, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("TelegramPlatformIds.", handler, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("command.TelegramUserId", handler, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("command.TelegramUsername", handler, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LeaveSessionHandler_ShouldFindParticipantsByPlatformIdentity()
|
||||
{
|
||||
var handler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/CreateSession/LeaveSessionHandler.cs");
|
||||
|
||||
Assert.Contains("p.platform = @Platform", handler, StringComparison.Ordinal);
|
||||
Assert.Contains("p.external_user_id = @ExternalUserId", handler, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("p.telegram_id = @TelegramUserId", handler, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("TelegramPlatformIds.", handler, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("command.TelegramUserId", handler, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SessionInteractionHandlers_ShouldUpdateSchedulesThroughCommandMessageReference()
|
||||
{
|
||||
var joinHandler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/CreateSession/JoinSessionHandler.cs");
|
||||
var leaveHandler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/CreateSession/LeaveSessionHandler.cs");
|
||||
|
||||
Assert.Contains("new PlatformScheduleMessage(", joinHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("command.Group", joinHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("command.ScheduleMessage", joinHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("new PlatformScheduleMessage(", leaveHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("command.Group", leaveHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("command.ScheduleMessage", leaveHandler, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static async Task<string> ReadRepositoryFileAsync(string relativePath)
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null)
|
||||
{
|
||||
var candidate = Path.Combine(directory.FullName, relativePath);
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return await File.ReadAllTextAsync(candidate);
|
||||
}
|
||||
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
throw new FileNotFoundException($"Could not locate repository file '{relativePath}'.");
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,13 @@
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.5" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
@@ -20,6 +25,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\GmRelay.Bot\GmRelay.Bot.csproj" />
|
||||
<ProjectReference Include="..\..\src\GmRelay.DiscordBot\GmRelay.DiscordBot.csproj" />
|
||||
<ProjectReference Include="..\..\src\GmRelay.Web\GmRelay.Web.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
namespace GmRelay.Bot.Tests.Infrastructure.Database;
|
||||
|
||||
public sealed class PlatformIdentityMigrationTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task MigrationV016_ShouldAddPlatformIdentityColumns()
|
||||
{
|
||||
var migration = await ReadRepositoryFileAsync("src/GmRelay.Bot/Migrations/V016__add_platform_identity.sql");
|
||||
|
||||
Assert.Contains("players", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("platform", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("external_user_id", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("external_username", migration, StringComparison.Ordinal);
|
||||
|
||||
Assert.Contains("game_groups", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("external_group_id", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("external_channel_id", migration, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MigrationV016_ShouldCreatePlatformMessagesTable()
|
||||
{
|
||||
var migration = await ReadRepositoryFileAsync("src/GmRelay.Bot/Migrations/V016__add_platform_identity.sql");
|
||||
|
||||
Assert.Contains("CREATE TABLE platform_messages", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("platform", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("group_id", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("batch_id", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("session_id", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("external_thread_id", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("external_message_id", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("purpose", migration, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MigrationV016_ShouldBackfillExistingTelegramData()
|
||||
{
|
||||
var migration = await ReadRepositoryFileAsync("src/GmRelay.Bot/Migrations/V016__add_platform_identity.sql");
|
||||
|
||||
Assert.Contains("UPDATE players", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("UPDATE game_groups", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("'Telegram'", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("telegram_id", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("telegram_chat_id", migration, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MigrationV016_ShouldNotDropLegacyTelegramColumns()
|
||||
{
|
||||
var migration = await ReadRepositoryFileAsync("src/GmRelay.Bot/Migrations/V016__add_platform_identity.sql");
|
||||
|
||||
Assert.DoesNotContain("DROP COLUMN telegram_id", migration, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("DROP COLUMN telegram_chat_id", migration, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("DROP COLUMN telegram_username", migration, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("DROP COLUMN gm_telegram_id", migration, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Code_ShouldQueryPlayersUsingExternalUserIdFallback()
|
||||
{
|
||||
var createHandler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/CreateSession/CreateSessionHandler.cs");
|
||||
|
||||
Assert.Contains("external_user_id", createHandler, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Code_ShouldQueryGroupsUsingExternalGroupIdFallback()
|
||||
{
|
||||
var createHandler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/CreateSession/CreateSessionHandler.cs");
|
||||
|
||||
Assert.Contains("external_group_id", createHandler, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task JoinSessionHandler_ShouldDualWritePlatformIdentity()
|
||||
{
|
||||
var handler = await ReadRepositoryFileAsync("src/GmRelay.Bot/Features/Sessions/CreateSession/JoinSessionHandler.cs");
|
||||
|
||||
Assert.Contains("external_user_id", handler, StringComparison.Ordinal);
|
||||
Assert.Contains("external_username", handler, StringComparison.Ordinal);
|
||||
Assert.Contains("platform", handler, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WebSessionService_ShouldDualWritePlatformIdentity()
|
||||
{
|
||||
var service = await ReadRepositoryFileAsync("src/GmRelay.Web/Services/SessionService.cs");
|
||||
|
||||
Assert.Contains("external_user_id", service, StringComparison.Ordinal);
|
||||
Assert.Contains("external_username", service, StringComparison.Ordinal);
|
||||
Assert.Contains("platform", service, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AttendanceStatsFunction_ShouldReferenceExternalUsername()
|
||||
{
|
||||
var statsMigration = await ReadRepositoryFileAsync("src/GmRelay.Bot/Migrations/V012__add_attendance_stats.sql");
|
||||
|
||||
Assert.Contains("external_username", statsMigration, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MigrationV017_ShouldAllowPlayersWithoutLegacyTelegramId()
|
||||
{
|
||||
var migration = await ReadRepositoryFileAsync("src/GmRelay.Bot/Migrations/V017__allow_platform_neutral_players.sql");
|
||||
|
||||
Assert.Contains("ALTER TABLE players", migration, StringComparison.Ordinal);
|
||||
Assert.Contains("telegram_id DROP NOT NULL", migration, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static async Task<string> ReadRepositoryFileAsync(string relativePath)
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null)
|
||||
{
|
||||
var candidate = Path.Combine(directory.FullName, relativePath);
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return await File.ReadAllTextAsync(candidate);
|
||||
}
|
||||
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
throw new FileNotFoundException($"Could not locate repository file '{relativePath}'.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using GmRelay.Bot.Infrastructure.Health;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Infrastructure.Health;
|
||||
|
||||
public sealed class BotHealthCheckHostedServiceTests : IDisposable
|
||||
{
|
||||
private readonly BotHealthCheckHostedService _service;
|
||||
private readonly int _port;
|
||||
|
||||
public BotHealthCheckHostedServiceTests()
|
||||
{
|
||||
_port = GetAvailablePort();
|
||||
var config = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["HealthCheck:Prefix"] = $"http://localhost:{_port}/"
|
||||
})
|
||||
.Build();
|
||||
|
||||
_service = new BotHealthCheckHostedService(
|
||||
NullLogger<BotHealthCheckHostedService>.Instance,
|
||||
config);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_service.StopAsync(CancellationToken.None).Wait(TimeSpan.FromSeconds(5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HealthEndpoint_ShouldReturn200_WhenServiceIsRunning()
|
||||
{
|
||||
await _service.StartAsync(CancellationToken.None);
|
||||
|
||||
using var client = new HttpClient();
|
||||
client.Timeout = TimeSpan.FromSeconds(5);
|
||||
var response = await client.GetAsync($"http://localhost:{_port}/health");
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
private static int GetAvailablePort()
|
||||
{
|
||||
var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
listener.Stop();
|
||||
return port;
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
namespace GmRelay.Bot.Tests.Infrastructure.Telegram;
|
||||
|
||||
public sealed class TelegramPlatformMessengerSourceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Program_ShouldRegisterTelegramPlatformMessenger()
|
||||
{
|
||||
var program = await ReadRepositoryFileAsync("src/GmRelay.Bot/Program.cs");
|
||||
|
||||
Assert.Contains("IPlatformMessenger", program, StringComparison.Ordinal);
|
||||
Assert.Contains("TelegramPlatformMessenger", program, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/CreateSession/JoinSessionHandler.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/CreateSession/LeaveSessionHandler.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/CreateSession/CancelSessionHandler.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/CreateSession/PromoteWaitlistedPlayerHandler.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/RescheduleSession/InitiateRescheduleHandler.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/RescheduleSession/HandleRescheduleTimeInputHandler.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/RescheduleSession/HandleRescheduleVoteHandler.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/RescheduleSession/RescheduleVotingDeadlineService.cs")]
|
||||
[InlineData("src/GmRelay.Bot/Features/Sessions/ExportCalendar/ExportCalendarHandler.cs")]
|
||||
public async Task SessionFlows_ShouldUsePlatformMessengerForOutboundTelegramWork(string relativePath)
|
||||
{
|
||||
var source = await ReadRepositoryFileAsync(relativePath);
|
||||
|
||||
Assert.Contains("IPlatformMessenger", source, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("BatchMessageEditor.EditBatchMessageAsync", source, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(".AnswerCallbackQuery(", source, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TelegramPlatformMessenger_ShouldOwnTelegramBotClientCalls()
|
||||
{
|
||||
var source = await ReadRepositoryFileAsync("src/GmRelay.Bot/Infrastructure/Telegram/TelegramPlatformMessenger.cs");
|
||||
|
||||
Assert.Contains("ITelegramBotClient", source, StringComparison.Ordinal);
|
||||
Assert.Contains("BatchMessageEditor.EditBatchMessageAsync", source, StringComparison.Ordinal);
|
||||
Assert.Contains("AnswerCallbackQuery", source, StringComparison.Ordinal);
|
||||
Assert.Contains("SendDocument", source, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static async Task<string> ReadRepositoryFileAsync(string relativePath)
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null)
|
||||
{
|
||||
var candidate = Path.Combine(directory.FullName, relativePath);
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return await File.ReadAllTextAsync(candidate);
|
||||
}
|
||||
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
throw new FileNotFoundException($"Could not locate repository file '{relativePath}'.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using GmRelay.Bot.Infrastructure.Telegram;
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Infrastructure.Telegram;
|
||||
|
||||
public sealed class TelegramPlatformMessengerTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task UpdateScheduleAsync_ShouldRejectNonTelegramExistingMessageReference()
|
||||
{
|
||||
var messenger = CreateMessenger();
|
||||
var message = new PlatformScheduleMessage(
|
||||
new PlatformGroup(PlatformKind.Telegram, "100", "Telegram group"),
|
||||
CreateView(),
|
||||
new PlatformMessageRef(PlatformKind.Discord, "100", null, "200"));
|
||||
|
||||
await Assert.ThrowsAsync<NotSupportedException>(
|
||||
() => messenger.UpdateScheduleAsync(message, CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateScheduleAsync_ShouldRejectMismatchedGroupAndExistingMessageReference()
|
||||
{
|
||||
var messenger = CreateMessenger();
|
||||
var message = new PlatformScheduleMessage(
|
||||
new PlatformGroup(PlatformKind.Telegram, "100", "Telegram group", ExternalThreadId: "7"),
|
||||
CreateView(),
|
||||
new PlatformMessageRef(PlatformKind.Telegram, "101", "7", "200"));
|
||||
|
||||
var exception = await Assert.ThrowsAsync<ArgumentException>(
|
||||
() => messenger.UpdateScheduleAsync(message, CancellationToken.None));
|
||||
|
||||
Assert.Equal("message", exception.ParamName);
|
||||
Assert.Contains("Existing schedule message reference must match the schedule group.", exception.Message);
|
||||
}
|
||||
|
||||
private static TelegramPlatformMessenger CreateMessenger() =>
|
||||
new(null!, NullLogger<TelegramPlatformMessenger>.Instance);
|
||||
|
||||
private static SessionBatchViewModel CreateView() =>
|
||||
new("Test batch", []);
|
||||
}
|
||||
+4
-4
@@ -43,18 +43,18 @@ public sealed class TelegramTopicIntegrationSmokeTests
|
||||
Assert.Contains("messageThreadId: session.ThreadId", rsvpHandler, StringComparison.Ordinal);
|
||||
|
||||
Assert.Contains("int? MessageThreadId", cancelHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("messageThreadId: command.MessageThreadId", cancelHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("TelegramPlatformIds.Group(command.ChatId, command.MessageThreadId)", cancelHandler, StringComparison.Ordinal);
|
||||
|
||||
Assert.Contains("int? MessageThreadId", initiateRescheduleHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("messageThreadId: command.MessageThreadId", initiateRescheduleHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("TelegramPlatformIds.Group(command.ChatId, command.MessageThreadId)", initiateRescheduleHandler, StringComparison.Ordinal);
|
||||
|
||||
Assert.Contains("int? ThreadId", rescheduleInputHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("s.thread_id AS ThreadId", rescheduleInputHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("messageThreadId: proposal.ThreadId", rescheduleInputHandler, StringComparison.Ordinal);
|
||||
Assert.Contains("TelegramPlatformIds.Group(proposal.TelegramChatId, proposal.ThreadId)", rescheduleInputHandler, StringComparison.Ordinal);
|
||||
|
||||
Assert.Contains("int? ThreadId", rescheduleDeadlineService, StringComparison.Ordinal);
|
||||
Assert.Contains("s.thread_id AS ThreadId", rescheduleDeadlineService, StringComparison.Ordinal);
|
||||
Assert.Contains("messageThreadId: proposal.ThreadId", rescheduleDeadlineService, StringComparison.Ordinal);
|
||||
Assert.Contains("TelegramPlatformIds.Group(proposal.TelegramChatId, proposal.ThreadId)", rescheduleDeadlineService, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static async Task<string> ReadRepositoryFileAsync(string relativePath)
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
using GmRelay.Shared.Platform;
|
||||
using GmRelay.Shared.Rendering;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Platform;
|
||||
|
||||
public sealed class PlatformContractsTests
|
||||
{
|
||||
[Fact]
|
||||
public void PlatformKind_ShouldDefineTelegramDiscordAndMaxSentinel()
|
||||
{
|
||||
Assert.Equal(0, (int)PlatformKind.Telegram);
|
||||
Assert.Equal(1, (int)PlatformKind.Discord);
|
||||
Assert.Equal(2, (int)PlatformKind.Max);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PlatformContracts_ShouldBeTelegramAssemblyFree()
|
||||
{
|
||||
var contractTypes = new[]
|
||||
{
|
||||
typeof(PlatformUser),
|
||||
typeof(PlatformGroup),
|
||||
typeof(PlatformMessageRef),
|
||||
typeof(PlatformMessageAction),
|
||||
typeof(PlatformScheduleMessage),
|
||||
typeof(PlatformPrivateMessage),
|
||||
typeof(PlatformInteractionReply),
|
||||
typeof(PlatformCalendarFile),
|
||||
typeof(IPlatformMessenger)
|
||||
};
|
||||
|
||||
Assert.All(contractTypes, type =>
|
||||
Assert.DoesNotContain(
|
||||
"Telegram",
|
||||
string.Join(" ", type.Assembly.GetReferencedAssemblies().Select(value => value.Name)),
|
||||
StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PlatformScheduleMessage_ShouldCarrySharedViewModelWithoutPlatformTypes()
|
||||
{
|
||||
var sessionId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
|
||||
var view = SessionBatchViewBuilder.Build(
|
||||
"Campaign",
|
||||
[new SessionBatchDto(sessionId, new DateTime(2026, 5, 15, 16, 0, 0, DateTimeKind.Utc), "Planned", 4, "https://example.test/game")],
|
||||
[]);
|
||||
var group = new PlatformGroup(PlatformKind.Discord, "guild-1", "Guild", "channel-1", "thread-1");
|
||||
|
||||
var message = new PlatformScheduleMessage(group, view, ExistingMessage: null);
|
||||
|
||||
Assert.Equal(PlatformKind.Discord, message.Group.Platform);
|
||||
Assert.Same(view, message.View);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Xunit;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Project;
|
||||
|
||||
public class LicenseFileTests
|
||||
{
|
||||
private static string GetRepoRoot()
|
||||
{
|
||||
var dir = AppContext.BaseDirectory;
|
||||
while (!string.IsNullOrEmpty(dir) && !File.Exists(Path.Combine(dir, "Directory.Build.props")))
|
||||
{
|
||||
dir = Directory.GetParent(dir)?.FullName;
|
||||
}
|
||||
return dir ?? throw new InvalidOperationException("Could not find repo root");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LicenseFile_ExistsInRepoRoot()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var licensePath = Path.Combine(repoRoot, "LICENSE");
|
||||
Assert.True(File.Exists(licensePath), "LICENSE file should exist in repo root");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LicenseFile_ContainsMitLicenseText()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var licensePath = Path.Combine(repoRoot, "LICENSE");
|
||||
Assert.True(File.Exists(licensePath), "LICENSE file should exist");
|
||||
var content = File.ReadAllText(licensePath);
|
||||
Assert.Contains("MIT License", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Readme_ReferencesLicenseFile()
|
||||
{
|
||||
var repoRoot = GetRepoRoot();
|
||||
var readmePath = Path.Combine(repoRoot, "README.md");
|
||||
Assert.True(File.Exists(readmePath), "README.md should exist");
|
||||
var content = File.ReadAllText(readmePath);
|
||||
Assert.Contains("./LICENSE", content);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
using GmRelay.DiscordBot.Rendering;
|
||||
using GmRelay.Shared.Domain;
|
||||
using GmRelay.Shared.Rendering;
|
||||
using NetCord;
|
||||
using NetCord.Rest;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Rendering;
|
||||
|
||||
public sealed class DiscordSessionBatchRendererTests
|
||||
{
|
||||
[Fact]
|
||||
public void Render_ShouldProduceEmbedsAndButtonsForMultipleSessions()
|
||||
{
|
||||
var firstSessionId = Guid.NewGuid();
|
||||
var secondSessionId = Guid.NewGuid();
|
||||
var cancelledSessionId = Guid.NewGuid();
|
||||
|
||||
var sessions = new[]
|
||||
{
|
||||
new SessionBatchDto(secondSessionId, new DateTime(2026, 4, 27, 18, 0, 0, DateTimeKind.Utc), SessionStatus.Planned, 4, "https://example.com/game2"),
|
||||
new SessionBatchDto(cancelledSessionId, new DateTime(2026, 4, 28, 18, 0, 0, DateTimeKind.Utc), SessionStatus.Cancelled, null, ""),
|
||||
new SessionBatchDto(firstSessionId, new DateTime(2026, 4, 26, 18, 0, 0, DateTimeKind.Utc), SessionStatus.Planned, 2, "https://example.com/game1")
|
||||
};
|
||||
var participants = new[]
|
||||
{
|
||||
new ParticipantBatchDto(secondSessionId, "Alice", "alice", ParticipantRegistrationStatus.Active),
|
||||
new ParticipantBatchDto(secondSessionId, "Charlie", null, ParticipantRegistrationStatus.Waitlisted),
|
||||
new ParticipantBatchDto(cancelledSessionId, "Bob", null, ParticipantRegistrationStatus.Active)
|
||||
};
|
||||
|
||||
var view = SessionBatchViewBuilder.Build("Campaign", sessions, participants);
|
||||
var (embeds, actionRows) = DiscordSessionBatchRenderer.Render(view);
|
||||
|
||||
Assert.Equal(3, embeds.Count);
|
||||
Assert.Equal(2, actionRows.Count); // cancelled skipped
|
||||
|
||||
// Embed titles contain game title and Moscow date
|
||||
Assert.Contains(embeds, e => e.Title!.Contains("Campaign") && e.Title.Contains("26"));
|
||||
Assert.Contains(embeds, e => e.Title!.Contains("Campaign") && e.Title.Contains("27"));
|
||||
Assert.Contains(embeds, e => e.Title!.Contains("Campaign") && e.Title.Contains("28"));
|
||||
|
||||
// Cancelled session embed description indicates cancellation
|
||||
var cancelledEmbed = embeds.First(e => e.Description!.Contains("отменена") || e.Description.Contains("Отменена"));
|
||||
Assert.NotNull(cancelledEmbed);
|
||||
|
||||
// Active session embeds contain player names
|
||||
Assert.Contains(embeds, e => e.Description!.Contains("Alice"));
|
||||
Assert.Contains(embeds, e => e.Description!.Contains("Charlie"));
|
||||
|
||||
// Buttons for active sessions
|
||||
var allButtons = actionRows.SelectMany(r => r).OfType<ButtonProperties>().ToList();
|
||||
Assert.Contains(allButtons, b => b.CustomId == $"join_session:{firstSessionId}");
|
||||
Assert.Contains(allButtons, b => b.CustomId == $"leave_session:{firstSessionId}");
|
||||
Assert.Contains(allButtons, b => b.CustomId == $"join_session:{secondSessionId}");
|
||||
Assert.Contains(allButtons, b => b.CustomId == $"leave_session:{secondSessionId}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Render_ShouldSkipActionRowsForCancelledSessions()
|
||||
{
|
||||
var cancelledSessionId = Guid.NewGuid();
|
||||
var sessions = new[] { new SessionBatchDto(cancelledSessionId, DateTime.UtcNow, SessionStatus.Cancelled, null, "") };
|
||||
var participants = Array.Empty<ParticipantBatchDto>();
|
||||
|
||||
var view = SessionBatchViewBuilder.Build("Test", sessions, participants);
|
||||
var (embeds, actionRows) = DiscordSessionBatchRenderer.Render(view);
|
||||
|
||||
Assert.Single(embeds);
|
||||
Assert.Empty(actionRows);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Render_ShouldShowWaitlistButtonWhenFull()
|
||||
{
|
||||
var sessionId = Guid.NewGuid();
|
||||
var sessions = new[] { new SessionBatchDto(sessionId, DateTime.UtcNow, SessionStatus.Planned, 1, "https://example.com/game") };
|
||||
var participants = new[] { new ParticipantBatchDto(sessionId, "Alice", "alice", ParticipantRegistrationStatus.Active) };
|
||||
|
||||
var view = SessionBatchViewBuilder.Build("Test", sessions, participants);
|
||||
var (_, actionRows) = DiscordSessionBatchRenderer.Render(view);
|
||||
var buttons = actionRows.SelectMany(r => r).OfType<ButtonProperties>().ToList();
|
||||
var joinButton = buttons.First(b => b.CustomId == $"join_session:{sessionId}");
|
||||
|
||||
Assert.Contains("ожидания", joinButton.Label);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Render_ShouldUseRedColorForCancelledSessions()
|
||||
{
|
||||
var sessionId = Guid.NewGuid();
|
||||
var sessions = new[] { new SessionBatchDto(sessionId, DateTime.UtcNow, SessionStatus.Cancelled, null, "") };
|
||||
var participants = Array.Empty<ParticipantBatchDto>();
|
||||
|
||||
var view = SessionBatchViewBuilder.Build("Test", sessions, participants);
|
||||
var (embeds, _) = DiscordSessionBatchRenderer.Render(view);
|
||||
|
||||
Assert.Equal(0xED4245, embeds[0].Color.RawValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Render_ShouldUseGreenColorForOpenSessions()
|
||||
{
|
||||
var sessionId = Guid.NewGuid();
|
||||
var sessions = new[] { new SessionBatchDto(sessionId, DateTime.UtcNow, SessionStatus.Planned, 4, "https://example.com/game") };
|
||||
var participants = Array.Empty<ParticipantBatchDto>();
|
||||
|
||||
var view = SessionBatchViewBuilder.Build("Test", sessions, participants);
|
||||
var (embeds, _) = DiscordSessionBatchRenderer.Render(view);
|
||||
|
||||
Assert.Equal(0x57F287, embeds[0].Color.RawValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Render_ShouldUseYellowColorForFullSessions()
|
||||
{
|
||||
var sessionId = Guid.NewGuid();
|
||||
var sessions = new[] { new SessionBatchDto(sessionId, DateTime.UtcNow, SessionStatus.Planned, 1, "https://example.com/game") };
|
||||
var participants = new[] { new ParticipantBatchDto(sessionId, "Alice", "alice", ParticipantRegistrationStatus.Active) };
|
||||
|
||||
var view = SessionBatchViewBuilder.Build("Test", sessions, participants);
|
||||
var (embeds, _) = DiscordSessionBatchRenderer.Render(view);
|
||||
|
||||
Assert.Equal(0xFEE75C, embeds[0].Color.RawValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Render_ShouldHandleRescheduleStatus()
|
||||
{
|
||||
var sessionId = Guid.NewGuid();
|
||||
var sessions = new[] { new SessionBatchDto(sessionId, DateTime.UtcNow, "Rescheduled", 4, "") };
|
||||
var participants = Array.Empty<ParticipantBatchDto>();
|
||||
|
||||
var view = SessionBatchViewBuilder.Build("Test", sessions, participants);
|
||||
var (embeds, actionRows) = DiscordSessionBatchRenderer.Render(view);
|
||||
|
||||
Assert.Single(embeds);
|
||||
Assert.Single(actionRows); // not cancelled → actions present
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using GmRelay.Web.Health;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Npgsql;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace GmRelay.Bot.Tests.Web;
|
||||
|
||||
public sealed class WebHealthEndpointTests
|
||||
{
|
||||
private static WebApplication CreateTestApp(HealthStatus npgsqlStatus)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder();
|
||||
builder.WebHost.UseTestServer();
|
||||
builder.Services.AddHealthChecks()
|
||||
.AddCheck("self", () => HealthCheckResult.Healthy(), ["live"])
|
||||
.AddCheck("npgsql", () => new HealthCheckResult(npgsqlStatus));
|
||||
|
||||
var app = builder.Build();
|
||||
app.MapHealthChecks("/health", new HealthCheckOptions
|
||||
{
|
||||
ResponseWriter = async (context, report) =>
|
||||
{
|
||||
context.Response.ContentType = "application/json";
|
||||
var response = new
|
||||
{
|
||||
status = report.Status == HealthStatus.Healthy ? "healthy" : "unhealthy",
|
||||
timestamp = DateTimeOffset.UtcNow.ToString("O")
|
||||
};
|
||||
await context.Response.WriteAsJsonAsync(response);
|
||||
}
|
||||
});
|
||||
app.MapHealthChecks("/alive", new HealthCheckOptions
|
||||
{
|
||||
Predicate = r => r.Tags.Contains("live")
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HealthEndpoint_ShouldReturn200AndJson_WhenHealthy()
|
||||
{
|
||||
await using var app = CreateTestApp(HealthStatus.Healthy);
|
||||
await app.StartAsync();
|
||||
using var client = app.GetTestClient();
|
||||
|
||||
var response = await client.GetAsync("/health");
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var content = await response.Content.ReadAsStringAsync();
|
||||
using var doc = JsonDocument.Parse(content);
|
||||
Assert.Equal("healthy", doc.RootElement.GetProperty("status").GetString());
|
||||
Assert.NotNull(doc.RootElement.GetProperty("timestamp").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HealthEndpoint_ShouldReturn503_WhenDatabaseUnavailable()
|
||||
{
|
||||
await using var app = CreateTestApp(HealthStatus.Unhealthy);
|
||||
await app.StartAsync();
|
||||
using var client = app.GetTestClient();
|
||||
|
||||
var response = await client.GetAsync("/health");
|
||||
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NpgsqlHealthCheck_ShouldReturnUnhealthy_WhenDatabaseIsInaccessible()
|
||||
{
|
||||
var dataSource = NpgsqlDataSource.Create("Host=localhost;Port=5432;Database=gmrelay_db;Username=gmrelay;Password=fake");
|
||||
var healthCheck = new NpgsqlHealthCheck(dataSource);
|
||||
|
||||
var result = await healthCheck.CheckHealthAsync(new HealthCheckContext());
|
||||
|
||||
Assert.Equal(HealthStatus.Unhealthy, result.Status);
|
||||
Assert.NotNull(result.Exception);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,16 @@
|
||||
"resolved": "6.0.4",
|
||||
"contentHash": "lkhqpF8Pu2Y7IiN7OntbsTtdbpR1syMsm2F3IgX6ootA4ffRqWL5jF7XipHuZQTdVuWG/gVAAcf8mjk8Tz0xPg=="
|
||||
},
|
||||
"Microsoft.AspNetCore.Mvc.Testing": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.5, )",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "MfacYQ7jNzj6073YobyoFfXpNmGqrV1UCywTM339DOcYpfalcM4K4heFjV5k3dDkKkWOGWO/DV3hdmVRqFkIxA==",
|
||||
"dependencies": {
|
||||
"Microsoft.AspNetCore.TestHost": "10.0.5",
|
||||
"Microsoft.Extensions.DependencyModel": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.NET.Test.Sdk": {
|
||||
"type": "Direct",
|
||||
"requested": "[17.14.1, )",
|
||||
@@ -47,14 +57,6 @@
|
||||
"contentHash": "nEYgziWN7hksgEQEWy24JypcMCU8gKYcIIyPL05JfdXxUWuPRLotH/KOeuHevAjSEOYkL3dtGakBkJAuPobGmA==",
|
||||
"dependencies": {
|
||||
"AspNetCore.HealthChecks.NpgSql": "9.0.0",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Binder": "10.0.5",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Diagnostics.HealthChecks": "10.0.5",
|
||||
"Microsoft.Extensions.Hosting.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5",
|
||||
"Microsoft.Extensions.Primitives": "10.0.5",
|
||||
"Npgsql.DependencyInjection": "10.0.1",
|
||||
"Npgsql.OpenTelemetry": "10.0.1",
|
||||
"OpenTelemetry.Extensions.Hosting": "1.15.0"
|
||||
@@ -65,7 +67,6 @@
|
||||
"resolved": "9.0.0",
|
||||
"contentHash": "npc58/AD5zuVxERdhCl2Kb7WnL37mwX42SJcXIwvmEig0/dugOLg3SIwtfvvh3TnvTwR/sk5LYNkkPaBdks61A==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Diagnostics.HealthChecks": "8.0.11",
|
||||
"Npgsql": "8.0.3"
|
||||
}
|
||||
},
|
||||
@@ -82,10 +83,7 @@
|
||||
"dbup-core": {
|
||||
"type": "Transitive",
|
||||
"resolved": "6.1.1",
|
||||
"contentHash": "kgpuyJVEFJHoIj/slnc994Go88aoeZqNDfGHDBr4sh7CsEWwJhOTCt/FJqO4ziUImL5L0NEY0kxxOiNgPKI2Fw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Logging.Abstractions": "8.0.0"
|
||||
}
|
||||
"contentHash": "kgpuyJVEFJHoIj/slnc994Go88aoeZqNDfGHDBr4sh7CsEWwJhOTCt/FJqO4ziUImL5L0NEY0kxxOiNgPKI2Fw=="
|
||||
},
|
||||
"dbup-postgresql": {
|
||||
"type": "Transitive",
|
||||
@@ -96,6 +94,11 @@
|
||||
"dbup-core": "6.1.1"
|
||||
}
|
||||
},
|
||||
"Microsoft.AspNetCore.TestHost": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "PJEdrZnnhvxIEXzDdvdZ38GvpdaiUfKkZ99kudS8riJwhowFb/Qh26Wjk9smrCWcYdMFQmpN5epGiL4o1s8LYA=="
|
||||
},
|
||||
"Microsoft.CodeCoverage": {
|
||||
"type": "Transitive",
|
||||
"resolved": "17.14.1",
|
||||
@@ -104,252 +107,33 @@
|
||||
"Microsoft.Extensions.AmbientMetadata.Application": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "CNrEjaOCZ8d1HtB0mvpiX4EWxLkee2xy+CsYXxmsEYJSFgw3OmF9pIhP/tCTeYBHhpsKJj5wM63G8IBFGxAcsw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.2",
|
||||
"Microsoft.Extensions.Hosting.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.2"
|
||||
}
|
||||
"contentHash": "CNrEjaOCZ8d1HtB0mvpiX4EWxLkee2xy+CsYXxmsEYJSFgw3OmF9pIhP/tCTeYBHhpsKJj5wM63G8IBFGxAcsw=="
|
||||
},
|
||||
"Microsoft.Extensions.Compliance.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "1a4xDAT6fRyP8t419q3WvWMmMslDTvI7OAZLWBhn5rysFG0bl5xFenTswd1xAbT/3u3mx4Xyb5bPx+V+18tJeQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.ObjectPool": "10.0.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "8Rx5sqg04FttxrumyG6bmoRuFRgYzK6IVwF1i0/o0cXfKBdDeVpJejKHtJCMjyg9E/DNMVqpqOGe/tCT5gYvVA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Primitives": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "P09QpTHjqHmCLQOTC+WyLkoRNxek4NIvfWt+TnU0etoDUSRxcltyd6+j/ouRbMdLR0j44GqGO+lhI2M4fAHG4g==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Primitives": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.Binder": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "99Z4rjyXopb1MIazDSPcvwYCUdYNO01Cf1GUs2WUjIFAbkGmwzj2vPa2k+3pheJRV+YgNd2QqRKHAri0oBAU4Q==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.CommandLine": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "or9fOLopMUTJOQVJ3bou4aD6PwvsiKf4kZC4EE5sRRKSkmh+wfk/LekJXRjAX88X+1JA9zHjDo+5fiQ7z3MY/A==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.EnvironmentVariables": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "tchMGQ+zVTO40np/Zzg2Li/TIR8bksQgg4UVXZa0OzeFCKWnIYtxE2FVs+eSmjPGCjMS2voZbwN/mUcYfpSTuA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.FileExtensions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "OhTr0O79dP49734lLTqVveivVX9sDXxbI/8vjELAZTHXqoN90mdpgTAgwicJED42iaHMCcZcK6Bj+8wNyBikaw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Physical": "10.0.5",
|
||||
"Microsoft.Extensions.Primitives": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.Json": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "brBM/WP0YAUYh2+QqSYVdK8eQHYQTtTEUJXJ+84Zkdo2buGLja9VSrMIhgoeBUU7JBmcskAib8Lb/N83bvxgYQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.FileExtensions": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Configuration.UserSecrets": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "fhdG6UV9lIp70QhNkVyaHciUVq25IPFkczheVJL9bIFvmnJ+Zghaie6dWkDbbVmxZlHl9gj3zTDxMxJs5zNhIA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Json": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Physical": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "v1SVsowG6YE1YnHVGmLWz57YTRCQRx9pH5ebIESXfm5isI9gA3QaMyg/oMTzPpXYZwSAVDzYItGJKfmV+pqXkQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "iVMtq9eRvzyhx8949EGT0OCYJfXi737SbRVzWXE5GrOgGj5AaZ9eUuxA/BSUfmOMALKn/g8KfFaNQw0eiB3lyA=="
|
||||
"contentHash": "1a4xDAT6fRyP8t419q3WvWMmMslDTvI7OAZLWBhn5rysFG0bl5xFenTswd1xAbT/3u3mx4Xyb5bPx+V+18tJeQ=="
|
||||
},
|
||||
"Microsoft.Extensions.DependencyInjection.AutoActivation": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "Z/OI261l7LnxyODKPx0trQyIHFyicCR/akfn64lGOjPcf4FpAZ7ePAGl2HPvQBUBSNfPTF0gWeCfuFmyftMgYA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Hosting.Abstractions": "10.0.2"
|
||||
}
|
||||
"contentHash": "Z/OI261l7LnxyODKPx0trQyIHFyicCR/akfn64lGOjPcf4FpAZ7ePAGl2HPvQBUBSNfPTF0gWeCfuFmyftMgYA=="
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics": {
|
||||
"Microsoft.Extensions.DependencyModel": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "vAJHd4yOpmKoK+jBuYV7a3y+Ab9U4ARCc29b6qvMy276RgJFw9LFs0DdsPqOL3ahwzyrX7tM+i4cCxU/RX0qAg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "/nYGrpa9/0BZofrVpBbbj+Ns8ZesiPE0V/KxsuHgDgHQopIzN54nRaQGSuvPw16/kI9sW1Zox5yyAPqvf0Jz6A==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5"
|
||||
}
|
||||
"contentHash": "xA4kkL+QS6KCAOKz/O0oquHs44Ob8J7zpBCNt3wjkBWDg5aCqfwG8rWWLsg5V86AM0sB849g9JjPjIdksTCIKg=="
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics.ExceptionSummarization": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "3qMK1D40D10kb5TdBtFJpzz6/WH0NinWs68ZZS8jCFgHMXDiOjGiPOneMmIocCP/wnUUW4Hzf8lMsIE1xIGxDA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.2"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics.HealthChecks": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "REdt95QXHscGdtw/UUgyCW2lF9DJcAOJxmebKW2IkgUjuCAdMODIi2HNOWg5utW98nm8ekgV0Gjqs/sljwwqMw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Hosting.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "NrIMTy7dpqxAvA6kHAYH8cXID/YgeNOy0OqFKpLtkPu5X4WS/basX91UszANzVrMNRAICJ2GOnGiRxJtsRyEQw=="
|
||||
},
|
||||
"Microsoft.Extensions.Features": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.2",
|
||||
"contentHash": "X7tm2aV2w3lN9roSSGhl19lz4w76HvdiuKNhIv2XOiorYII9XCm66o/z9IJ0+QwkgvEv5gMZDM6rV6uwABHEQQ=="
|
||||
},
|
||||
"Microsoft.Extensions.FileProviders.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "nCBmCx0Xemlu65ZiWMcXbvfvtznKxf4/YYKF9R28QkqdI9lTikedGqzJ28/xmdGGsxUnsP5/3TQGpiPwVjK0dA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Primitives": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.FileProviders.Physical": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "dMu5kUPSfol1Rqhmr6nWPSmbFjDe9w6bkoKithG17bWTZA0UyKirTatM5mqYUN3mGpNA0MorlusIoVTh6J7o5g==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.FileSystemGlobbing": "10.0.5",
|
||||
"Microsoft.Extensions.Primitives": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.FileSystemGlobbing": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "mOE3ARusNQR0a5x8YOcnUbfyyXGqoAWQtEc7qFOfNJgruDWQLo39Re+3/Lzj5pLPFuFYj8hN4dgKzaSQDKiOCw=="
|
||||
},
|
||||
"Microsoft.Extensions.Hosting": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "8i7e5IBdiKLNqt/+ciWrS8U95Rv5DClaaj7ulkZbimnCi4uREWd+lXzkp3joofFuIPOlAzV4AckxLTIELv2jdg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Binder": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.CommandLine": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.EnvironmentVariables": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.FileExtensions": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Json": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.UserSecrets": "10.0.5",
|
||||
"Microsoft.Extensions.DependencyInjection": "10.0.5",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Diagnostics": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Physical": "10.0.5",
|
||||
"Microsoft.Extensions.Hosting.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Console": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Debug": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.EventLog": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.EventSource": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Hosting.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "+Wb7KAMVZTomwJkQrjuPTe5KBzGod7N8XeG+ScxRlkPOB4sZLG4ccVwjV4Phk5BCJt7uIMnGHVoN6ZMVploX+g==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.FileProviders.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Http": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.2",
|
||||
"contentHash": "egUPC0xydb1ugCMcRyJ6zaOGOzx7N4coOVlGeLcIsXhUf1xHHwZeX+ob7JuG0dXExFduHYE/t+4/4y8BLlBKmw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.Diagnostics": "10.0.2",
|
||||
"Microsoft.Extensions.Logging": "10.0.2",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.Options": "10.0.2"
|
||||
}
|
||||
"contentHash": "3qMK1D40D10kb5TdBtFJpzz6/WH0NinWs68ZZS8jCFgHMXDiOjGiPOneMmIocCP/wnUUW4Hzf8lMsIE1xIGxDA=="
|
||||
},
|
||||
"Microsoft.Extensions.Http.Diagnostics": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "I0FBgF6yZRwYH9E3KQ2vHm80YZ7YBj+52GDsmOWXPBv/p15b/wUoNupV9kw3LnSNVsWMqlGbiuZgBnHpMwPh+Q==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Http": "10.0.2",
|
||||
"Microsoft.Extensions.Telemetry": "10.2.0"
|
||||
}
|
||||
},
|
||||
@@ -359,128 +143,15 @@
|
||||
"contentHash": "Lg+OjBW+ODDbM4Ax4LoERvQ1dqSZ8I2gQc2+B0/WOWl2+PunLJ3xb3x8MtHGfcb/Mp98RoMpwRKm6Aj9mzXwrA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Http.Diagnostics": "10.2.0",
|
||||
"Microsoft.Extensions.ObjectPool": "10.0.2",
|
||||
"Microsoft.Extensions.Resilience": "10.2.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "+XTMKQyDWg4ODoNHU/BN3BaI1jhGO7VCS+BnzT/4IauiG6y2iPAte7MyD7rHKS+hNP0TkFkjrae8DFjDUxtcxg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "9HOdqlDtPptVcmKAjsQ/Nr5Rxfq6FMYLdhvZh1lVmeKR738qeYecQD7+ldooXf+u2KzzR1kafSphWngIM3C6ug==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Configuration": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "cSgxsDgfP0+gmVRPVoNHI/KIDavIZxh+CxE6tSLPlYTogqccDnjBFI9CgEsiNuMP6+fiuXUwhhlTz36uUEpwbQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Binder": "10.0.5",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5",
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Console": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "PMs2gha2v24hvH5o5KQem5aNK4mN0BhhCWlMqsg9tzifWKzjeQi2tyPOP/RaWMVvalOhVLcrmoMYPqbnia/epg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Configuration": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging.Debug": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "/VacEkBQ02A8PBXSa6YpbIXCuisYy6JJr62/+ANJDZE+RMBfZMcXJXLfr/LpyLE6pgdp17Wxlt7e7R9zvkwZ3Q==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging.EventLog": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "0ezhWYJS4/6KrqQel9JL+Tr4n+4EX2TF5EYiaysBWNNEM2c3Gtj1moD39esfgk8OHblSX+UFjtZ3z0c4i9tRvw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5",
|
||||
"System.Diagnostics.EventLog": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Logging.EventSource": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "vN+aq1hBFXyYvY5Ow9WyeR66drKQxRZmas4lAjh6QWfryPkjTn1uLtX5AFIxyDaZj78v5TG2sELUyvrXpAPQQw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Logging": "10.0.5",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5",
|
||||
"Microsoft.Extensions.Primitives": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.ObjectPool": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.2",
|
||||
"contentHash": "kpCp4m7nwJVBcRKWXYHdVK/W0dkKyyFOjCmKVdO+zKThWvUxP1V+jVEP9FGpqRu4GPl9041SEXu2f+U/l825nQ=="
|
||||
},
|
||||
"Microsoft.Extensions.Options": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "MDaQMdUplw0AIRhWWmbLA7yQEXaLIHb+9CTroTiNS8OlI0LMXS4LCxtopqauiqGCWlRgJ+xyraVD8t6veRAFbw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Primitives": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "BB9uUW3+6Rxu1R97OB1H/13lUF8P2+H1+eDhpZlK30kDh/6E4EKHBUqTp+ilXQmZLzsRErxON8aBSR6WpUKJdg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Configuration.Binder": "10.0.5",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.5",
|
||||
"Microsoft.Extensions.Options": "10.0.5",
|
||||
"Microsoft.Extensions.Primitives": "10.0.5"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.Primitives": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "/HUHJ0tw/LQvD0DZrz50eQy/3z7PfX7WWEaXnjKTV9/TNdcgFlNTZGo49QhS7PTmhDqMyHRMqAXSBxLh0vso4g=="
|
||||
},
|
||||
"Microsoft.Extensions.Resilience": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "v4WOdAOFxB3AcsUkZWNcHL3mYzs4KAPtHO8rkoQlFKOBoD3KyjjAL+h3tRwSK5i4UpF/yhxsQRY0JxKj4osxxw==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Diagnostics": "10.0.2",
|
||||
"Microsoft.Extensions.Diagnostics.ExceptionSummarization": "10.2.0",
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": "10.0.2",
|
||||
"Microsoft.Extensions.Telemetry.Abstractions": "10.2.0",
|
||||
"Polly.Extensions": "8.4.2",
|
||||
"Polly.RateLimiting": "8.4.2"
|
||||
@@ -491,23 +162,13 @@
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "AHTPfiKodj66xA8RwRkFD4q11V2AvzcuDsujv6ViPkOPtvBEYcPVplHakK56pPzWlX08MDS+TAQXfFXAeP7J5w==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Http": "10.0.2",
|
||||
"Microsoft.Extensions.ServiceDiscovery.Abstractions": "10.2.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.Extensions.ServiceDiscovery.Abstractions": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "sANlOvfqfw/yfych4CLlHSKSWzIie6mQG7w83gVur1foNOafyHxcgpoQMvBf+KiB4Tpls6P1/Z77IIQSK8hxFg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.Configuration.Binder": "10.0.2",
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.Features": "10.0.2",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.Options": "10.0.2",
|
||||
"Microsoft.Extensions.Primitives": "10.0.2"
|
||||
}
|
||||
"contentHash": "sANlOvfqfw/yfych4CLlHSKSWzIie6mQG7w83gVur1foNOafyHxcgpoQMvBf+KiB4Tpls6P1/Z77IIQSK8hxFg=="
|
||||
},
|
||||
"Microsoft.Extensions.Telemetry": {
|
||||
"type": "Transitive",
|
||||
@@ -516,8 +177,6 @@
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.AmbientMetadata.Application": "10.2.0",
|
||||
"Microsoft.Extensions.DependencyInjection.AutoActivation": "10.2.0",
|
||||
"Microsoft.Extensions.Logging.Configuration": "10.0.2",
|
||||
"Microsoft.Extensions.ObjectPool": "10.0.2",
|
||||
"Microsoft.Extensions.Telemetry.Abstractions": "10.2.0"
|
||||
}
|
||||
},
|
||||
@@ -526,10 +185,7 @@
|
||||
"resolved": "10.2.0",
|
||||
"contentHash": "6V4V6NX6RLUYWwV89DeW/4zK5xOycYHWhsfMXSpKVGgMHfXcczmbk6hBeqTnRPzhpATYcOWlmA6hk1jgdxUugA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Compliance.Abstractions": "10.2.0",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.2",
|
||||
"Microsoft.Extensions.ObjectPool": "10.0.2",
|
||||
"Microsoft.Extensions.Options": "10.0.2"
|
||||
"Microsoft.Extensions.Compliance.Abstractions": "10.2.0"
|
||||
}
|
||||
},
|
||||
"Microsoft.TestPlatform.ObjectModel": {
|
||||
@@ -546,6 +202,36 @@
|
||||
"Newtonsoft.Json": "13.0.3"
|
||||
}
|
||||
},
|
||||
"NetCord": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.0.0-alpha.489",
|
||||
"contentHash": "/rM73l1pwwJCWHi7YrIiSVc+GVL0lV+k+amqNJUMINjLO+c5bKWj9PoNNoMhiPZoaORO4k6Uxp8EQfoQj3AYtA=="
|
||||
},
|
||||
"NetCord.Hosting": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.0.0-alpha.489",
|
||||
"contentHash": "yQcvgY3uu98ndoLXpiFhJ5kungoWVLd7xnO18GmukRPVsRzyOKgxe/Ycp8DLYTtiQG9Wyg1pV4Iv6rvo+zck4w==",
|
||||
"dependencies": {
|
||||
"NetCord": "1.0.0-alpha.489"
|
||||
}
|
||||
},
|
||||
"NetCord.Hosting.Services": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.0.0-alpha.489",
|
||||
"contentHash": "Md46+zLB9UWYLM7PVlATytkjAC9602wBNKO7m5eaBiDdEvZOPsUrR6NJJr2YtJoKjttbvhte5ayDXj8WGGsevQ==",
|
||||
"dependencies": {
|
||||
"NetCord.Hosting": "1.0.0-alpha.489",
|
||||
"NetCord.Services": "1.0.0-alpha.489"
|
||||
}
|
||||
},
|
||||
"NetCord.Services": {
|
||||
"type": "Transitive",
|
||||
"resolved": "1.0.0-alpha.489",
|
||||
"contentHash": "SwG/7Khba1uRENDvG22RV/POByIwh/ZrenMrSzwoEcEYPMI5TabmEEB3ySH15XGdLcFZJEj106AlriN0kZhfFg==",
|
||||
"dependencies": {
|
||||
"NetCord": "1.0.0-alpha.489"
|
||||
}
|
||||
},
|
||||
"Newtonsoft.Json": {
|
||||
"type": "Transitive",
|
||||
"resolved": "13.0.3",
|
||||
@@ -554,17 +240,13 @@
|
||||
"Npgsql": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.2",
|
||||
"contentHash": "q5RfBI+wywJSFUNDE1L4ZbHEHCFTblo8Uf6A6oe4feOUFYiUQXyAf9GBh5qEZpvJaHiEbpBPkQumjEhXCJxdrg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.0"
|
||||
}
|
||||
"contentHash": "q5RfBI+wywJSFUNDE1L4ZbHEHCFTblo8Uf6A6oe4feOUFYiUQXyAf9GBh5qEZpvJaHiEbpBPkQumjEhXCJxdrg=="
|
||||
},
|
||||
"Npgsql.DependencyInjection": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.1",
|
||||
"contentHash": "YHFa4vD27sNIfv6s5q8Zi1fLvKfmK1xcpMv0PUvXOxDFbRmuMRSHwpZTbPvsAlj97q1/o7DfyynLqfqrCm1VnA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.0",
|
||||
"Npgsql": "10.0.1"
|
||||
}
|
||||
},
|
||||
@@ -582,8 +264,6 @@
|
||||
"resolved": "1.15.3",
|
||||
"contentHash": "N0i6WjPoHPbZyms1ugbDIFAJFuGlpeExJMU/+XSL0lQRUkg/D0utFkDoLXf8Z1km5B+xVZ2GyMXXiX8qdeNmPg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Diagnostics.Abstractions": "10.0.0",
|
||||
"Microsoft.Extensions.Logging.Configuration": "10.0.0",
|
||||
"OpenTelemetry.Api.ProviderBuilderExtensions": "1.15.3"
|
||||
}
|
||||
},
|
||||
@@ -597,7 +277,6 @@
|
||||
"resolved": "1.15.3",
|
||||
"contentHash": "SYn0lqYDwLMWhv/zlNGsQcl2yX++yTumanX46bmOZE/ZDOd1WjPBO2kZaZgKLEZTZk48pavIFGJ6vOvxXgWVFQ==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0",
|
||||
"OpenTelemetry.Api": "1.15.3"
|
||||
}
|
||||
},
|
||||
@@ -614,7 +293,6 @@
|
||||
"resolved": "1.15.3",
|
||||
"contentHash": "u8n/W8yIlqv0BXZmvId1iVaeWXG42tGKdTkuLYg5g57Y/r9CeUNzqtrSHNdG5IoO8iPX79w3v+WsbAHgUQbfeg==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Hosting.Abstractions": "10.0.0",
|
||||
"OpenTelemetry": "1.15.3"
|
||||
}
|
||||
},
|
||||
@@ -631,8 +309,6 @@
|
||||
"resolved": "1.15.1",
|
||||
"contentHash": "vFO4Fj/dXkoVNGo/nhoGpO2zYQmZwr4jTID7oRGo+XlQ8LqksyZjUXQ4p39RfUvTID7IzzL8Qe71tW7CcAFymA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Configuration": "10.0.0",
|
||||
"Microsoft.Extensions.Options": "10.0.0",
|
||||
"OpenTelemetry.Api.ProviderBuilderExtensions": "[1.15.3, 2.0.0)"
|
||||
}
|
||||
},
|
||||
@@ -654,8 +330,6 @@
|
||||
"resolved": "8.4.2",
|
||||
"contentHash": "GZ9vRVmR0jV2JtZavt+pGUsQ1O1cuRKG7R7VOZI6ZDy9y6RNPvRvXK1tuS4ffUrv8L0FTea59oEuQzgS0R7zSA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Logging.Abstractions": "8.0.0",
|
||||
"Microsoft.Extensions.Options": "8.0.0",
|
||||
"Polly.Core": "8.4.2"
|
||||
}
|
||||
},
|
||||
@@ -664,27 +338,13 @@
|
||||
"resolved": "8.4.2",
|
||||
"contentHash": "ehTImQ/eUyO07VYW2WvwSmU9rRH200SKJ/3jku9rOkyWE0A2JxNFmAVms8dSn49QLSjmjFRRSgfNyOgr/2PSmA==",
|
||||
"dependencies": {
|
||||
"Polly.Core": "8.4.2",
|
||||
"System.Threading.RateLimiting": "8.0.0"
|
||||
"Polly.Core": "8.4.2"
|
||||
}
|
||||
},
|
||||
"System.Diagnostics.EventLog": {
|
||||
"type": "Transitive",
|
||||
"resolved": "10.0.5",
|
||||
"contentHash": "wugvy+pBVzjQEnRs9wMTWwoaeNFX3hsaHeVHFDIvJSWXp7wfmNWu3mxAwBIE6pyW+g6+rHa1Of5fTzb0QVqUTA=="
|
||||
},
|
||||
"System.Threading.RateLimiting": {
|
||||
"type": "Transitive",
|
||||
"resolved": "8.0.0",
|
||||
"contentHash": "7mu9v0QDv66ar3DpGSZHg9NuNcxDaaAcnMULuZlaTpP9+hwXhrxNGsF5GmLkSHxFdb5bBc1TzeujsRgTrPWi+Q=="
|
||||
},
|
||||
"Telegram.Bot": {
|
||||
"type": "Transitive",
|
||||
"resolved": "22.9.6.1",
|
||||
"contentHash": "I0eaMaETcWIhMn4uu4RGd9e6PLJOjaOG3QAcKPsTcS80H3TF6gqj3UF9NKu4ZY90ul6Y6NiWToHkg/PsvxkotA==",
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Options.ConfigurationExtensions": "8.0.0"
|
||||
}
|
||||
"contentHash": "I0eaMaETcWIhMn4uu4RGd9e6PLJOjaOG3QAcKPsTcS80H3TF6gqj3UF9NKu4ZY90ul6Y6NiWToHkg/PsvxkotA=="
|
||||
},
|
||||
"xunit.abstractions": {
|
||||
"type": "Transitive",
|
||||
@@ -732,14 +392,26 @@
|
||||
"Aspire.Npgsql": "[13.2.2, )",
|
||||
"Dapper": "[2.1.72, )",
|
||||
"Dapper.AOT": "[1.0.48, )",
|
||||
"GmRelay.ServiceDefaults": "[1.15.0, )",
|
||||
"GmRelay.Shared": "[1.15.0, )",
|
||||
"Microsoft.Extensions.Hosting": "[10.0.5, )",
|
||||
"GmRelay.ServiceDefaults": "[2.3.0, )",
|
||||
"GmRelay.Shared": "[2.3.0, )",
|
||||
"Npgsql": "[10.0.2, )",
|
||||
"Telegram.Bot": "[22.9.5.3, )",
|
||||
"dbup-postgresql": "[7.0.1, )"
|
||||
}
|
||||
},
|
||||
"gmrelay.discordbot": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Aspire.Npgsql": "[13.2.2, )",
|
||||
"Dapper": "[2.1.72, )",
|
||||
"GmRelay.ServiceDefaults": "[2.3.0, )",
|
||||
"GmRelay.Shared": "[2.3.0, )",
|
||||
"NetCord.Hosting": "[1.0.0-alpha.489, )",
|
||||
"NetCord.Hosting.Services": "[1.0.0-alpha.489, )",
|
||||
"NetCord.Services": "[1.0.0-alpha.489, )",
|
||||
"Npgsql": "[10.0.2, )"
|
||||
}
|
||||
},
|
||||
"gmrelay.servicedefaults": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
@@ -760,8 +432,8 @@
|
||||
"dependencies": {
|
||||
"Aspire.Npgsql": "[13.2.2, )",
|
||||
"Dapper": "[2.1.72, )",
|
||||
"GmRelay.ServiceDefaults": "[1.15.0, )",
|
||||
"GmRelay.Shared": "[1.15.0, )",
|
||||
"GmRelay.ServiceDefaults": "[2.3.0, )",
|
||||
"GmRelay.Shared": "[2.3.0, )",
|
||||
"Npgsql": "[10.0.2, )",
|
||||
"Telegram.Bot": "[22.9.6.1, )"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user