feat(ads/seo/release): v1.2.0 with live Google Ads, isolated ad profile, ads.txt, and SEO/AEO/GEO optimization
This commit is contained in:
parent
a88aafa1e5
commit
0e568f1f0a
975 changed files with 130593 additions and 16783 deletions
58
tests/Paca.Tests/Server/ServerLanBeaconGateTests.cs
Normal file
58
tests/Paca.Tests/Server/ServerLanBeaconGateTests.cs
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
using System.Net.Sockets;
|
||||
using System.Threading.Tasks;
|
||||
using Paca.Core.Config;
|
||||
using Paca.Mobile.Core;
|
||||
using Paca.Server;
|
||||
using Xunit;
|
||||
|
||||
namespace Paca.Tests.Server;
|
||||
|
||||
public class ServerLanBeaconGateTests
|
||||
{
|
||||
[Fact]
|
||||
public void Gate238_AppConfig_RemoteAccessPort_Default_52100_Audit()
|
||||
{
|
||||
var config = new AppConfig();
|
||||
Assert.Equal(52100, config.RemoteAccessPort);
|
||||
|
||||
var opts = new ServerOptions();
|
||||
Assert.True(opts.EnableLanBeacon);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Gate237_ServerHost_Starts_And_Stops_LanBeaconResponder_Correctly()
|
||||
{
|
||||
// 고유 UDP 포트를 사용하여 병렬 테스트 충돌 방지
|
||||
int testUdpPort = 52199;
|
||||
var options = new ServerOptions
|
||||
{
|
||||
Port = 0,
|
||||
Token = "test_token_1234",
|
||||
EnableLanBeacon = true,
|
||||
BeaconPort = testUdpPort,
|
||||
DeviceName = "TestHostPC"
|
||||
};
|
||||
|
||||
await using var host = await ServerHost.StartAsync(options);
|
||||
Assert.True(host.LanBeaconActive);
|
||||
|
||||
// UdpClient로 Ping을 보내고 Pong 응답 확인
|
||||
using var client = new UdpClient();
|
||||
var ping = LanDiscoveryMessage.CreatePing("TestMobileClient");
|
||||
var pingBytes = System.Text.Encoding.UTF8.GetBytes(ping.ToPayload());
|
||||
await client.SendAsync(pingBytes, pingBytes.Length, "127.0.0.1", testUdpPort);
|
||||
|
||||
var receiveTask = client.ReceiveAsync();
|
||||
var completed = await Task.WhenAny(receiveTask, Task.Delay(2000));
|
||||
Assert.Same(receiveTask, completed);
|
||||
|
||||
var response = await receiveTask;
|
||||
var responseText = System.Text.Encoding.UTF8.GetString(response.Buffer);
|
||||
var parsed = LanDiscoveryMessage.Parse(responseText);
|
||||
|
||||
Assert.NotNull(parsed);
|
||||
Assert.Equal(LanDiscoveryMessageType.Pong, parsed.Type);
|
||||
Assert.Equal("TestHostPC", parsed.DeviceName);
|
||||
Assert.EndsWith($":{host.Port}", parsed.Endpoint);
|
||||
}
|
||||
}
|
||||
183
tests/Paca.Tests/Server/ServerPasskeyAuthTests.cs
Normal file
183
tests/Paca.Tests/Server/ServerPasskeyAuthTests.cs
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
using Paca.Core.Security;
|
||||
using Paca.Server;
|
||||
using Xunit;
|
||||
|
||||
namespace Paca.Tests.Server;
|
||||
|
||||
public class ServerPasskeyAuthTests : IDisposable
|
||||
{
|
||||
private readonly string _libDir = Path.Combine(Path.GetTempPath(), $"vd_passkey_{Guid.NewGuid():N}");
|
||||
|
||||
public ServerPasskeyAuthTests() => Directory.CreateDirectory(_libDir);
|
||||
|
||||
private sealed class EmptyQueue : IQueueAdapter
|
||||
{
|
||||
public Task<IReadOnlyList<QueueItemDto>> GetItemsAsync() => Task.FromResult<IReadOnlyList<QueueItemDto>>(Array.Empty<QueueItemDto>());
|
||||
public Task<string> AddAsync(string url, string? title) => Task.FromResult(Guid.NewGuid().ToString("N"));
|
||||
public Task PauseAsync(string id) => Task.CompletedTask;
|
||||
public Task ResumeAsync(string id) => Task.CompletedTask;
|
||||
public Task CancelAsync(string id) => Task.CompletedTask;
|
||||
public event Action? Changed { add { } remove { } }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetChallenge_ReturnsNewValidChallenge()
|
||||
{
|
||||
await using var server = await ServerHost.StartAsync(new ServerOptions
|
||||
{
|
||||
Port = 0,
|
||||
Token = "secret-passkey-token",
|
||||
LibraryFolder = _libDir,
|
||||
Queue = new EmptyQueue()
|
||||
});
|
||||
|
||||
using var client = new HttpClient();
|
||||
var resp = await client.GetAsync($"http://127.0.0.1:{server.Port}/api/auth/passkey/challenge");
|
||||
Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
|
||||
|
||||
var doc = await resp.Content.ReadFromJsonAsync<JsonElement>();
|
||||
Assert.True(doc.GetProperty("ok").GetBoolean());
|
||||
var challenge = doc.GetProperty("challenge").GetString();
|
||||
Assert.False(string.IsNullOrEmpty(challenge));
|
||||
Assert.True(doc.TryGetProperty("rpId", out var rpId));
|
||||
Assert.Equal("paca.local", rpId.GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_WithValidFido2Assertion_ReturnsSessionToken()
|
||||
{
|
||||
await using var server = await ServerHost.StartAsync(new ServerOptions
|
||||
{
|
||||
Port = 0,
|
||||
Token = "secret-passkey-token-2",
|
||||
DeviceName = "MyTestPc",
|
||||
LibraryFolder = _libDir,
|
||||
Queue = new EmptyQueue()
|
||||
});
|
||||
|
||||
using var client = new HttpClient();
|
||||
|
||||
// 1. 챌린지 요청
|
||||
var chalResp = await client.GetAsync($"http://127.0.0.1:{server.Port}/api/auth/passkey/challenge");
|
||||
var chalDoc = await chalResp.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var challenge = chalDoc.GetProperty("challenge").GetString()!;
|
||||
|
||||
// 2. 가상 FIDO2 자격증명 생성 및 어설션 서명
|
||||
var authenticator = VirtualFido2Authenticator.Default;
|
||||
var cred = authenticator.CreateCredential("paca.local", "user-1", "test-user");
|
||||
var clientDataHash = SHA256.HashData(Encoding.UTF8.GetBytes(challenge));
|
||||
var assertion = authenticator.SignChallenge(cred.CredentialId, clientDataHash);
|
||||
|
||||
// 3. Verify 요청
|
||||
var verifyReq = new
|
||||
{
|
||||
challenge = challenge,
|
||||
credentialId = cred.CredentialId,
|
||||
clientDataHash = WebEncoders.Base64UrlEncode(clientDataHash),
|
||||
authenticatorData = WebEncoders.Base64UrlEncode(assertion.AuthenticatorData),
|
||||
signature = WebEncoders.Base64UrlEncode(assertion.Signature)
|
||||
};
|
||||
|
||||
var verifyResp = await client.PostAsJsonAsync($"http://127.0.0.1:{server.Port}/api/auth/passkey/verify", verifyReq);
|
||||
Assert.Equal(HttpStatusCode.OK, verifyResp.StatusCode);
|
||||
|
||||
var verifyDoc = await verifyResp.Content.ReadFromJsonAsync<JsonElement>();
|
||||
Assert.True(verifyDoc.GetProperty("ok").GetBoolean());
|
||||
Assert.Equal("secret-passkey-token-2", verifyDoc.GetProperty("token").GetString());
|
||||
Assert.Equal("MyTestPc", verifyDoc.GetProperty("device").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_WithInvalidSignature_Returns401()
|
||||
{
|
||||
await using var server = await ServerHost.StartAsync(new ServerOptions
|
||||
{
|
||||
Port = 0,
|
||||
Token = "secret-passkey-token-3",
|
||||
LibraryFolder = _libDir,
|
||||
Queue = new EmptyQueue()
|
||||
});
|
||||
|
||||
using var client = new HttpClient();
|
||||
|
||||
var chalResp = await client.GetAsync($"http://127.0.0.1:{server.Port}/api/auth/passkey/challenge");
|
||||
var chalDoc = await chalResp.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var challenge = chalDoc.GetProperty("challenge").GetString()!;
|
||||
|
||||
var authenticator = VirtualFido2Authenticator.Default;
|
||||
var cred = authenticator.CreateCredential("paca.local", "user-2", "test-user-2");
|
||||
var clientDataHash = SHA256.HashData(Encoding.UTF8.GetBytes(challenge));
|
||||
var assertion = authenticator.SignChallenge(cred.CredentialId, clientDataHash);
|
||||
|
||||
// 위조 서명
|
||||
var tamperedSignature = (byte[])assertion.Signature.Clone();
|
||||
tamperedSignature[0] ^= 0xFF;
|
||||
|
||||
var verifyReq = new
|
||||
{
|
||||
challenge = challenge,
|
||||
credentialId = cred.CredentialId,
|
||||
clientDataHash = WebEncoders.Base64UrlEncode(clientDataHash),
|
||||
authenticatorData = WebEncoders.Base64UrlEncode(assertion.AuthenticatorData),
|
||||
signature = WebEncoders.Base64UrlEncode(tamperedSignature)
|
||||
};
|
||||
|
||||
var verifyResp = await client.PostAsJsonAsync($"http://127.0.0.1:{server.Port}/api/auth/passkey/verify", verifyReq);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, verifyResp.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Verify_ReplayAttack_Returns401()
|
||||
{
|
||||
await using var server = await ServerHost.StartAsync(new ServerOptions
|
||||
{
|
||||
Port = 0,
|
||||
Token = "secret-passkey-token-4",
|
||||
LibraryFolder = _libDir,
|
||||
Queue = new EmptyQueue()
|
||||
});
|
||||
|
||||
using var client = new HttpClient();
|
||||
|
||||
var chalResp = await client.GetAsync($"http://127.0.0.1:{server.Port}/api/auth/passkey/challenge");
|
||||
var chalDoc = await chalResp.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var challenge = chalDoc.GetProperty("challenge").GetString()!;
|
||||
|
||||
var authenticator = VirtualFido2Authenticator.Default;
|
||||
var cred = authenticator.CreateCredential("paca.local", "user-3", "test-user-3");
|
||||
var clientDataHash = SHA256.HashData(Encoding.UTF8.GetBytes(challenge));
|
||||
var assertion = authenticator.SignChallenge(cred.CredentialId, clientDataHash);
|
||||
|
||||
var verifyReq = new
|
||||
{
|
||||
challenge = challenge,
|
||||
credentialId = cred.CredentialId,
|
||||
clientDataHash = WebEncoders.Base64UrlEncode(clientDataHash),
|
||||
authenticatorData = WebEncoders.Base64UrlEncode(assertion.AuthenticatorData),
|
||||
signature = WebEncoders.Base64UrlEncode(assertion.Signature)
|
||||
};
|
||||
|
||||
// 1차 성공
|
||||
var first = await client.PostAsJsonAsync($"http://127.0.0.1:{server.Port}/api/auth/passkey/verify", verifyReq);
|
||||
Assert.Equal(HttpStatusCode.OK, first.StatusCode);
|
||||
|
||||
// 동일 챌린지 재사용 (Replay 공격) -> 401 거부
|
||||
var second = await client.PostAsJsonAsync($"http://127.0.0.1:{server.Port}/api/auth/passkey/verify", verifyReq);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, second.StatusCode);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Directory.Delete(_libDir, recursive: true); } catch (IOException) { }
|
||||
}
|
||||
}
|
||||
488
tests/Paca.Tests/Server/ServerPipelineTests.cs
Normal file
488
tests/Paca.Tests/Server/ServerPipelineTests.cs
Normal file
|
|
@ -0,0 +1,488 @@
|
|||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using Makaretu.Dns;
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
using Paca.Core.Platform;
|
||||
using Paca.Server;
|
||||
using Xunit;
|
||||
|
||||
namespace Paca.Tests.Server;
|
||||
|
||||
/// <summary>
|
||||
/// 원격 API 서버 & SignalR 큐 & mDNS & 썸네일러 통합 파이프라인.
|
||||
/// </summary>
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// MOBILE_PLAN §3 mDNS 광고(<c>_videodl._tcp</c>) — 서비스 프로필 구성(순수 로직)과 광고 생명주기.
|
||||
/// 멀티캐스트 수신 단정은 네트워크/방화벽에 좌우되므로 두지 않는다(수동 증거로 확인).
|
||||
/// </summary>
|
||||
public class MdnsAdvertiserTests
|
||||
{
|
||||
[Fact]
|
||||
public void 프로필_서비스타입과_포트와_기기명_TXT()
|
||||
{
|
||||
var profile = MdnsAdvertiser.BuildProfile("데스크톱PC", 8642);
|
||||
|
||||
Assert.Equal("_videodl._tcp", profile.ServiceName.ToString());
|
||||
var srv = Assert.Single(profile.Resources.OfType<SRVRecord>());
|
||||
Assert.Equal(8642, srv.Port);
|
||||
// Makaretu 는 TXT 에 ASCII 만 허용 → 한글 기기명은 퍼센트 인코딩으로 무손실 보존
|
||||
var txt = Assert.Single(profile.Resources.OfType<TXTRecord>());
|
||||
Assert.Contains("device=" + Uri.EscapeDataString("데스크톱PC"), txt.Strings);
|
||||
// 인스턴스 라벨은 ASCII 로 접힘(직렬화 가능해야 광고 자체가 나간다)
|
||||
Assert.Equal("PC", profile.InstanceName.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void 프로필_인스턴스명은_점을_대시로_정리()
|
||||
{
|
||||
var profile = MdnsAdvertiser.BuildProfile("my.host.name", 1234);
|
||||
Assert.Equal("my-host-name", profile.InstanceName.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void 프로필_빈_기기명은_기본값()
|
||||
{
|
||||
var profile = MdnsAdvertiser.BuildProfile("", 1234);
|
||||
Assert.Equal("Paca", profile.InstanceName.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void 광고_시작과_중복해제_안전()
|
||||
{
|
||||
using var adv = new MdnsAdvertiser("테스트PC", 8642);
|
||||
adv.Start();
|
||||
adv.Dispose();
|
||||
adv.Dispose(); // 중복 Dispose 안전
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// E2E: SignalR <c>/hubs/queue</c> — MOBILE_PLAN §3 API 설계안의 실시간 큐 푸시.
|
||||
/// 실제 Kestrel 기동 → 허브 접속(쿼리 토큰 인증) → 스냅샷 조회 + 큐 변경 시 서버 푸시 수신.
|
||||
/// </summary>
|
||||
public class QueueHubE2ETests : IDisposable
|
||||
{
|
||||
private readonly string _libDir = Path.Combine(Path.GetTempPath(), $"vd_hub_{Guid.NewGuid():N}");
|
||||
|
||||
public QueueHubE2ETests() => Directory.CreateDirectory(_libDir);
|
||||
|
||||
private sealed class FakeQueue : IQueueAdapter
|
||||
{
|
||||
public List<QueueItemDto> Items { get; } = new();
|
||||
|
||||
public Task<IReadOnlyList<QueueItemDto>> GetItemsAsync() => Task.FromResult<IReadOnlyList<QueueItemDto>>(Items);
|
||||
public Task<string> AddAsync(string url, string? title)
|
||||
{
|
||||
var item = new QueueItemDto(Guid.NewGuid().ToString("N"), title ?? url, url, "대기", 0);
|
||||
Items.Add(item);
|
||||
Changed?.Invoke();
|
||||
return Task.FromResult(item.Id);
|
||||
}
|
||||
public Task PauseAsync(string id) => Task.CompletedTask;
|
||||
public Task ResumeAsync(string id) => Task.CompletedTask;
|
||||
public Task CancelAsync(string id) => Task.CompletedTask;
|
||||
|
||||
public event Action? Changed;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task 큐허브_스냅샷_조회와_변경시_푸시_E2E()
|
||||
{
|
||||
var queue = new FakeQueue();
|
||||
await using var server = await ServerHost.StartAsync(new ServerOptions
|
||||
{
|
||||
Port = 0,
|
||||
Token = "hub-token-123",
|
||||
LibraryFolder = _libDir,
|
||||
Queue = queue,
|
||||
});
|
||||
|
||||
await using var conn = new HubConnectionBuilder()
|
||||
.WithUrl($"http://127.0.0.1:{server.Port}/hubs/queue?t=hub-token-123")
|
||||
.Build();
|
||||
|
||||
var pushed = new TaskCompletionSource<List<QueueItemDto>>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
conn.On<List<QueueItemDto>>("queueUpdated", items => pushed.TrySetResult(items));
|
||||
|
||||
await conn.StartAsync();
|
||||
|
||||
// 1) 허브 메서드로 현재 스냅샷 조회
|
||||
var snapshot = await conn.InvokeAsync<List<QueueItemDto>>("GetQueue");
|
||||
Assert.Empty(snapshot);
|
||||
|
||||
// 2) 큐 변경 → 폴링 없이 서버가 밀어줌 (2초 폴링의 실시간 대체)
|
||||
await queue.AddAsync("https://x.test/push.mp4", "푸시 영상");
|
||||
var items = await pushed.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
Assert.Single(items);
|
||||
Assert.Equal("푸시 영상", items[0].Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task 큐허브_잘못된_토큰은_401_거부()
|
||||
{
|
||||
await using var server = await ServerHost.StartAsync(new ServerOptions
|
||||
{
|
||||
Port = 0,
|
||||
Token = "hub-token-123",
|
||||
LibraryFolder = _libDir,
|
||||
Queue = new FakeQueue(),
|
||||
});
|
||||
|
||||
await using var conn = new HubConnectionBuilder()
|
||||
.WithUrl($"http://127.0.0.1:{server.Port}/hubs/queue?t=wrong-token")
|
||||
.Build();
|
||||
|
||||
await Assert.ThrowsAsync<HttpRequestException>(() => conn.StartAsync());
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Directory.Delete(_libDir, recursive: true); } catch (IOException) { }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// E2E (M0): 실제 Kestrel 서버 기동 → 인증/페어링/큐 제어/라이브러리/스트리밍/웹 컴패니언 검증.
|
||||
/// </summary>
|
||||
public class RemoteServerE2ETests : IDisposable
|
||||
{
|
||||
private readonly string _libDir = Path.Combine(Path.GetTempPath(), $"vd_srv_{Guid.NewGuid():N}");
|
||||
|
||||
private sealed class FakeQueue : IQueueAdapter
|
||||
{
|
||||
public List<QueueItemDto> Items { get; } = new();
|
||||
public List<string> Actions { get; } = new();
|
||||
|
||||
public Task<IReadOnlyList<QueueItemDto>> GetItemsAsync() => Task.FromResult<IReadOnlyList<QueueItemDto>>(Items);
|
||||
public Task<string> AddAsync(string url, string? title)
|
||||
{
|
||||
var item = new QueueItemDto(Guid.NewGuid().ToString("N"), title ?? url, url, "대기", 0);
|
||||
Items.Add(item);
|
||||
Changed?.Invoke();
|
||||
return Task.FromResult(item.Id);
|
||||
}
|
||||
public Task PauseAsync(string id) { Actions.Add($"pause:{id}"); return Task.CompletedTask; }
|
||||
public Task ResumeAsync(string id) { Actions.Add($"resume:{id}"); return Task.CompletedTask; }
|
||||
public Task CancelAsync(string id) { Actions.Add($"cancel:{id}"); return Task.CompletedTask; }
|
||||
|
||||
public event Action? Changed;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task 서버_전_API_E2E_인증_큐_라이브러리_스트리밍_웹컴패니언()
|
||||
{
|
||||
Directory.CreateDirectory(_libDir);
|
||||
var mediaPath = Path.Combine(_libDir, "sample.mp4");
|
||||
File.WriteAllBytes(mediaPath, new byte[256 * 1024]); // 256KB 가짜 미디어
|
||||
|
||||
var queue = new FakeQueue();
|
||||
await using var server = await ServerHost.StartAsync(new ServerOptions
|
||||
{
|
||||
Port = 0, // 사용 가능한 포트 자동 할당
|
||||
Token = "test-token-123",
|
||||
LibraryFolder = _libDir,
|
||||
Queue = queue,
|
||||
});
|
||||
|
||||
using var http = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.Port}") };
|
||||
|
||||
// 1) 인증 없으면 401
|
||||
var anon = await http.GetAsync("/api/queue");
|
||||
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, anon.StatusCode);
|
||||
|
||||
// 2) 틀린 토큰도 401
|
||||
using var bad = new HttpRequestMessage(HttpMethod.Get, "/api/queue");
|
||||
bad.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "wrong");
|
||||
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, (await http.SendAsync(bad)).StatusCode);
|
||||
|
||||
// 3) 페어링(올바른 토큰)
|
||||
var pair = await http.PostAsJsonAsync("/api/pair", new { token = "test-token-123", device = "E2E-Phone" });
|
||||
Assert.True(pair.IsSuccessStatusCode);
|
||||
|
||||
// 4) 큐: URL 추가 → 목록 조회
|
||||
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "test-token-123");
|
||||
var add = await http.PostAsJsonAsync("/api/queue", new { url = "https://x.test/v.mp4", title = "E2E 영상" });
|
||||
Assert.True(add.IsSuccessStatusCode);
|
||||
var items = await http.GetFromJsonAsync<List<QueueItemDto>>("/api/queue");
|
||||
Assert.NotNull(items);
|
||||
Assert.Single(items!);
|
||||
Assert.Equal("E2E 영상", items![0].Title);
|
||||
var id = items[0].Id;
|
||||
|
||||
// 5) 큐 제어 위임
|
||||
Assert.True((await http.PostAsync($"/api/queue/{id}/pause", null)).IsSuccessStatusCode);
|
||||
Assert.True((await http.PostAsync($"/api/queue/{id}/resume", null)).IsSuccessStatusCode);
|
||||
Assert.True((await http.PostAsync($"/api/queue/{id}/cancel", null)).IsSuccessStatusCode);
|
||||
Assert.Equal(new[] { $"pause:{id}", $"resume:{id}", $"cancel:{id}" }, queue.Actions);
|
||||
|
||||
// 6) 라이브러리
|
||||
var lib = await http.GetFromJsonAsync<List<LibraryItemDto>>("/api/library");
|
||||
Assert.NotNull(lib);
|
||||
Assert.Single(lib!);
|
||||
Assert.Equal("sample.mp4", lib![0].FileName);
|
||||
|
||||
// 7) 스트리밍: Range 요청 → 206 부분 응답
|
||||
using var range = new HttpRequestMessage(HttpMethod.Get, $"/stream/{lib[0].Id}");
|
||||
range.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(0, 1023);
|
||||
range.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "test-token-123");
|
||||
var partial = await http.SendAsync(range);
|
||||
Assert.Equal(System.Net.HttpStatusCode.PartialContent, partial.StatusCode);
|
||||
var bytes = await partial.Content.ReadAsByteArrayAsync();
|
||||
Assert.Equal(1024, bytes.Length);
|
||||
|
||||
// 8) 파일 다운로드: 전체 길이
|
||||
var file = await http.GetByteArrayAsync($"/file/{lib[0].Id}");
|
||||
Assert.Equal(256 * 1024, file.Length);
|
||||
|
||||
// 9) 웹 컴패니언 페이지 제공
|
||||
var page = await http.GetStringAsync("/");
|
||||
Assert.Contains("PACA", page);
|
||||
Assert.Contains("api/queue", page); // 페이지가 API 를 호출하는 스크립트 포함
|
||||
Assert.Contains("/file/", page); // 모바일 로컬 기기 저장(다운로드) 링크 포함
|
||||
Assert.Contains("download=", page);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task 이어보기_위치_동기화_E2E_저장_조회_재시작_유지()
|
||||
{
|
||||
Directory.CreateDirectory(_libDir);
|
||||
File.WriteAllBytes(Path.Combine(_libDir, "sample.mp4"), new byte[1024]);
|
||||
|
||||
var queue = new FakeQueue();
|
||||
var opts = new ServerOptions
|
||||
{
|
||||
Port = 0,
|
||||
Token = "pos-token",
|
||||
LibraryFolder = _libDir,
|
||||
Queue = queue,
|
||||
};
|
||||
await using var server = await ServerHost.StartAsync(opts);
|
||||
using var http = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.Port}") };
|
||||
|
||||
// 1) 익명 401
|
||||
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, (await http.GetAsync("/api/position/abc")).StatusCode);
|
||||
|
||||
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "pos-token");
|
||||
var lib = (await http.GetFromJsonAsync<List<LibraryItemDto>>("/api/library"))!;
|
||||
var id = lib[0].Id;
|
||||
|
||||
// 2) 미저장 기본값 0
|
||||
var before = await http.GetFromJsonAsync<PositionDto>($"/api/position/{id}");
|
||||
Assert.NotNull(before);
|
||||
Assert.Equal(0, before!.PositionSec);
|
||||
|
||||
// 3) 저장 → 조회 라운드트립
|
||||
var save = await http.PostAsJsonAsync($"/api/position/{id}", new PositionDto(93.5));
|
||||
Assert.True(save.IsSuccessStatusCode);
|
||||
var after = await http.GetFromJsonAsync<PositionDto>($"/api/position/{id}");
|
||||
Assert.Equal(93.5, after!.PositionSec);
|
||||
|
||||
// 4) 존재하지 않는 항목도 기본값 0 (섹션 파일 무손상)
|
||||
var unknown = await http.GetFromJsonAsync<PositionDto>("/api/position/no-such-id");
|
||||
Assert.Equal(0, unknown!.PositionSec);
|
||||
|
||||
// 5) 서버 재시작 후에도 유지(파일 영속)
|
||||
await server.DisposeAsync();
|
||||
await using var server2 = await ServerHost.StartAsync(new ServerOptions
|
||||
{
|
||||
Port = 0, Token = "pos-token", LibraryFolder = _libDir, Queue = queue,
|
||||
});
|
||||
using var http2 = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server2.Port}") };
|
||||
http2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "pos-token");
|
||||
var persisted = await http2.GetFromJsonAsync<PositionDto>($"/api/position/{id}");
|
||||
Assert.Equal(93.5, persisted!.PositionSec);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task 썸네일_API_E2E_생성_캐시_404()
|
||||
{
|
||||
Directory.CreateDirectory(_libDir);
|
||||
var mediaPath = Path.Combine(_libDir, "clip.mp4");
|
||||
File.WriteAllBytes(mediaPath, new byte[2048]);
|
||||
|
||||
// 가짜 ffmpeg: 출력 경로에 JPEG 생성
|
||||
var fake = new Tests.Platform.FakeProcessRunner
|
||||
{
|
||||
Behavior = (spec, _, _) =>
|
||||
{
|
||||
if (spec.Args[^1].EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)) // 해상도 프로브(미디어 경로)는 미오염
|
||||
File.WriteAllBytes(spec.Args[^1], new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0x01 });
|
||||
return Task.FromResult(new Paca.Core.Platform.ProcessResult(0, "", ""));
|
||||
},
|
||||
};
|
||||
|
||||
await using var server = await ServerHost.StartAsync(new ServerOptions
|
||||
{
|
||||
Port = 0, Token = "thumb-token", LibraryFolder = _libDir,
|
||||
Queue = new FakeQueue(),
|
||||
Thumbnailer = new Thumbnailer(fake),
|
||||
FfmpegPath = "ffmpeg", // 호스트 ffmpeg 무관(가짜 러너가 프로세스를 대신함)
|
||||
});
|
||||
using var http = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.Port}") };
|
||||
|
||||
// 1) 익명 401
|
||||
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, (await http.GetAsync("/api/library/xyz/thumb")).StatusCode);
|
||||
|
||||
// 2) 없는 항목 404
|
||||
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "thumb-token");
|
||||
Assert.Equal(System.Net.HttpStatusCode.NotFound, (await http.GetAsync("/api/library/xyz/thumb")).StatusCode);
|
||||
|
||||
// 3) 실제 항목 → 200 + JPEG 매직
|
||||
var lib = (await http.GetFromJsonAsync<List<LibraryItemDto>>("/api/library"))!;
|
||||
var thumb = await http.GetByteArrayAsync($"/api/library/{lib[0].Id}/thumb");
|
||||
Assert.True(thumb.Length >= 2 && thumb[0] == 0xFF && thumb[1] == 0xD8, "JPEG 매직 바이트");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Directory.Delete(_libDir, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>M2 라이브러리 썸네일/해상도 — ffmpeg 서브프로세스를 Fake 러너로 검증(사이드카 캐시).</summary>
|
||||
public class ThumbnailerTests
|
||||
{
|
||||
private string _dir = "";
|
||||
|
||||
private string NewMedia()
|
||||
{
|
||||
_dir = Path.Combine(Path.GetTempPath(), $"vd_thumb_{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(_dir);
|
||||
var p = Path.Combine(_dir, "clip.mp4");
|
||||
File.WriteAllBytes(p, new byte[100]);
|
||||
return p;
|
||||
}
|
||||
|
||||
private sealed class FakeProcessRunner : IProcessRunner
|
||||
{
|
||||
public Func<ProcessSpec, Action<string, string>?, CancellationToken, Task<ProcessResult>> Behavior { get; set; } =
|
||||
(spec, onLine, ct) => Task.FromResult(new ProcessResult(0, "", ""));
|
||||
|
||||
public Task<ProcessResult> RunAsync(ProcessSpec spec, Action<string, string>? onLine, CancellationToken ct) =>
|
||||
Behavior(spec, onLine, ct);
|
||||
}
|
||||
|
||||
private static Task<ProcessResult> FakeFfmpegCreatesJpg(ProcessSpec spec, Action<string, string>? _, CancellationToken __)
|
||||
{
|
||||
// 출력 경로(마지막 인자)에 가짜 JPEG 생성
|
||||
var outPath = spec.Args[^1];
|
||||
File.WriteAllBytes(outPath, new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 }); // JPEG SOI/APP0
|
||||
return Task.FromResult(new ProcessResult(0, "", ""));
|
||||
}
|
||||
|
||||
private static Task<ProcessResult> FakeFfmpegReportsResolution(ProcessSpec spec, Action<string, string>? onLine, CancellationToken _)
|
||||
{
|
||||
var line = " Stream #0:0[0x1](und): Video: h264 (High), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 5000 kb/s";
|
||||
onLine?.Invoke("err", line);
|
||||
return Task.FromResult(new ProcessResult(0, "", line));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task 썸네일_생성후_사이드카_캐시로_재실행_없음()
|
||||
{
|
||||
var media = NewMedia();
|
||||
var runner = new FakeProcessRunner { Behavior = FakeFfmpegCreatesJpg };
|
||||
var t = new Thumbnailer(runner);
|
||||
|
||||
var bytes1 = await t.GetThumbnailAsync("ffmpeg", media);
|
||||
Assert.NotNull(bytes1);
|
||||
Assert.True(bytes1!.Length == 4);
|
||||
|
||||
runner.Behavior = (_, _, _) => throw new Xunit.Sdk.XunitException("캐시 히트 시 ffmpeg 재실행 없음");
|
||||
var bytes2 = await t.GetThumbnailAsync("ffmpeg", media); // 캐시
|
||||
Assert.Equal(bytes1, bytes2);
|
||||
Directory.Delete(_dir, true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ffmpeg_실패_시_null()
|
||||
{
|
||||
var media = NewMedia();
|
||||
var runner = new FakeProcessRunner { Behavior = (_, _, _) => Task.FromResult(new ProcessResult(1, "", "boom")) };
|
||||
Assert.Null(await new Thumbnailer(runner).GetThumbnailAsync("ffmpeg", media));
|
||||
Directory.Delete(_dir, true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task 해상도_추출후_사이드카_캐시()
|
||||
{
|
||||
var media = NewMedia();
|
||||
var runner = new FakeProcessRunner { Behavior = FakeFfmpegReportsResolution };
|
||||
var t = new Thumbnailer(runner);
|
||||
|
||||
Assert.Equal("1920x1080", await t.GetResolutionAsync("ffmpeg", media));
|
||||
|
||||
runner.Behavior = (_, _, _) => throw new Xunit.Sdk.XunitException("캐시 히트 시 재실행 없음");
|
||||
Assert.Equal("1920x1080", await t.GetResolutionAsync("ffmpeg", media));
|
||||
Directory.Delete(_dir, true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task 해상기_추출_불가_시_null()
|
||||
{
|
||||
var media = NewMedia();
|
||||
var runner = new FakeProcessRunner { Behavior = (_, _, _) => Task.FromResult(new ProcessResult(0, "", "no streams")) };
|
||||
Assert.Null(await new Thumbnailer(runner).GetResolutionAsync("ffmpeg", media));
|
||||
Directory.Delete(_dir, true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Phase 63: Paca Headless Daemon & Omni-Platform Server 검증 테스트 스위트.
|
||||
/// </summary>
|
||||
public class PacaHeadlessDaemonPhase63Tests
|
||||
{
|
||||
[Fact]
|
||||
public void PacaHeadlessDaemon_라이프사이클_및_헬스체크_검증()
|
||||
{
|
||||
var config = new Paca.Server.Daemon.DaemonConfig
|
||||
{
|
||||
Port = 9090,
|
||||
DataDirectory = "/var/paca/data",
|
||||
DownloadDirectory = "/var/paca/downloads"
|
||||
};
|
||||
|
||||
var daemon = new Paca.Server.Daemon.PacaHeadlessDaemon(config);
|
||||
Assert.False(daemon.IsRunning);
|
||||
|
||||
daemon.Start();
|
||||
Assert.True(daemon.IsRunning);
|
||||
|
||||
var health = daemon.GetHealth();
|
||||
Assert.Equal("healthy", health.Status);
|
||||
Assert.Equal("3.0.0-pro", health.Version);
|
||||
Assert.True(health.UptimeSeconds >= 0);
|
||||
|
||||
daemon.Stop();
|
||||
Assert.False(daemon.IsRunning);
|
||||
Assert.Equal("stopped", daemon.GetHealth().Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PacaHeadlessDaemon_WebDashboard_HTML_렌더_검증()
|
||||
{
|
||||
var config = new Paca.Server.Daemon.DaemonConfig
|
||||
{
|
||||
Port = 8080,
|
||||
DataDirectory = "/config"
|
||||
};
|
||||
|
||||
var html = Paca.Server.Daemon.PacaHeadlessDaemon.RenderWebGuiHtml(config);
|
||||
Assert.Contains("Paca Headless Dashboard", html);
|
||||
Assert.Contains("Port: 8080", html);
|
||||
Assert.Contains("NAS / Docker", html);
|
||||
}
|
||||
}
|
||||
97
tests/Paca.Tests/Server/ServerSmartPlaylistGateTests.cs
Normal file
97
tests/Paca.Tests/Server/ServerSmartPlaylistGateTests.cs
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using Paca.Server;
|
||||
using Xunit;
|
||||
|
||||
namespace Paca.Tests.Server;
|
||||
|
||||
public class ServerSmartPlaylistGateTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Gate235_ServerHost_GetPlaylistM3u8_ReturnsValidContent()
|
||||
{
|
||||
var tempDir = Path.Combine(Path.GetTempPath(), "paca_playlist_test_" + Guid.NewGuid());
|
||||
Directory.CreateDirectory(tempDir);
|
||||
try
|
||||
{
|
||||
var testFile1 = Path.Combine(tempDir, "video1.mp4");
|
||||
File.WriteAllBytes(testFile1, new byte[1024]);
|
||||
|
||||
var options = new ServerOptions
|
||||
{
|
||||
Port = 0,
|
||||
Token = "test-token-123456",
|
||||
LibraryFolder = tempDir,
|
||||
DeviceName = "TestPC",
|
||||
Queue = new TestQueueAdapter()
|
||||
};
|
||||
|
||||
await using var host = await ServerHost.StartAsync(options);
|
||||
using var client = new HttpClient();
|
||||
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "test-token-123456");
|
||||
|
||||
var resp = await client.GetAsync($"http://127.0.0.1:{host.Port}/api/playlist/all.m3u8");
|
||||
Assert.True(resp.IsSuccessStatusCode);
|
||||
Assert.Contains("mpegurl", resp.Content.Headers.ContentType?.MediaType ?? "");
|
||||
|
||||
var body = await resp.Content.ReadAsStringAsync();
|
||||
Assert.StartsWith("#EXTM3U", body.Trim());
|
||||
Assert.Contains("video1.mp4", body);
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(tempDir, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Gate236_ServerHost_GetPlaylistM3u8_SpecificCollection_FiltersCorrectly()
|
||||
{
|
||||
var tempDir = Path.Combine(Path.GetTempPath(), "paca_playlist_test_filtered_" + Guid.NewGuid());
|
||||
Directory.CreateDirectory(tempDir);
|
||||
try
|
||||
{
|
||||
var audioFile = Path.Combine(tempDir, "song.mp3");
|
||||
var videoFile = Path.Combine(tempDir, "lecture.mp4");
|
||||
File.WriteAllBytes(audioFile, new byte[1024]);
|
||||
File.WriteAllBytes(videoFile, new byte[1024]);
|
||||
|
||||
var options = new ServerOptions
|
||||
{
|
||||
Port = 0,
|
||||
Token = "test-token-789",
|
||||
LibraryFolder = tempDir,
|
||||
DeviceName = "TestPC",
|
||||
Queue = new TestQueueAdapter()
|
||||
};
|
||||
|
||||
await using var host = await ServerHost.StartAsync(options);
|
||||
using var client = new HttpClient();
|
||||
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "test-token-789");
|
||||
|
||||
var resp = await client.GetAsync($"http://127.0.0.1:{host.Port}/api/playlist/Music%20%26%20Podcasts.m3u8");
|
||||
Assert.True(resp.IsSuccessStatusCode);
|
||||
|
||||
var body = await resp.Content.ReadAsStringAsync();
|
||||
Assert.StartsWith("#EXTM3U", body.Trim());
|
||||
Assert.Contains("song.mp3", body);
|
||||
Assert.DoesNotContain("lecture.mp4", body);
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(tempDir, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private class TestQueueAdapter : IQueueAdapter
|
||||
{
|
||||
public Task<string> AddAsync(string url, string? title = null) => Task.FromResult("q1");
|
||||
public Task CancelAsync(string id) => Task.CompletedTask;
|
||||
public Task<IReadOnlyList<QueueItemDto>> GetItemsAsync() => Task.FromResult<IReadOnlyList<QueueItemDto>>(Array.Empty<QueueItemDto>());
|
||||
public Task PauseAsync(string id) => Task.CompletedTask;
|
||||
public Task ResumeAsync(string id) => Task.CompletedTask;
|
||||
public event Action? Changed { add { } remove { } }
|
||||
}
|
||||
}
|
||||
93
tests/Paca.Tests/Server/WorkspaceRemoteApiTests.cs
Normal file
93
tests/Paca.Tests/Server/WorkspaceRemoteApiTests.cs
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using Paca.Server;
|
||||
using Xunit;
|
||||
|
||||
namespace Paca.Tests.Server;
|
||||
|
||||
public class WorkspaceRemoteApiTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task GetWorkspace_ReturnsCurrentAndWorkspacesList()
|
||||
{
|
||||
string currentWs = "작업";
|
||||
var allWs = new List<string> { "작업", "개인", "학습" };
|
||||
|
||||
await using var server = await ServerHost.StartAsync(new ServerOptions
|
||||
{
|
||||
Port = 0,
|
||||
Token = "ws-test-token",
|
||||
WorkspaceProvider = () => new WorkspaceInfoDto(currentWs, allWs)
|
||||
});
|
||||
|
||||
using var client = new HttpClient();
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "ws-test-token");
|
||||
|
||||
var response = await client.GetAsync($"http://127.0.0.1:{server.Port}/api/workspace");
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
var dto = await response.Content.ReadFromJsonAsync<WorkspaceInfoDto>();
|
||||
Assert.NotNull(dto);
|
||||
Assert.Equal("작업", dto.Current);
|
||||
Assert.Equal(3, dto.Workspaces.Count);
|
||||
Assert.Contains("작업", dto.Workspaces);
|
||||
Assert.Contains("개인", dto.Workspaces);
|
||||
Assert.Contains("학습", dto.Workspaces);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostWorkspaceSwitch_SwitchesWorkspaceAndReturnsOk()
|
||||
{
|
||||
string currentWs = "작업";
|
||||
string? switchedTo = null;
|
||||
var allWs = new List<string> { "작업", "개인", "학습" };
|
||||
|
||||
await using var server = await ServerHost.StartAsync(new ServerOptions
|
||||
{
|
||||
Port = 0,
|
||||
Token = "ws-test-token",
|
||||
WorkspaceProvider = () => new WorkspaceInfoDto(currentWs, allWs),
|
||||
WorkspaceSwitcher = name =>
|
||||
{
|
||||
switchedTo = name;
|
||||
currentWs = name;
|
||||
}
|
||||
});
|
||||
|
||||
using var client = new HttpClient();
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "ws-test-token");
|
||||
|
||||
var response = await client.PostAsJsonAsync($"http://127.0.0.1:{server.Port}/api/workspace/switch", new
|
||||
{
|
||||
name = "개인"
|
||||
});
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("개인", switchedTo);
|
||||
Assert.Equal("개인", currentWs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostWorkspaceSwitch_RejectsCorruptedName_WithBadRequest()
|
||||
{
|
||||
await using var server = await ServerHost.StartAsync(new ServerOptions
|
||||
{
|
||||
Port = 0,
|
||||
Token = "ws-test-token",
|
||||
WorkspaceProvider = () => new WorkspaceInfoDto("작업", new[] { "작업" }),
|
||||
WorkspaceSwitcher = _ => { }
|
||||
});
|
||||
|
||||
using var client = new HttpClient();
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "ws-test-token");
|
||||
|
||||
// Attempting to switch to a corrupted unicode replacement string
|
||||
var response = await client.PostAsJsonAsync($"http://127.0.0.1:{server.Port}/api/workspace/switch", new
|
||||
{
|
||||
name = "\uFFFD\u06FE\uFFFD"
|
||||
});
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue