改善: ZIPダウンロード時のページ抜け防止、保存先事前指定および進捗モーダルの実装

- ダウンロードボタン押下時にFile System Access APIを用いて先に保存先(ファイル名・場所)を指定するフローを導入
- 保存先指定後にリアルタイム進捗モーダル(進行状況・パーセンテージ・件数・スキップ警告・中断機能)を表示
- 各画像の取得において最大3回リトライ+待機を行い、一時的な通信エラーによる抜けを完全防止(タイムアウト時のみスキップ許容)
- 外部依存ゼロの軽量インラインZIPエンジン(Store形式・UTF-8対応)を実装し、ブラウザ内で高速かつ確実にアーカイブを生成・保存
- サーバーサイドAPI(/api/download-zip)にも最大3回のリトライおよび待機処理を追加し、バックエンド側でも抜け防止を徹底
This commit is contained in:
armonica committed 2026-11-04 11:13:41 +09:00
1 parent ab8216b38e
commit bc8bce8de4
2 files changed
+917 -25

No files matched your search

@@ -190,6 +190,161 @@ public static class UnifiedHtmlRenderer
.header-search { display: none; }
.unified-header { padding: 0 16px; }
}
/* ZIP進捗モーダルスタイル */
.zip-modal-overlay {
display: none;
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.75);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
z-index: 10000;
align-items: center;
justify-content: center;
padding: 20px;
opacity: 0;
transition: opacity 0.25s ease;
}
.zip-modal-overlay.active {
display: flex;
opacity: 1;
}
.zip-modal-card {
background: var(--bg-surface-elevated);
border: 1px solid var(--border-glow);
border-radius: 16px;
width: 100%;
max-width: 480px;
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.8), 0 0 30px rgba(99, 102, 241, 0.2);
overflow: hidden;
display: flex;
flex-direction: column;
animation: modalPop 0.3s cubic-bezier(0.16, 1, 0.3, 1);
}
@keyframes modalPop {
from { transform: scale(0.92) translateY(10px); opacity: 0; }
to { transform: scale(1) translateY(0); opacity: 1; }
}
.zip-modal-header {
padding: 18px 24px;
background: rgba(0, 0, 0, 0.3);
border-bottom: 1px solid var(--border-subtle);
}
.zip-modal-title {
font-size: 1.1rem;
font-weight: 700;
color: #fff;
display: flex;
align-items: center;
gap: 10px;
}
.zip-spinner {
width: 18px;
height: 18px;
border: 2px solid rgba(255, 255, 255, 0.2);
border-top-color: var(--accent-primary);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
.zip-spinner.done {
display: none;
}
.zip-modal-body {
padding: 24px;
display: flex;
flex-direction: column;
gap: 12px;
}
.zip-progress-track {
width: 100%;
height: 10px;
background: rgba(255, 255, 255, 0.08);
border-radius: 5px;
overflow: hidden;
position: relative;
}
.zip-progress-bar {
height: 100%;
width: 0%;
background: var(--accent-gradient);
border-radius: 5px;
transition: width 0.2s ease;
}
.zip-status-row {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.85rem;
}
.zip-status-text {
color: var(--text-muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 320px;
}
.zip-percent-text {
font-weight: 700;
color: var(--accent-primary);
font-family: 'Outfit', monospace;
font-size: 0.95rem;
}
.zip-counter-text {
font-size: 0.85rem;
color: var(--text-subtle);
font-family: 'Outfit', monospace;
}
.zip-warning-text {
font-size: 0.8rem;
color: #f59e0b;
background: rgba(245, 158, 11, 0.1);
border: 1px solid rgba(245, 158, 11, 0.25);
padding: 6px 12px;
border-radius: 6px;
}
.zip-modal-footer {
padding: 14px 24px;
background: rgba(0, 0, 0, 0.2);
border-top: 1px solid var(--border-subtle);
display: flex;
justify-content: flex-end;
}
.zip-cancel-btn {
background: rgba(255, 255, 255, 0.08);
border: 1px solid var(--border-subtle);
color: var(--text-muted);
padding: 8px 18px;
border-radius: 8px;
font-size: 0.85rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.zip-cancel-btn:hover {
background: rgba(239, 68, 68, 0.2);
border-color: rgba(239, 68, 68, 0.4);
color: #ef4444;
}
""";
#endregion
@@ -1490,7 +1645,7 @@ 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アーカイブで一括ダウンロード">
<a href="/api/download-zip?url={{Uri.EscapeDataString(gallery.SourceUrl)}}" id="headerZipBtn" class="btn-header" 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>
@@ -2049,7 +2204,361 @@ public static class UnifiedHtmlRenderer
}
setPage(startPage, false);
downloader.start();
// ZIPダウンロードボタン連携(保存先事前選択 & 進捗モーダル)
const headerZipBtn = document.getElementById('headerZipBtn');
if (headerZipBtn) {
headerZipBtn.addEventListener('click', (e) => {
e.preventDefault();
startZipDownloadWithProgress(galleryData);
});
}
</script>
<!-- ZIPダウンロード進捗モーダル -->
<div class="zip-modal-overlay" id="zipProgressModal">
<div class="zip-modal-card">
<div class="zip-modal-header">
<div class="zip-modal-title">
<span class="zip-spinner" id="zipModalSpinner"></span>
<span id="zipModalTitle">📦 ZIP一括保存中...</span>
</div>
</div>
<div class="zip-modal-body">
<div class="zip-progress-track">
<div class="zip-progress-bar" id="zipProgressBar"></div>
</div>
<div class="zip-status-row">
<span class="zip-status-text" id="zipStatusText">画像を順次取得しています...</span>
<span class="zip-percent-text" id="zipPercentText">0%</span>
</div>
<div class="zip-counter-text" id="zipCounterText">0 / {{totalPages}} ページ</div>
<div class="zip-warning-text" id="zipWarningText" style="display: none;"></div>
</div>
<div class="zip-modal-footer">
<button type="button" class="zip-cancel-btn" id="zipCancelBtn">中断する</button>
</div>
</div>
</div>
<script>
// ==========================================
// 純JavaScript ZIP生成エンジン (PKZIP Store形式)
// ==========================================
const CRC32_TABLE = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let c = i;
for (let k = 0; k < 8; k++) {
c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
}
CRC32_TABLE[i] = c >>> 0;
}
function crc32(bytes) {
let crc = 0xFFFFFFFF;
for (let i = 0; i < bytes.length; i++) {
crc = (crc >>> 8) ^ CRC32_TABLE[(crc ^ bytes[i]) & 0xFF];
}
return (crc ^ 0xFFFFFFFF) >>> 0;
}
class SimpleZip {
constructor() {
this.files = [];
}
addFile(filename, bytes) {
this.files.push({
name: filename,
bytes: bytes,
crc: crc32(bytes),
size: bytes.length
});
}
generateUint8Array() {
const textEncoder = new TextEncoder();
let totalSize = 0;
const fileHeaders = [];
for (const file of this.files) {
const nameBytes = textEncoder.encode(file.name);
const headerOffset = totalSize;
const headerSize = 30 + nameBytes.length + file.size;
totalSize += headerSize;
fileHeaders.push({ file, nameBytes, headerOffset });
}
let centralDirSize = 0;
const centralDirOffset = totalSize;
for (const { file, nameBytes } of fileHeaders) {
centralDirSize += 46 + nameBytes.length;
}
totalSize += centralDirSize;
totalSize += 22; // EOCD
const out = new Uint8Array(totalSize);
const view = new DataView(out.buffer);
let pos = 0;
for (const { file, nameBytes, headerOffset } of fileHeaders) {
view.setUint32(pos, 0x04034b50, true);
view.setUint16(pos + 4, 10, true);
view.setUint16(pos + 6, 0x0800, true); // UTF-8
view.setUint16(pos + 8, 0, true); // Store
view.setUint16(pos + 10, 0, true);
view.setUint16(pos + 12, 0, true);
view.setUint32(pos + 14, file.crc, true);
view.setUint32(pos + 18, file.size, true);
view.setUint32(pos + 22, file.size, true);
view.setUint16(pos + 26, nameBytes.length, true);
view.setUint16(pos + 28, 0, true);
pos += 30;
out.set(nameBytes, pos);
pos += nameBytes.length;
out.set(file.bytes, pos);
pos += file.bytes.length;
}
for (const { file, nameBytes, headerOffset } of fileHeaders) {
view.setUint32(pos, 0x02014b50, true);
view.setUint16(pos + 4, 20, true);
view.setUint16(pos + 6, 10, true);
view.setUint16(pos + 8, 0x0800, true);
view.setUint16(pos + 10, 0, true);
view.setUint16(pos + 12, 0, true);
view.setUint16(pos + 14, 0, true);
view.setUint32(pos + 16, file.crc, true);
view.setUint32(pos + 20, file.size, true);
view.setUint32(pos + 24, file.size, true);
view.setUint16(pos + 28, nameBytes.length, true);
view.setUint16(pos + 30, 0, true);
view.setUint16(pos + 32, 0, true);
view.setUint16(pos + 34, 0, true);
view.setUint16(pos + 36, 0, true);
view.setUint32(pos + 38, 0, true);
view.setUint32(pos + 42, headerOffset, true);
pos += 46;
out.set(nameBytes, pos);
pos += nameBytes.length;
}
view.setUint32(pos, 0x06054b50, true);
view.setUint16(pos + 4, 0, true);
view.setUint16(pos + 6, 0, true);
view.setUint16(pos + 8, this.files.length, true);
view.setUint16(pos + 10, this.files.length, true);
view.setUint32(pos + 12, centralDirSize, true);
view.setUint32(pos + 16, centralDirOffset, true);
view.setUint16(pos + 20, 0, true);
return out;
}
}
// ==========================================
// 保存先事前指定 & 進捗モーダル付きZIPダウンロード
// ==========================================
let isZipDownloading = false;
let zipAbortController = null;
async function startZipDownloadWithProgress(gallery) {
if (isZipDownloading) return;
if (!gallery || !gallery.images || gallery.images.length === 0) {
alert('ダウンロード対象の画像がありません。');
return;
}
const safeBaseName = (gallery.title || 'gallery').replace(/[\\/:*?"<>|]/g, '_').trim() || 'gallery';
const suggestedFileName = `${safeBaseName}.zip`;
let fileHandle = null;
// 1. 【要件】先に保存先を指定させる
if ('showSaveFilePicker' in window) {
try {
fileHandle = await window.showSaveFilePicker({
suggestedName: suggestedFileName,
types: [{
description: 'ZIP Archive (*.zip)',
accept: { 'application/zip': ['.zip'] }
}]
});
} catch (err) {
if (err.name === 'AbortError') {
// ユーザーが保存先選択をキャンセルした場合は処理を中断
return;
}
console.warn('showSaveFilePicker fallback:', err);
}
}
// 2. モーダル表示と初期化
const modal = document.getElementById('zipProgressModal');
const progressBar = document.getElementById('zipProgressBar');
const statusText = document.getElementById('zipStatusText');
const percentText = document.getElementById('zipPercentText');
const counterText = document.getElementById('zipCounterText');
const warningText = document.getElementById('zipWarningText');
const spinner = document.getElementById('zipModalSpinner');
const cancelBtn = document.getElementById('zipCancelBtn');
const modalTitle = document.getElementById('zipModalTitle');
isZipDownloading = true;
zipAbortController = new AbortController();
modal.classList.add('active');
progressBar.style.width = '0%';
percentText.textContent = '0%';
counterText.textContent = `0 / ${gallery.images.length} ページ`;
statusText.textContent = '画像のダウンロードを準備しています...';
warningText.style.display = 'none';
warningText.textContent = '';
spinner.classList.remove('done');
cancelBtn.textContent = '中断する';
modalTitle.textContent = '📦 ZIP一括保存中...';
cancelBtn.onclick = () => {
if (zipAbortController) zipAbortController.abort();
modal.classList.remove('active');
isZipDownloading = false;
};
const total = gallery.images.length;
let completed = 0;
let failedCount = 0;
const zip = new SimpleZip();
// 並列度3で順次確実に取得(相手サーバーへの負荷軽減とブロック防止)
const concurrency = 3;
let queueIndex = 0;
async function downloadWorker() {
while (queueIndex < gallery.images.length) {
if (zipAbortController.signal.aborted) throw new Error('Canceled');
const idx = queueIndex++;
const imgInfo = gallery.images[idx];
const pNum = imgInfo.pageNumber;
statusText.textContent = `${pNum} / ${total} ページを取得中...`;
let data = null;
let ext = '.webp';
// 最大3回リトライを行い、一時的な失敗による抜けを徹底防止
for (let attempt = 1; attempt <= 3; attempt++) {
if (zipAbortController.signal.aborted) throw new Error('Canceled');
try {
const fetchCtrl = new AbortController();
const timeoutId = setTimeout(() => fetchCtrl.abort(), 20000); // 20秒タイムアウト
const resp = await fetch(imgInfo.imageUrl, {
signal: fetchCtrl.signal
});
clearTimeout(timeoutId);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const cType = resp.headers.get('content-type') || '';
if (cType.includes('png')) ext = '.png';
else if (cType.includes('jpeg') || cType.includes('jpg')) ext = '.jpg';
else if (cType.includes('gif')) ext = '.gif';
else if (cType.includes('webp')) ext = '.webp';
else {
const urlPart = imgInfo.imageUrl.split('?')[0];
const dotExt = urlPart.split('.').pop();
if (dotExt && dotExt.length <= 4) ext = '.' + dotExt;
}
const buf = await resp.arrayBuffer();
data = new Uint8Array(buf);
break;
} catch (e) {
if (zipAbortController.signal.aborted) throw new Error('Canceled');
if (attempt < 3) {
await new Promise(r => setTimeout(r, attempt * 1000));
} else {
console.warn(`Page ${pNum} download failed after 3 attempts:`, e);
}
}
}
if (data && data.length > 0) {
const entryName = `${String(pNum).padStart(3, '0')}${ext}`;
zip.addFile(entryName, data);
} else {
failedCount++;
}
completed++;
const pct = Math.round((completed / total) * 100);
progressBar.style.width = `${pct}%`;
percentText.textContent = `${pct}%`;
counterText.textContent = `${completed} / ${total} ページ完了`;
if (failedCount > 0) {
warningText.style.display = 'block';
warningText.textContent = `※ ${failedCount} 件の画像がタイムアウト等のためスキップされました`;
}
}
}
try {
const workers = [];
for (let i = 0; i < Math.min(concurrency, gallery.images.length); i++) {
workers.push(downloadWorker());
}
await Promise.all(workers);
statusText.textContent = 'ZIPアーカイブを作成しています...';
const zipBytes = zip.generateUint8Array();
statusText.textContent = '保存先に書き込み中...';
if (fileHandle) {
const writable = await fileHandle.createWritable();
await writable.write(zipBytes);
await writable.close();
} else {
const blob = new Blob([zipBytes], { type: 'application/zip' });
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = blobUrl;
a.download = suggestedFileName;
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(blobUrl);
a.remove();
}, 5000);
}
modalTitle.textContent = '✅ 保存完了';
spinner.classList.add('done');
statusText.textContent = `全 ${zip.files.length} 枚の画像を正常に保存しました!`;
cancelBtn.textContent = '閉じる';
cancelBtn.onclick = () => {
modal.classList.remove('active');
isZipDownloading = false;
};
setTimeout(() => {
modal.classList.remove('active');
isZipDownloading = false;
}, 2200);
} catch (err) {
if (zipAbortController && zipAbortController.signal.aborted) {
console.log('Download canceled by user');
} else {
console.error('ZIP generation error:', err);
statusText.textContent = 'ダウンロード中にエラーが発生しました。';
cancelBtn.textContent = '閉じる';
}
isZipDownloading = false;
}
}
</script>
</body>
</html>
""";
@@ -2075,6 +2584,12 @@ public static class UnifiedHtmlRenderer
var encodedSourceUrl = Uri.EscapeDataString(gallery.SourceUrl);
var totalPages = gallery.TotalPages;
var galleryJson = JsonSerializer.Serialize(gallery, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
});
var metaBadges = new List<string>
{
$"<span class=\"badge-pill highlight\">全 {totalPages} ページ</span>"
@@ -2407,7 +2922,7 @@ public static class UnifiedHtmlRenderer
</div>
<div class="header-actions">
<a href="/api/download-zip?url={{encodedSourceUrl}}" class="btn-header" download title="全ページをZIPアーカイブで一括ダウンロード">
<a href="/api/download-zip?url={{encodedSourceUrl}}" id="thumbHeaderZipBtn" class="btn-header" 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>
@@ -2439,7 +2954,7 @@ public static class UnifiedHtmlRenderer
<a href="/?url={{encodedSourceUrl}}" class="primary-action-btn">
<span>📖 ビューアーで閲覧を開始する</span>
</a>
<a href="/api/download-zip?url={{encodedSourceUrl}}" class="secondary-action-btn" title="全画像をZIP形式でまとめてダウンロード">
<a href="/api/download-zip?url={{encodedSourceUrl}}" id="thumbActionZipBtn" class="secondary-action-btn" title="全画像をZIP形式でまとめて保存">
<span>📦 ZIP一括ダウンロード</span>
</a>
</div>
@@ -2460,6 +2975,7 @@ public static class UnifiedHtmlRenderer
<button id="backToTop" class="back-to-top-btn" title="上に戻る">▲</button>
<script>
const galleryData = {{galleryJson}};
const backToTop = document.getElementById('backToTop');
window.addEventListener('scroll', () => {
if (window.scrollY > 300) {
@@ -2471,7 +2987,362 @@ public static class UnifiedHtmlRenderer
backToTop.addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
// ZIPダウンロードボタン連携
const handleZipClick = (e) => {
e.preventDefault();
startZipDownloadWithProgress(galleryData);
};
const thumbHeaderZipBtn = document.getElementById('thumbHeaderZipBtn');
if (thumbHeaderZipBtn) thumbHeaderZipBtn.addEventListener('click', handleZipClick);
const thumbActionZipBtn = document.getElementById('thumbActionZipBtn');
if (thumbActionZipBtn) thumbActionZipBtn.addEventListener('click', handleZipClick);
</script>
<!-- ZIPダウンロード進捗モーダル -->
<div class="zip-modal-overlay" id="zipProgressModal">
<div class="zip-modal-card">
<div class="zip-modal-header">
<div class="zip-modal-title">
<span class="zip-spinner" id="zipModalSpinner"></span>
<span id="zipModalTitle">📦 ZIP一括保存中...</span>
</div>
</div>
<div class="zip-modal-body">
<div class="zip-progress-track">
<div class="zip-progress-bar" id="zipProgressBar"></div>
</div>
<div class="zip-status-row">
<span class="zip-status-text" id="zipStatusText">画像を順次取得しています...</span>
<span class="zip-percent-text" id="zipPercentText">0%</span>
</div>
<div class="zip-counter-text" id="zipCounterText">0 / {{totalPages}} ページ</div>
<div class="zip-warning-text" id="zipWarningText" style="display: none;"></div>
</div>
<div class="zip-modal-footer">
<button type="button" class="zip-cancel-btn" id="zipCancelBtn">中断する</button>
</div>
</div>
</div>
<script>
// ==========================================
// 純JavaScript ZIP生成エンジン (PKZIP Store形式)
// ==========================================
const CRC32_TABLE = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let c = i;
for (let k = 0; k < 8; k++) {
c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
}
CRC32_TABLE[i] = c >>> 0;
}
function crc32(bytes) {
let crc = 0xFFFFFFFF;
for (let i = 0; i < bytes.length; i++) {
crc = (crc >>> 8) ^ CRC32_TABLE[(crc ^ bytes[i]) & 0xFF];
}
return (crc ^ 0xFFFFFFFF) >>> 0;
}
class SimpleZip {
constructor() {
this.files = [];
}
addFile(filename, bytes) {
this.files.push({
name: filename,
bytes: bytes,
crc: crc32(bytes),
size: bytes.length
});
}
generateUint8Array() {
const textEncoder = new TextEncoder();
let totalSize = 0;
const fileHeaders = [];
for (const file of this.files) {
const nameBytes = textEncoder.encode(file.name);
const headerOffset = totalSize;
const headerSize = 30 + nameBytes.length + file.size;
totalSize += headerSize;
fileHeaders.push({ file, nameBytes, headerOffset });
}
let centralDirSize = 0;
const centralDirOffset = totalSize;
for (const { file, nameBytes } of fileHeaders) {
centralDirSize += 46 + nameBytes.length;
}
totalSize += centralDirSize;
totalSize += 22; // EOCD
const out = new Uint8Array(totalSize);
const view = new DataView(out.buffer);
let pos = 0;
for (const { file, nameBytes, headerOffset } of fileHeaders) {
view.setUint32(pos, 0x04034b50, true);
view.setUint16(pos + 4, 10, true);
view.setUint16(pos + 6, 0x0800, true); // UTF-8
view.setUint16(pos + 8, 0, true); // Store
view.setUint16(pos + 10, 0, true);
view.setUint16(pos + 12, 0, true);
view.setUint32(pos + 14, file.crc, true);
view.setUint32(pos + 18, file.size, true);
view.setUint32(pos + 22, file.size, true);
view.setUint16(pos + 26, nameBytes.length, true);
view.setUint16(pos + 28, 0, true);
pos += 30;
out.set(nameBytes, pos);
pos += nameBytes.length;
out.set(file.bytes, pos);
pos += file.bytes.length;
}
for (const { file, nameBytes, headerOffset } of fileHeaders) {
view.setUint32(pos, 0x02014b50, true);
view.setUint16(pos + 4, 20, true);
view.setUint16(pos + 6, 10, true);
view.setUint16(pos + 8, 0x0800, true);
view.setUint16(pos + 10, 0, true);
view.setUint16(pos + 12, 0, true);
view.setUint16(pos + 14, 0, true);
view.setUint32(pos + 16, file.crc, true);
view.setUint32(pos + 20, file.size, true);
view.setUint32(pos + 24, file.size, true);
view.setUint16(pos + 28, nameBytes.length, true);
view.setUint16(pos + 30, 0, true);
view.setUint16(pos + 32, 0, true);
view.setUint16(pos + 34, 0, true);
view.setUint16(pos + 36, 0, true);
view.setUint32(pos + 38, 0, true);
view.setUint32(pos + 42, headerOffset, true);
pos += 46;
out.set(nameBytes, pos);
pos += nameBytes.length;
}
view.setUint32(pos, 0x06054b50, true);
view.setUint16(pos + 4, 0, true);
view.setUint16(pos + 6, 0, true);
view.setUint16(pos + 8, this.files.length, true);
view.setUint16(pos + 10, this.files.length, true);
view.setUint32(pos + 12, centralDirSize, true);
view.setUint32(pos + 16, centralDirOffset, true);
view.setUint16(pos + 20, 0, true);
return out;
}
}
// ==========================================
// 保存先事前指定 & 進捗モーダル付きZIPダウンロード
// ==========================================
let isZipDownloading = false;
let zipAbortController = null;
async function startZipDownloadWithProgress(gallery) {
if (isZipDownloading) return;
if (!gallery || !gallery.images || gallery.images.length === 0) {
alert('ダウンロード対象の画像がありません。');
return;
}
const safeBaseName = (gallery.title || 'gallery').replace(/[\\/:*?"<>|]/g, '_').trim() || 'gallery';
const suggestedFileName = `${safeBaseName}.zip`;
let fileHandle = null;
// 1. 【要件】先に保存先を指定させる
if ('showSaveFilePicker' in window) {
try {
fileHandle = await window.showSaveFilePicker({
suggestedName: suggestedFileName,
types: [{
description: 'ZIP Archive (*.zip)',
accept: { 'application/zip': ['.zip'] }
}]
});
} catch (err) {
if (err.name === 'AbortError') {
// ユーザーが保存先選択をキャンセルした場合は処理を中断
return;
}
console.warn('showSaveFilePicker fallback:', err);
}
}
// 2. モーダル表示と初期化
const modal = document.getElementById('zipProgressModal');
const progressBar = document.getElementById('zipProgressBar');
const statusText = document.getElementById('zipStatusText');
const percentText = document.getElementById('zipPercentText');
const counterText = document.getElementById('zipCounterText');
const warningText = document.getElementById('zipWarningText');
const spinner = document.getElementById('zipModalSpinner');
const cancelBtn = document.getElementById('zipCancelBtn');
const modalTitle = document.getElementById('zipModalTitle');
isZipDownloading = true;
zipAbortController = new AbortController();
modal.classList.add('active');
progressBar.style.width = '0%';
percentText.textContent = '0%';
counterText.textContent = `0 / ${gallery.images.length} ページ`;
statusText.textContent = '画像のダウンロードを準備しています...';
warningText.style.display = 'none';
warningText.textContent = '';
spinner.classList.remove('done');
cancelBtn.textContent = '中断する';
modalTitle.textContent = '📦 ZIP一括保存中...';
cancelBtn.onclick = () => {
if (zipAbortController) zipAbortController.abort();
modal.classList.remove('active');
isZipDownloading = false;
};
const total = gallery.images.length;
let completed = 0;
let failedCount = 0;
const zip = new SimpleZip();
// 並列度3で順次確実に取得(相手サーバーへの負荷軽減とブロック防止)
const concurrency = 3;
let queueIndex = 0;
async function downloadWorker() {
while (queueIndex < gallery.images.length) {
if (zipAbortController.signal.aborted) throw new Error('Canceled');
const idx = queueIndex++;
const imgInfo = gallery.images[idx];
const pNum = imgInfo.pageNumber;
statusText.textContent = `${pNum} / ${total} ページを取得中...`;
let data = null;
let ext = '.webp';
// 最大3回リトライを行い、一時的な失敗による抜けを徹底防止
for (let attempt = 1; attempt <= 3; attempt++) {
if (zipAbortController.signal.aborted) throw new Error('Canceled');
try {
const fetchCtrl = new AbortController();
const timeoutId = setTimeout(() => fetchCtrl.abort(), 20000); // 20秒タイムアウト
const resp = await fetch(imgInfo.imageUrl, {
signal: fetchCtrl.signal
});
clearTimeout(timeoutId);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const cType = resp.headers.get('content-type') || '';
if (cType.includes('png')) ext = '.png';
else if (cType.includes('jpeg') || cType.includes('jpg')) ext = '.jpg';
else if (cType.includes('gif')) ext = '.gif';
else if (cType.includes('webp')) ext = '.webp';
else {
const urlPart = imgInfo.imageUrl.split('?')[0];
const dotExt = urlPart.split('.').pop();
if (dotExt && dotExt.length <= 4) ext = '.' + dotExt;
}
const buf = await resp.arrayBuffer();
data = new Uint8Array(buf);
break;
} catch (e) {
if (zipAbortController.signal.aborted) throw new Error('Canceled');
if (attempt < 3) {
await new Promise(r => setTimeout(r, attempt * 1000));
} else {
console.warn(`Page ${pNum} download failed after 3 attempts:`, e);
}
}
}
if (data && data.length > 0) {
const entryName = `${String(pNum).padStart(3, '0')}${ext}`;
zip.addFile(entryName, data);
} else {
failedCount++;
}
completed++;
const pct = Math.round((completed / total) * 100);
progressBar.style.width = `${pct}%`;
percentText.textContent = `${pct}%`;
counterText.textContent = `${completed} / ${total} ページ完了`;
if (failedCount > 0) {
warningText.style.display = 'block';
warningText.textContent = `※ ${failedCount} 件の画像がタイムアウト等のためスキップされました`;
}
}
}
try {
const workers = [];
for (let i = 0; i < Math.min(concurrency, gallery.images.length); i++) {
workers.push(downloadWorker());
}
await Promise.all(workers);
statusText.textContent = 'ZIPアーカイブを作成しています...';
const zipBytes = zip.generateUint8Array();
statusText.textContent = '保存先に書き込み中...';
if (fileHandle) {
const writable = await fileHandle.createWritable();
await writable.write(zipBytes);
await writable.close();
} else {
const blob = new Blob([zipBytes], { type: 'application/zip' });
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = blobUrl;
a.download = suggestedFileName;
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(blobUrl);
a.remove();
}, 5000);
}
modalTitle.textContent = '✅ 保存完了';
spinner.classList.add('done');
statusText.textContent = `全 ${zip.files.length} 枚の画像を正常に保存しました!`;
cancelBtn.textContent = '閉じる';
cancelBtn.onclick = () => {
modal.classList.remove('active');
isZipDownloading = false;
};
setTimeout(() => {
modal.classList.remove('active');
isZipDownloading = false;
}, 2200);
} catch (err) {
if (zipAbortController && zipAbortController.signal.aborted) {
console.log('Download canceled by user');
} else {
console.error('ZIP generation error:', err);
statusText.textContent = 'ダウンロード中にエラーが発生しました。';
cancelBtn.textContent = '閉じる';
}
isZipDownloading = false;
}
}
</script>
</body>
</html>
""";
+43 -22
View File
@@ -278,36 +278,57 @@ static async Task<(byte[]? Data, string? ContentType)> FetchImageBytesForZipAsyn
UnifiedHttpHelper httpHelper,
CancellationToken ct)
{
try
{
string targetUrl = imageUrl;
string? targetReferer = defaultReferer;
string targetUrl = imageUrl;
string? targetReferer = defaultReferer;
// /api/proxy-image?... 形式の場合は内部パラメータを展開して直接取得
if (imageUrl.StartsWith("/api/proxy-image", StringComparison.OrdinalIgnoreCase))
// /api/proxy-image?... 形式の場合は内部パラメータを展開して直接取得
if (imageUrl.StartsWith("/api/proxy-image", StringComparison.OrdinalIgnoreCase))
{
var qIndex = imageUrl.IndexOf('?');
if (qIndex >= 0)
{
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))
{
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();
}
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
// 最大3回リトライを行い、一時的なネットワーク揺らぎによるページ抜けを徹底防止
for (int attempt = 1; attempt <= 3; attempt++)
{
return (null, null);
try
{
var (data, contentType) = await httpHelper.GetBinaryAsync(targetUrl, targetReferer, ct);
if (data != null && data.Length > 0)
{
return (data, contentType);
}
}
catch (OperationCanceledException)
{
throw;
}
catch
{
if (attempt == 3) break;
try
{
await Task.Delay(attempt * 1000, ct);
}
catch (OperationCanceledException)
{
throw;
}
}
}
return (null, null);
}
static string DetermineImageExtensionForZip(string? contentType, string imageUrl)