追加: 全ページZIP一括ダウンロードAPIの新設とヘッダーボタンの追加
- ギャラリーの全ページ画像を安全かつ高速にZIPアーカイブとして一括配信するAPI(/api/download-zip)を新設 - 最大4並列での画像取得、ContentTypeおよび拡張子の自動判別、ゼロ埋め連番ファイル名(001.jpg等)による格納を実装 - サーバーメモリ枯渇を防ぐ一時ファイルストリーミング配信とFastest圧縮レベルによる高速生成を実現 - ビューアー画面およびサムネイル一覧画面のヘッダーに「ZIP保存」ボタンを追加
This commit is contained in:
1 parent
b9a316254b
commit
ab8216b38e
2 files changed
+176
-1
No files matched your search
@@ -1490,6 +1490,10 @@ public static class UnifiedHtmlRenderer
|
||||
</div>
|
||||
|
||||
<div class="header-actions">
|
||||
<a href="/api/download-zip?url={{Uri.EscapeDataString(gallery.SourceUrl)}}" class="btn-header" download title="全ページをZIPアーカイブで一括ダウンロード">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
|
||||
<span>ZIP保存</span>
|
||||
</a>
|
||||
<a href="/?url={{Uri.EscapeDataString(gallery.SourceUrl)}}&view=thumbnails" class="btn-header" title="全ページのサムネイルを一覧表示">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>
|
||||
<span>サムネイル一覧</span>
|
||||
@@ -2403,6 +2407,10 @@ public static class UnifiedHtmlRenderer
|
||||
</div>
|
||||
|
||||
<div class="header-actions">
|
||||
<a href="/api/download-zip?url={{encodedSourceUrl}}" class="btn-header" download title="全ページをZIPアーカイブで一括ダウンロード">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
|
||||
<span>ZIP保存</span>
|
||||
</a>
|
||||
<a href="/?url={{encodedSourceUrl}}" class="btn-header" style="background: var(--accent-gradient-gallery); color: #fff; border-color: transparent;">
|
||||
<span>📖 ビューアーを開く</span>
|
||||
</a>
|
||||
|
||||
+168
-1
@@ -1,4 +1,5 @@
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using System.IO.Compression;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using WebImageViewer.Class.Legacy;
|
||||
using WebImageViewer.Class.Unified;
|
||||
using WebImageViewer.Class.Unified.Common;
|
||||
@@ -109,6 +110,109 @@ app.MapGet("/thumbnails", async (string? url, UnifiedViewerService viewerService
|
||||
return Results.Content(UnifiedHtmlRenderer.RenderThumbnailGridPage(result.Gallery), "text/html; charset=utf-8");
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// 全ページZIP一括ダウンロードAPI
|
||||
// ==========================================
|
||||
app.MapGet("/api/download-zip", async (
|
||||
string url,
|
||||
UnifiedViewerService viewerService,
|
||||
UnifiedHttpHelper httpHelper,
|
||||
HttpContext httpContext,
|
||||
ILoggerFactory loggerFactory,
|
||||
CancellationToken ct) =>
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url))
|
||||
{
|
||||
return Results.BadRequest("URL is required");
|
||||
}
|
||||
|
||||
var logger = loggerFactory.CreateLogger("ZipDownload");
|
||||
var result = await viewerService.ResolveAsync(url, null, null, ct);
|
||||
if (!result.IsSuccess || result.Gallery == null || result.Gallery.Images.Count == 0)
|
||||
{
|
||||
return Results.NotFound(new { error = result.ErrorMessage ?? "ギャラリー画像を取得できませんでした。" });
|
||||
}
|
||||
|
||||
var gallery = result.Gallery;
|
||||
|
||||
// ファイル名として使用できない文字を除去
|
||||
var invalidChars = Path.GetInvalidFileNameChars();
|
||||
var cleanTitle = string.Concat(gallery.Title.Select(c => invalidChars.Contains(c) ? '_' : c)).Trim();
|
||||
if (string.IsNullOrWhiteSpace(cleanTitle)) cleanTitle = "gallery";
|
||||
var zipFileName = $"{cleanTitle}.zip";
|
||||
|
||||
httpContext.Response.ContentType = "application/zip";
|
||||
httpContext.Response.Headers.ContentDisposition = $"attachment; filename=\"{Uri.EscapeDataString(zipFileName)}\"; filename*=UTF-8''{Uri.EscapeDataString(zipFileName)}";
|
||||
|
||||
// サーバーメモリを圧迫しないよう一時ファイルを使用して安全にZIPストリーミング生成
|
||||
var tempZipPath = Path.GetTempFileName();
|
||||
|
||||
try
|
||||
{
|
||||
using (var fileStream = new FileStream(tempZipPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, FileOptions.DeleteOnClose))
|
||||
{
|
||||
using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, leaveOpen: true))
|
||||
{
|
||||
// 最大4並列で各ページの画像データを取得
|
||||
using var semaphore = new SemaphoreSlim(4);
|
||||
var downloadTasks = gallery.Images.Select(async img =>
|
||||
{
|
||||
await semaphore.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
var (data, contentType) = await FetchImageBytesForZipAsync(img.ImageUrl, gallery.SourceUrl, httpHelper, ct);
|
||||
return (img.PageNumber, img.ImageUrl, Data: data, ContentType: contentType);
|
||||
}
|
||||
finally
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
}).ToList();
|
||||
|
||||
var downloadResults = await Task.WhenAll(downloadTasks);
|
||||
|
||||
foreach (var item in downloadResults.OrderBy(r => r.PageNumber))
|
||||
{
|
||||
if (item.Data == null || item.Data.Length == 0)
|
||||
{
|
||||
logger.LogWarning("ページ {Page} の画像ダウンロードをスキップしました (データなし)", item.PageNumber);
|
||||
continue;
|
||||
}
|
||||
|
||||
var ext = DetermineImageExtensionForZip(item.ContentType, item.ImageUrl);
|
||||
var entryName = $"{item.PageNumber:D3}{ext}";
|
||||
var entry = archive.CreateEntry(entryName, CompressionLevel.Fastest);
|
||||
|
||||
using var entryStream = entry.Open();
|
||||
await entryStream.WriteAsync(item.Data, ct);
|
||||
}
|
||||
}
|
||||
|
||||
fileStream.Position = 0;
|
||||
await fileStream.CopyToAsync(httpContext.Response.Body, ct);
|
||||
}
|
||||
|
||||
return Results.Empty;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
logger.LogInformation("ZIPダウンロードがクライアントによりキャンセルされました: {Url}", url);
|
||||
return Results.Empty;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "ZIPアーカイブ生成エラー: {Url}", url);
|
||||
return Results.Problem(detail: ex.Message, statusCode: 500);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(tempZipPath))
|
||||
{
|
||||
try { File.Delete(tempZipPath); } catch { }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// 画像プロキシAPI (Referer制限回避・高速キャッシュ配信)
|
||||
// ==========================================
|
||||
@@ -165,4 +269,67 @@ app.MapMethods("/api/proxy-embed-req", new[] { "GET", "POST", "HEAD" }, async (s
|
||||
// ==========================================
|
||||
app.MapLegacyEndpoints();
|
||||
|
||||
// ==========================================
|
||||
// ZIPダウンロード用画像バイナリ取得ヘルパー
|
||||
// ==========================================
|
||||
static async Task<(byte[]? Data, string? ContentType)> FetchImageBytesForZipAsync(
|
||||
string imageUrl,
|
||||
string defaultReferer,
|
||||
UnifiedHttpHelper httpHelper,
|
||||
CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
string targetUrl = imageUrl;
|
||||
string? targetReferer = defaultReferer;
|
||||
|
||||
// /api/proxy-image?... 形式の場合は内部パラメータを展開して直接取得
|
||||
if (imageUrl.StartsWith("/api/proxy-image", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var qIndex = imageUrl.IndexOf('?');
|
||||
if (qIndex >= 0)
|
||||
{
|
||||
var qs = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(imageUrl.Substring(qIndex));
|
||||
if (qs.TryGetValue("url", out var u) && !string.IsNullOrEmpty(u))
|
||||
{
|
||||
targetUrl = u.ToString();
|
||||
}
|
||||
if (qs.TryGetValue("referer", out var r) && !string.IsNullOrEmpty(r))
|
||||
{
|
||||
targetReferer = r.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (data, contentType) = await httpHelper.GetBinaryAsync(targetUrl, targetReferer, ct);
|
||||
return (data, contentType);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (null, null);
|
||||
}
|
||||
}
|
||||
|
||||
static string DetermineImageExtensionForZip(string? contentType, string imageUrl)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(contentType))
|
||||
{
|
||||
var ctLower = contentType.ToLowerInvariant();
|
||||
if (ctLower.Contains("png")) return ".png";
|
||||
if (ctLower.Contains("webp")) return ".webp";
|
||||
if (ctLower.Contains("gif")) return ".gif";
|
||||
if (ctLower.Contains("jpeg") || ctLower.Contains("jpg")) return ".jpg";
|
||||
if (ctLower.Contains("avif")) return ".avif";
|
||||
}
|
||||
|
||||
var cleanUrl = imageUrl.Split('?')[0];
|
||||
var ext = Path.GetExtension(cleanUrl);
|
||||
if (!string.IsNullOrWhiteSpace(ext) && ext.Length <= 5)
|
||||
{
|
||||
return ext.ToLowerInvariant();
|
||||
}
|
||||
|
||||
return ".jpg";
|
||||
}
|
||||
|
||||
app.Run();
|
||||
Reference in new issue
Block a user