From f4f7cb17334fa73d97f15ec07a643ffe6d5eb424 Mon Sep 17 00:00:00 2001 From: uduki Date: Mon, 31 Aug 2026 11:45:02 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20Program.cs=E3=81=A8HTTP=E3=83=AA?= =?UTF-8?q?=E3=82=AF=E3=82=A8=E3=82=B9=E3=83=88=E3=82=A8=E3=83=B3=E3=83=89?= =?UTF-8?q?=E3=83=9D=E3=82=A4=E3=83=B3=E3=83=88=E3=82=92=E5=82=99=E3=81=88?= =?UTF-8?q?=E3=81=9FRSSAPI=E3=83=97=E3=83=AD=E3=82=B8=E3=82=A7=E3=82=AF?= =?UTF-8?q?=E3=83=88=E3=82=92=E5=88=9D=E6=9C=9F=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- RSSAPI/Program.cs | 143 +++++++++++++++++++++++++++++++++++++++++++++ RSSAPI/RSSAPI.http | 2 +- 2 files changed, 144 insertions(+), 1 deletion(-) diff --git a/RSSAPI/Program.cs b/RSSAPI/Program.cs index e9001a7..c030f08 100644 --- a/RSSAPI/Program.cs +++ b/RSSAPI/Program.cs @@ -1,6 +1,8 @@ using AngleSharp; using AngleSharp.Dom; +using Microsoft.AspNetCore.WebUtilities; using System.Diagnostics; +using System.IO.Compression; using System.Security.Cryptography; using System.ServiceModel.Syndication; using System.Text; @@ -329,10 +331,151 @@ app.MapGet("/missav123", async () => } }); +// --- 2. APIエンドポイントの定義 --- +app.MapGet("/fanzine/{base64Url}", async (string base64Url, IHttpClientFactory httpClientFactory) => +{ + string targetUrl; + + // 1. Base64URL 文字列のデコード + try + { + byte[] decodedBytes = WebEncoders.Base64UrlDecode(base64Url); + targetUrl = Encoding.UTF8.GetString(decodedBytes); + } + catch (Exception) + { + return Results.BadRequest(new { error = "Base64文字列のデコードに失敗しました。" }); + } + + // 2. デコード結果が有効なURLか検証 + if (string.IsNullOrWhiteSpace(targetUrl) || !Uri.TryCreate(targetUrl, UriKind.Absolute, out Uri? baseUri)) + { + return Results.BadRequest(new { error = "有効なURLではありません。", decodedUrl = targetUrl }); + } + + try + { + // 3. AngleSharp を使って HTML を取得・解析 + using var document = await context.OpenAsync(targetUrl); + if (document == null) + { + return Results.Problem(detail: "対象ページの取得に失敗しました。", statusCode: 500); + } + + // 4. h1 タグからタイトルを取得してファイル名を作成(使用不可文字をサニタイズ) + var h1Element = document.QuerySelector("h1"); + string title = h1Element?.TextContent?.Trim() ?? "download"; + string safeFileName = cmnUtil.SanitizeFileName(title); + if (string.IsNullOrEmpty(safeFileName)) + { + safeFileName = "download"; + } + + // 5. #post-hentai 以下の img タグから画像 URL を抽出 + var imgElements = document.QuerySelectorAll("#post-hentai img"); + var imageUrls = new List(); + + foreach (var img in imgElements) + { + // data-src または src 属性を取得 + string? src = img.GetAttribute("src"); + if (string.IsNullOrEmpty(src)) + { + src = img.GetAttribute("data-src"); + } + + if (!string.IsNullOrEmpty(src)) + { + // 相対パスの場合は絶対 URL に解決 + if (Uri.TryCreate(baseUri, src, out Uri? absoluteUri)) + { + imageUrls.Add(absoluteUri); + } + } + } + + if (imageUrls.Count == 0) + { + return Results.NotFound(new { error = "指定された条件(#post-hentai img)の画像が見つかりませんでした。" }); + } + + // 6. SemaphoreSlim を用いて同時接続数を制限し、並列ダウンロード(最大5並列) + var httpClient = httpClientFactory.CreateClient(); + int maxDegreeOfParallelism = 5; + using var semaphore = new SemaphoreSlim(maxDegreeOfParallelism); + + var downloadTasks = imageUrls.Select(async uri => + { + await semaphore.WaitAsync(); + try + { + return await httpClient.GetByteArrayAsync(uri); + } + catch (Exception) + { + // ダウンロード失敗時は null + return null; + } + finally + { + semaphore.Release(); + } + }).ToList(); + + byte[]?[] downloadedImages = await Task.WhenAll(downloadTasks); + + // 7. メモリ上で ZIP アーカイブを作成 + using var zipMemoryStream = new MemoryStream(); + using (var archive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Create, leaveOpen: true)) + { + for (int i = 0; i < downloadedImages.Length; i++) + { + var imgData = downloadedImages[i]; + if (imgData == null) continue; // 取得失敗した画像はスキップ + + // 拡張子を取得(不明な場合は .jpg をデフォルトに) + string extension = Path.GetExtension(imageUrls[i].AbsolutePath); + if (string.IsNullOrEmpty(extension)) + { + extension = ".jpg"; + } + + // 元の HTML 順序通りに連番でエントリを作成 (例: image_001.jpg) + string entryName = $"image_{i + 1:D3}{extension}"; + var zipEntry = archive.CreateEntry(entryName, CompressionLevel.Optimal); + + using var entryStream = zipEntry.Open(); + await entryStream.WriteAsync(imgData); + } + } + + // 8. ZIP ファイルとしてレスポンス返却(ブラウザでクリック時にダウンロード) + return Results.File( + fileContents: zipMemoryStream.ToArray(), + contentType: "application/zip", + fileDownloadName: $"{safeFileName}.zip" + ); + } + catch (Exception ex) + { + return Results.Problem(detail: ex.Message, statusCode: 500, title: "Scraping/Download Error"); + } +}); + app.Run(); public class cmnUtil { + /// + /// ファイル名として使用できない文字をアンダースコアに置換します。 + /// + public static string SanitizeFileName(string fileName) + { + if (string.IsNullOrEmpty(fileName)) return "download"; + var invalidChars = Path.GetInvalidFileNameChars(); + return string.Join("_", fileName.Split(invalidChars, StringSplitOptions.RemoveEmptyEntries)).Trim(); + } + public static string GetLastPathPart(string urlStr) { if (Uri.TryCreate(urlStr, UriKind.Absolute, out Uri? uri)) diff --git a/RSSAPI/RSSAPI.http b/RSSAPI/RSSAPI.http index f675292..259d68e 100644 --- a/RSSAPI/RSSAPI.http +++ b/RSSAPI/RSSAPI.http @@ -3,7 +3,7 @@ # GET {{RSSAPI_HostAddress}}/momonga/fanzine # Accept: application/json -GET {{RSSAPI_HostAddress}}/missav123 +GET {{RSSAPI_HostAddress}}/momonga/fanzine/aHR0cHM6Ly96My5tb21vbi1nYS5jb20vZ2FsbGVyaWVzLzQxMTkwODUvMS53ZWJw Accept: application/json ###