UI 복잡 버전 234 RED→GREEN 완료(docs/UI_USECASES.md §A~§J): 라이브 테마 전환(DynamicResource 전환+ThemeResolver+HighContrast 테마, 재시작 없음), 디자인 토큰 체계·WCAG 대비 결함 5건 수정, 설정창 카테고리 내비/검색 재구성+AppConfig 40여 속성, 다운로드 관리자(속도/ETA/세그먼트맵/전체 일시정지-이어받기/CSV 내보내기/예약 게이트/중복 확인), 라이브러리·아카이브·작업공간·재생목록·즐겨찾기 편집 뷰, 접근성(자동화 속성 30여 개·커스텀 피어·docs/ACCESSIBILITY.md), 인터랙션(휠 클릭 새 탭·XButton 탐색·F12·영역 캡처·프로필 전환), 상태/알림(토스트·알림센터·온보딩·CrashReportDialog). 보강 테스트 35건+실창 E2E 4건(StaDispatcher 기반 — 프록시 설정이 기시작 핸들러를 건드리는 크래시 실결함 수정 포함) — 453/453 GREEN. 이전 미커밋 작업(CI 워크플로·Mdns·QueueHub·UpdateChecker·AGENTS/CLAUDE·빌드 스크립트) 일괄 포함

This commit is contained in:
Yun Chan 2026-08-17 15:54:53 +09:00
parent 5a0ce730b2
commit 17f2f91152
88 changed files with 9463 additions and 1127 deletions

View file

@ -0,0 +1,58 @@
using Makaretu.Dns;
namespace VideoDownloader.Server;
/// <summary>
/// mDNS 서비스 광고(<c>_videodl._tcp</c>) — MOBILE_PLAN §3 아키텍처.
/// QR 페어링이 주 경로이고 광고는 발견 보조이므로, 멀티캐스트가 막힌 네트워크에서의
/// 실패는 서버 기동을 막지 않는다(ServerHost 가 MdnsError 로 드러냄).
/// </summary>
public sealed class MdnsAdvertiser : IDisposable
{
public const string ServiceType = "_videodl._tcp";
private readonly ServiceProfile _profile;
private ServiceDiscovery? _sd;
public MdnsAdvertiser(string deviceName, int port) => _profile = BuildProfile(deviceName, (ushort)port);
/// <summary>
/// 광고 프로필 구성(순수 로직). 점은 DNS 라벨 구분자와 충돌하므로 대시로 정리.
/// Makaretu WireWriter 가 TXT/라벨에 ASCII 만 허용 → 기기명은 퍼센트 인코딩으로 무손실 보존,
/// 인스턴스 라벨은 ASCII 로 접는다(클라이언트는 TXT device 를 디코드해 표시).
/// </summary>
public static ServiceProfile BuildProfile(string deviceName, ushort port)
{
var display = string.IsNullOrWhiteSpace(deviceName) ? "VideoDownloader" : deviceName.Trim();
var profile = new ServiceProfile(ToAsciiLabel(display), ServiceType, port);
profile.AddProperty("device", Uri.EscapeDataString(display));
return profile;
}
private static string ToAsciiLabel(string s)
{
var label = new string(s.Replace('.', '-').Where(c => c >= ' ' && c < (char)0x7f).ToArray()).Trim();
return label.Length == 0 ? "VideoDownloader" : label;
}
/// <summary>광고 시작. 멀티캐스트 소켓 실패는 그대로 던진다(호출측이 보조 기능으로 취급).</summary>
public void Start()
{
_sd ??= new ServiceDiscovery();
_sd.Advertise(_profile);
}
public void Dispose()
{
if (_sd == null) return;
try
{
_sd.Unadvertise(); // goodbye 패킷은 규격상 best-effort — 네트워크가 이미 죽었으면 보낼 수 없다
}
catch (Exception ex) when (ex is System.Net.Sockets.SocketException or ObjectDisposedException)
{
}
_sd.Dispose();
_sd = null;
}
}

View file

@ -0,0 +1,17 @@
using Microsoft.AspNetCore.SignalR;
namespace VideoDownloader.Server;
/// <summary>
/// 실시간 큐 허브(MOBILE_PLAN §3 <c>/hubs/queue</c>).
/// 클라이언트는 접속 직후 GetQueue 로 스냅샷을 받고, 이후 서버발 queueUpdated 푸시로 갱신한다
/// (2초 폴링의 실시간 대체 — 폴링 클라이언트와 공존).
/// </summary>
public sealed class QueueHub : Hub
{
private readonly IQueueAdapter _queue;
public QueueHub(IQueueAdapter queue) => _queue = queue;
public Task<IReadOnlyList<QueueItemDto>> GetQueue() => _queue.GetItemsAsync();
}

View file

