feat(unified): HTTPヘルパー設定注入とビューアーサービス連携を改善
This commit is contained in:
1 parent
295d1f0731
commit
d3ef4fe04f
2 files changed
+125
-26
No files matched your search
@@ -1,5 +1,6 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace WebImageViewer.Class.Unified.Common;
|
||||
@@ -11,14 +12,16 @@ namespace WebImageViewer.Class.Unified.Common;
|
||||
public class UnifiedHttpHelper
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly ILogger<UnifiedHttpHelper> _logger;
|
||||
private const string FlareSolverrUrl = "http://localhost:8191/v1";
|
||||
|
||||
public UnifiedHttpHelper(HttpClient httpClient, ILogger<UnifiedHttpHelper> logger)
|
||||
public UnifiedHttpHelper(HttpClient httpClient, IConfiguration configuration, ILogger<UnifiedHttpHelper> logger)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_configuration = configuration;
|
||||
_logger = logger;
|
||||
_httpClient.Timeout = TimeSpan.FromSeconds(25);
|
||||
// FlareSolverrでのチャレンジ解決(最大60秒)に備え十分なタイムアウトを設定
|
||||
_httpClient.Timeout = TimeSpan.FromSeconds(70);
|
||||
_httpClient.DefaultRequestHeaders.Clear();
|
||||
_httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36");
|
||||
_httpClient.DefaultRequestHeaders.Add("Accept-Language", "ja,en-US;q=0.9,en;q=0.8");
|
||||
@@ -65,30 +68,66 @@ public class UnifiedHttpHelper
|
||||
/// </summary>
|
||||
private async Task<string> GetHtmlViaFlareSolverrAsync(string url, CancellationToken ct)
|
||||
{
|
||||
var configuredEndpoint = _configuration["FlareSolverr:Endpoint"] ?? "http://127.0.0.1/v1";
|
||||
var hostHeader = _configuration["FlareSolverr:HostHeader"] ?? "udukipc-flaresolverr.armonica-vps.work";
|
||||
var timeoutMs = int.TryParse(_configuration["FlareSolverr:TimeoutMs"], out var t) ? t : 60000;
|
||||
|
||||
// 試行先エンドポイントリスト(設定値 -> 公開HTTPSエンドポイント -> ローカルホスト)
|
||||
var candidates = new List<(string Endpoint, string? Host)>
|
||||
{
|
||||
(configuredEndpoint, hostHeader),
|
||||
("https://udukipc-flaresolverr.armonica-vps.work/v1", null),
|
||||
("http://127.0.0.1:8191/v1", null)
|
||||
};
|
||||
|
||||
var payload = new
|
||||
{
|
||||
cmd = "request.get",
|
||||
url = url,
|
||||
maxTimeout = 30000
|
||||
maxTimeout = timeoutMs
|
||||
};
|
||||
|
||||
var content = new StringContent(
|
||||
JsonSerializer.Serialize(payload),
|
||||
System.Text.Encoding.UTF8,
|
||||
"application/json");
|
||||
var contentString = JsonSerializer.Serialize(payload);
|
||||
|
||||
using var resp = await _httpClient.PostAsync(FlareSolverrUrl, content, ct);
|
||||
resp.EnsureSuccessStatusCode();
|
||||
|
||||
var json = await resp.Content.ReadAsStringAsync(ct);
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
if (doc.RootElement.TryGetProperty("solution", out var sol) &&
|
||||
sol.TryGetProperty("response", out var respHtml))
|
||||
Exception? lastEx = null;
|
||||
foreach (var (endpoint, host) in candidates.DistinctBy(c => c.Endpoint))
|
||||
{
|
||||
return respHtml.GetString() ?? string.Empty;
|
||||
try
|
||||
{
|
||||
using var req = new HttpRequestMessage(HttpMethod.Post, endpoint)
|
||||
{
|
||||
Content = new StringContent(contentString, System.Text.Encoding.UTF8, "application/json")
|
||||
};
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(host))
|
||||
{
|
||||
req.Headers.Host = host;
|
||||
}
|
||||
|
||||
using var resp = await _httpClient.SendAsync(req, ct);
|
||||
if (!resp.IsSuccessStatusCode)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var json = await resp.Content.ReadAsStringAsync(ct);
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
var root = doc.RootElement;
|
||||
if (root.TryGetProperty("status", out var statusProp) && statusProp.GetString() == "ok" &&
|
||||
root.TryGetProperty("solution", out var sol) &&
|
||||
sol.TryGetProperty("response", out var respHtml))
|
||||
{
|
||||
return respHtml.GetString() ?? string.Empty;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
lastEx = ex;
|
||||
_logger.LogDebug(ex, "FlareSolverrエンドポイント({Endpoint})へのリクエストに失敗しました", endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("FlareSolverrのレスポンスに有効なHTMLが含まれていませんでした。");
|
||||
throw lastEx ?? new InvalidOperationException("すべてのFlareSolverrエンドポイントからの取得に失敗しました。");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -28,19 +28,47 @@ public class UnifiedViewerService
|
||||
/// 入力されたURLまたはIDを自動解析し、動画または画像ギャラリーの解決結果を返します。
|
||||
/// </summary>
|
||||
public async Task<UnifiedViewerResult> ResolveAsync(string urlOrInput, CancellationToken ct = default)
|
||||
{
|
||||
return await ResolveAsync(urlOrInput, null, null, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 入力されたURLまたはID、および補助パラメータ(play/stream)を考慮して動画または画像ギャラリーの解決結果を返します。
|
||||
/// </summary>
|
||||
public async Task<UnifiedViewerResult> ResolveAsync(string urlOrInput, string? play = null, string? stream = null, CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(urlOrInput))
|
||||
{
|
||||
return new UnifiedViewerResult
|
||||
if (!string.IsNullOrWhiteSpace(play) || !string.IsNullOrWhiteSpace(stream))
|
||||
{
|
||||
Type = MediaType.Unknown,
|
||||
IsSuccess = false,
|
||||
ErrorMessage = "URLまたはIDが入力されていません。",
|
||||
StatusCode = 400
|
||||
};
|
||||
urlOrInput = play ?? stream ?? "";
|
||||
}
|
||||
else
|
||||
{
|
||||
return new UnifiedViewerResult
|
||||
{
|
||||
Type = MediaType.Unknown,
|
||||
IsSuccess = false,
|
||||
ErrorMessage = "URLまたはIDが入力されていません。",
|
||||
StatusCode = 400
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
var trimmed = urlOrInput.Trim();
|
||||
|
||||
// urlOrInput自体にplayやstreamが含まれている場合の救済
|
||||
if (string.IsNullOrWhiteSpace(play) && trimmed.Contains("play=", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var mPlay = System.Text.RegularExpressions.Regex.Match(trimmed, @"[?&]play=([^&]+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
if (mPlay.Success) play = Uri.UnescapeDataString(mPlay.Groups[1].Value);
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(stream) && trimmed.Contains("stream=", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var mStream = System.Text.RegularExpressions.Regex.Match(trimmed, @"[?&]stream=([^&]+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
if (mStream.Success) stream = Uri.UnescapeDataString(mStream.Groups[1].Value);
|
||||
}
|
||||
|
||||
var classification = DomainClassifier.Classify(trimmed);
|
||||
_logger.LogInformation("URL解析結果: Host={Host}, SiteKey={SiteKey}, Type={MediaType}",
|
||||
classification.Host, classification.SiteKey, classification.MediaType);
|
||||
@@ -48,7 +76,7 @@ public class UnifiedViewerService
|
||||
// 1. 動画サイト判定の場合
|
||||
if (classification.MediaType == MediaType.Video)
|
||||
{
|
||||
var video = await _videoExtractor.ResolveAsync(trimmed, ct);
|
||||
var video = await _videoExtractor.ResolveAsync(trimmed, play, stream, ct);
|
||||
return new UnifiedViewerResult
|
||||
{
|
||||
Type = MediaType.Video,
|
||||
@@ -62,6 +90,38 @@ public class UnifiedViewerService
|
||||
// 2. 画像ギャラリーサイト判定の場合
|
||||
if (classification.MediaType == MediaType.Gallery)
|
||||
{
|
||||
// 直接画像URL(WebP/JPG/PNG等の直リンク)の即時構築
|
||||
if (string.Equals(classification.SiteKey, "direct_image", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var directGallery = new UnifiedGalleryItem
|
||||
{
|
||||
Id = "direct",
|
||||
Title = "画像ビューアー",
|
||||
SourceSite = "Direct Image",
|
||||
SourceUrl = trimmed,
|
||||
ThumbnailUrl = trimmed,
|
||||
Images = new List<UnifiedImageInfo>
|
||||
{
|
||||
new()
|
||||
{
|
||||
PageNumber = 1,
|
||||
ImageUrl = trimmed,
|
||||
ThumbnailUrl = trimmed,
|
||||
AltText = "画像"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return new UnifiedViewerResult
|
||||
{
|
||||
Type = MediaType.Gallery,
|
||||
OriginalUrl = trimmed,
|
||||
Gallery = directGallery,
|
||||
IsSuccess = true,
|
||||
StatusCode = 200
|
||||
};
|
||||
}
|
||||
|
||||
var scraper = _scrapers.FirstOrDefault(s => s.CanHandle(trimmed));
|
||||
if (scraper != null)
|
||||
{
|
||||
@@ -80,7 +140,7 @@ public class UnifiedViewerService
|
||||
}
|
||||
|
||||
// 画像サイトとしての取得に失敗した場合、動画の可能性もフォールバック試行
|
||||
var fallbackVideo = await _videoExtractor.ResolveAsync(trimmed, ct);
|
||||
var fallbackVideo = await _videoExtractor.ResolveAsync(trimmed, play, stream, ct);
|
||||
if (fallbackVideo.HasPlayableContent)
|
||||
{
|
||||
return new UnifiedViewerResult
|
||||
@@ -104,7 +164,7 @@ public class UnifiedViewerService
|
||||
}
|
||||
|
||||
// 3. 不明・汎用URLの場合: まず動画の埋め込み・ストリーム検出を試行
|
||||
var unknownVideo = await _videoExtractor.ResolveAsync(trimmed, ct);
|
||||
var unknownVideo = await _videoExtractor.ResolveAsync(trimmed, play, stream, ct);
|
||||
if (unknownVideo.HasPlayableContent)
|
||||
{
|
||||
return new UnifiedViewerResult
|
||||
|
||||
Reference in new issue
Block a user