feat: Program.csとHTTPリクエストエンドポイントを備えたRSSAPIプロジェクトを初期化
This commit is contained in:
1 parent
d16109b441
commit
f4f7cb1733
2 files changed
+144
-1
No files matched your search
@@ -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<Uri>();
|
||||
|
||||
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
|
||||
{
|
||||
/// <summary>
|
||||
/// ファイル名として使用できない文字をアンダースコアに置換します。
|
||||
/// </summary>
|
||||
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))
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
###
|
||||
Reference in new issue
Block a user