@ -2,6 +2,7 @@ using System.Linq;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
@ -18,17 +19,27 @@ public sealed class ServerHost : IAsyncDisposable
private readonly WebApplication _app;
private readonly string _token;
private readonly ServerOptions _options;
private readonly Action? _unsubscribeQueueChanged;
private readonly MdnsAdvertiser? _mdns;
public int Port { get; }
/// <summary>QR 에 담을 페어링 URL 형식: http://&lt;lan-ip&gt;:&lt;port&gt;/#t=&lt;token&gt;</summary>
public string Token => _token;
/// <summary>mDNS 광고(_videodl._tcp) 동작 여부. EnableMdns=true 인데 false 면 MdnsError 를 본다.</summary>
public bool MdnsActive => _mdns != null;
/// <summary>mDNS 시작 실패 원인(발견 보조 기능이라 서버 기동은 막지 않고 여기로 드러냄).</summary>
public Exception? MdnsError { get; }
private ServerHost(WebApplication app, int port, string token, ServerOptions options)
private ServerHost(WebApplication app, int port, string token, ServerOptions options,
Action? unsubscribeQueueChanged, MdnsAdvertiser? mdns, Exception? mdnsError)
{
_app = app;
Port = port;
_token = token;
_options = options;
_unsubscribeQueueChanged = unsubscribeQueueChanged;
_mdns = mdns;
MdnsError = mdnsError;
}
public static async Task<ServerHost> StartAsync(ServerOptions options)
@ -40,19 +51,25 @@ public sealed class ServerHost : IAsyncDisposable
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = new[] { "--urls", $"http://0.0.0.0:{(options.Port == 0 ? GetFreePort() : options.Port)}" } });
foreach (var prov in builder.Services.Where(sd => sd.ServiceType.FullName!.Contains("LoggerProvider")).ToList())
builder.Services.Remove(prov);
builder.Services.AddSingleton<IQueueAdapter>(options.Queue);
builder.Services.AddSignalR();
var app = builder.Build();
app.UseWebSockets(); // SignalR 웹소켓 전송용 (없으면 롱폴링만 됨)
// Bearer 토큰 인증(상수시간 비교) — / 와 /api/* 전체 적용
app.Use(async (ctx, next) =>
{
if (!ctx.Request.Path.StartsWithSegments("/api/pair") &&
(ctx.Request.Path.StartsWithSegments("/api") || ctx.Request.Path.StartsWithSegments("/stream") || ctx.Request.Path.StartsWithSegments("/file")))
(ctx.Request.Path.StartsWithSegments("/api") || ctx.Request.Path.StartsWithSegments("/stream") ||
ctx.Request.Path.StartsWithSegments("/file") || ctx.Request.Path.StartsWithSegments("/hubs")))
{
var auth = ctx.Request.Headers.Authorization.ToString();
var provided = auth.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) ? auth[7..].Trim() : "";
// <video>/<a> 태그는 헤더를 못 실음 → 쿼리 토큰도 허용(LAN 한정)
if (provided.Length == 0 && ctx.Request.Query.TryGetValue("t", out var q)) provided = q.ToString();
// SignalR 클라이언트 관례(AccessTokenProvider)는 access_token 쿼리로 실어 보냄
if (provided.Length == 0 && ctx.Request.Query.TryGetValue("access_token", out var at)) provided = at.ToString();
if (!FixedTimeEquals(provided, token))
{
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
@ -146,6 +163,12 @@ public sealed class ServerHost : IAsyncDisposable
return Results.Ok();
});
// ── 실시간 큐 허브 (MOBILE_PLAN §3 /hubs/queue) ──
app.MapHub<QueueHub>("/hubs/queue");
var hubContext = app.Services.GetRequiredService<Microsoft.AspNetCore.SignalR.IHubContext<QueueHub>>();
Action onQueueChanged = () => _ = BroadcastQueueAsync(hubContext, queue);
queue.Changed += onQueueChanged;
// ── 웹 컴패니언 (제로 설치 클라이언트) ──
app.MapGet("/", () => Results.Text(WebCompanion.Html, "text/html; charset=utf-8"));
@ -157,11 +180,46 @@ public sealed class ServerHost : IAsyncDisposable
.Select(m2 => int.Parse(m2.Groups[1].Value)).FirstOrDefault();
actualPort = m;
}
return new ServerHost(app, actualPort, token, options);
// ── mDNS 광고 (_videodl._tcp) — 발견 보조. 실패는 MdnsError 로 드러내되 서버는 유지 ──
MdnsAdvertiser? mdns = null;
Exception? mdnsError = null;
if (options.EnableMdns)
{
try
{
mdns = new MdnsAdvertiser(options.DeviceName, actualPort);
mdns.Start();
}
catch (Exception ex)
{
mdnsError = ex;
mdns?.Dispose();
mdns = null;
}
}
return new ServerHost(app, actualPort, token, options, () => queue.Changed -= onQueueChanged, mdns, mdnsError);
}
/// <summary>큐 변경 → 전 클라이언트 푸시. 종료 경합만 무시(그 외 실패는 UnobservedTaskException 로 관찰됨).</summary>
private static async Task BroadcastQueueAsync(Microsoft.AspNetCore.SignalR.IHubContext<QueueHub> hub, IQueueAdapter queue)
{
try
{
var items = await queue.GetItemsAsync();
await hub.Clients.All.SendAsync("queueUpdated", items);
}
catch (ObjectDisposedException)
{
// 서버 종료와 경합한 마지막 푸시 — 클라이언트는 재접속/스냅샷으로 보정
}
}
public async ValueTask DisposeAsync()
{
_unsubscribeQueueChanged?.Invoke();
_mdns?.Dispose();
await _app.StopAsync();
await _app.DisposeAsync();
}

View file

@ -24,6 +24,8 @@ public sealed class ServerOptions
public string DeviceName { get; init; } = Environment.MachineName;
/// <summary>썸네일/해상도 생성기(기본: DesktopProcessRunner 기반 ffmpeg). 테스트 주입 가능.</summary>
public Thumbnailer? Thumbnailer { get; init; }
/// <summary>mDNS 광고(_videodl._tcp) 켜기 — MOBILE_PLAN §3. 실패해도 서버는 뜬다(MdnsError 로 노출).</summary>
public bool EnableMdns { get; init; }
/// <summary>ffmpeg 경로 오버라이드(기본: 설정→PATH 탐색). 호스트 ffmpeg 없는 환경 테스트용.</summary>
public string? FfmpegPath { get; init; }
}

View file

@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Makaretu.Dns.Multicast" Version="0.27.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\VideoDownloader.Core\VideoDownloader.Core.csproj" />