v0.2.0: URL 패턴 기반 이미지 생성 fallback + downloadImagesAsZip 구현

This commit is contained in:
user01
2026-06-14 22:41:09 +09:00
parent a3845bf429
commit beb8b793dd

View File

@@ -1,7 +1,7 @@
// ==UserScript== // ==UserScript==
// @name sbxh6Downloader // @name sbxh6Downloader
// @namespace https://github.com/crossSiteKikyo/tokiDownloader // @namespace https://github.com/crossSiteKikyo/tokiDownloader
// @version 0.1.0 // @version 0.2.0
// @description sbxh6.com (뉴토끼) 만화 다운로더 // @description sbxh6.com (뉴토끼) 만화 다운로더
// @author hehaho // @author hehaho
// @match https://sbxh*.com/manhwa/* // @match https://sbxh*.com/manhwa/*
@@ -20,22 +20,36 @@
(function () { (function () {
'use strict'; 'use strict';
// 페이지가 setTimeout을 오버라이드해도 영향받지 않도록 원본 캡처
const _setTimeout = window.setTimeout.bind(window);
const sleep = (ms) => new Promise(r => _setTimeout(r, ms));
// --------------------------------------------------------------- // ---------------------------------------------------------------
// Phase 1: IntersectionObserver 후킹 (document-start 에서 즉시 실행) // Phase 1: 문서 표시 상태 강제 + IntersectionObserver 후킹
// 백그라운드 탭에서 IO가 동작하지 않아도 observe() 즉시 콜백 실행
// --------------------------------------------------------------- // ---------------------------------------------------------------
// document.hidden 강제 false (배경 탭에서도 페이지가 활성화된 것으로 인식) // document/visibility 강제 활성화 (페이지 JS가 덮어써도 주기적 복원)
try { const forceVisible = () => {
Object.defineProperty(document, 'hidden', { get: () => false, configurable: true }); try {
Object.defineProperty(document, 'visibilityState', { get: () => 'visible', configurable: true }); Object.defineProperty(document, 'hidden', { get: () => false, configurable: true });
} catch (_) {} Object.defineProperty(document, 'visibilityState', { get: () => 'visible', configurable: true });
try { ['webkitHidden', 'mozHidden', 'msHidden'].forEach(p => {
const proto = Document.prototype; try { Object.defineProperty(document, p, { get: () => false, configurable: true }); } catch (_) {}
if (proto) { });
Object.defineProperty(proto, 'hidden', { get: () => false, configurable: true }); } catch (_) {}
Object.defineProperty(proto, 'visibilityState', { get: () => 'visible', configurable: true }); try {
} const proto = Document.prototype;
} catch (_) {} if (proto) {
Object.defineProperty(proto, 'hidden', { get: () => false, configurable: true });
Object.defineProperty(proto, 'visibilityState', { get: () => 'visible', configurable: true });
}
} catch (_) {}
try { document.hasFocus = () => true; } catch (_) {}
};
forceVisible();
(function refreshVisible() {
forceVisible();
_setTimeout(refreshVisible, 500);
})();
// IntersectionObserver 후킹: observe() 즉시 콜백 실행 // IntersectionObserver 후킹: observe() 즉시 콜백 실행
const OrigIO = window.IntersectionObserver; const OrigIO = window.IntersectionObserver;
@@ -45,7 +59,7 @@
const origObserve = instance.observe.bind(instance); const origObserve = instance.observe.bind(instance);
instance.observe = function (target) { instance.observe = function (target) {
origObserve(target); origObserve(target);
setTimeout(() => { _setTimeout(() => {
try { try {
callback([{ callback([{
target: target, target: target,
@@ -69,10 +83,38 @@
// Phase 2: DOM 로딩 후 나머지 로직 // Phase 2: DOM 로딩 후 나머지 로직
// --------------------------------------------------------------- // ---------------------------------------------------------------
const main = () => { const main = () => {
// 사이트가 console을 모니터링/차단하므로 자체 로거 사용 // ---------------------------------------------------------------
const log = (...args) => { // 로깅 시스템 (sessionStorage 기반, 페이지 이동 시에도 유지)
try { console.log(...args); } catch (_) {} // ---------------------------------------------------------------
const LOG_KEY2 = 'sbxh6_log';
const getLog = () => {
try { return JSON.parse(sessionStorage.getItem(LOG_KEY2) || '[]'); } catch (_) { return []; }
}; };
const appendLog = (...args) => {
const msg = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ');
const entry = `[${new Date().toISOString().slice(11,23)}] ${msg}`;
try { console.log(...args); } catch (_) {}
try {
const buf = getLog();
buf.push(entry);
if (buf.length > 500) buf.splice(0, buf.length - 500);
sessionStorage.setItem(LOG_KEY2, JSON.stringify(buf));
} catch (_) {}
};
const downloadLog = () => {
const buf = getLog();
if (buf.length === 0) { alert('로그가 없습니다.'); return; }
const text = buf.join('\n');
const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = `download_log_${Date.now()}.txt`;
a.click();
URL.revokeObjectURL(url);
};
const log = appendLog;
// 메뉴 명령 ID 관리 (중복 등록 방지 → 배지 숫자 증가 방지) // 메뉴 명령 ID 관리 (중복 등록 방지 → 배지 숫자 증가 방지)
let menuCmdIds = []; let menuCmdIds = [];
@@ -88,8 +130,10 @@
menuCmdIds.push(GM_registerMenuCommand('[목록] 전체 에피소드 다운로드', () => downloadAllEpisodes())); menuCmdIds.push(GM_registerMenuCommand('[목록] 전체 에피소드 다운로드', () => downloadAllEpisodes()));
menuCmdIds.push(GM_registerMenuCommand('[목록] n화 이후 다운로드', () => downloadAfterEpisode())); menuCmdIds.push(GM_registerMenuCommand('[목록] n화 이후 다운로드', () => downloadAfterEpisode()));
menuCmdIds.push(GM_registerMenuCommand('[목록] 범위 다운로드', () => downloadRangeEpisodes())); menuCmdIds.push(GM_registerMenuCommand('[목록] 범위 다운로드', () => downloadRangeEpisodes()));
menuCmdIds.push(GM_registerMenuCommand('[목록] 로그 다운로드', () => downloadLog()));
} else if (isEpisodePage) { } else if (isEpisodePage) {
menuCmdIds.push(GM_registerMenuCommand('현재 에피소드 다운로드', () => downloadCurrentEpisode())); menuCmdIds.push(GM_registerMenuCommand('현재 에피소드 다운로드', () => downloadCurrentEpisode()));
menuCmdIds.push(GM_registerMenuCommand('로그 다운로드', () => downloadLog()));
} }
}; };
@@ -117,10 +161,6 @@
} }
}; };
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// 자동 연속 다운로드 큐 (sessionStorage 기반) // 자동 연속 다운로드 큐 (sessionStorage 기반)
const QUEUE_KEY = 'sbxh6_q'; const QUEUE_KEY = 'sbxh6_q';
const IDX_KEY = 'sbxh6_i'; const IDX_KEY = 'sbxh6_i';
@@ -196,6 +236,9 @@
urls.push(src); urls.push(src);
} }
}); });
if (urls.length < 5) {
log(`getEpisodeImages: img=${imgs.length} urls=${urls.length} (소수만 발견)`);
}
return urls; return urls;
} }
@@ -238,92 +281,151 @@
return { isListPage, isEpisodePage }; return { isListPage, isEpisodePage };
} }
// 이미지의 data-* 속성을 src로 강제 복사 // 모든 img의 data-* 속성을 src로 강제 복사 (알려진 속성명 우선, 이후 모든 data-* 검사)
const forceLoadImages = (root) => { const forceLoadImages = (root) => {
const container = root || document; const container = root || document;
container.querySelectorAll('img').forEach(img => { container.querySelectorAll('img').forEach(img => {
img.setAttribute('loading', 'eager'); img.setAttribute('loading', 'eager');
// 우선 알려진 속성명
['data-src', 'data-original', 'data-lazy-src', 'data-lazy', 'data-srcset'].forEach(attr => { ['data-src', 'data-original', 'data-lazy-src', 'data-lazy', 'data-srcset'].forEach(attr => {
const val = img.getAttribute(attr); const val = img.getAttribute(attr);
if (val && !img.src) img.src = val; if (val && !img.src) img.src = val;
}); });
// 그래도 src가 없으면 모든 data-* 속성 중 http로 시작하는 값 사용
if (!img.src || !img.src.startsWith('http')) {
for (const attr of img.attributes) {
if (attr.name.startsWith('data-') && attr.value && attr.value.startsWith('http')) {
img.src = attr.value;
break;
}
}
}
}); });
}; };
// 강제 scroll 이벤트 디스패치
const fireScroll = () => {
window.dispatchEvent(new Event('scroll', { bubbles: true }));
window.dispatchEvent(new UIEvent('scroll', { detail: 0 }));
};
// 디버그: .vw-imgs 영역 HTML 구조 로그
const debugDumpViewer = (label) => {
try {
const viewer = document.querySelector('.vw-imgs, [class*="vw-imgs"]');
if (!viewer) { log(`${label}: viewer 없음`); return; }
const children = viewer.children;
let info = `${label}: childCount=${children.length}`;
for (let i = 0; i < Math.min(children.length, 5); i++) {
const c = children[i];
info += ` | [${i}] <${c.tagName}> class="${c.className}" style="${c.getAttribute('style') || ''}"`;
if (c.tagName === 'IMG') {
info += ` src="${c.src || '(none)'}" data-src="${c.getAttribute('data-src') || ''}"`;
}
}
log(info);
} catch (_) {}
};
// lazy loading 트리거: data-src 복사 + loading=eager + 스크롤 // lazy loading 트리거: data-src 복사 + loading=eager + 스크롤
const triggerLazyLoading = async () => { const triggerLazyLoading = async (doc, win) => {
const viewer = document.querySelector('.vw-imgs, [class*="vw-imgs"]') || document; const d = doc || document;
// 우선 현재 img들 강제 로딩 const w = win || window;
log(`triggerLazyLoading: scrollY=${w.scrollY}, hidden=${document.hidden}, innerH=${window.innerHeight}`);
debugDumpViewer('triggerLazyLoading 시작');
const viewer = d.querySelector('.vw-imgs, [class*="vw-imgs"]') || d;
forceLoadImages(viewer); forceLoadImages(viewer);
// 동적 스크롤: 새 콘텐츠가 계속 로드되면 scrollHeight도 계속 증가
let prevHeight = 0; let prevHeight = 0;
let stuckCount = 0; let stuckCount = 0;
while (stuckCount < 3) { while (stuckCount < 3) {
const maxScroll = Math.max( const maxScroll = Math.max(
document.documentElement.scrollHeight, d.documentElement.scrollHeight,
document.body.scrollHeight, 0 d.body.scrollHeight, 0
); );
log(`triggerLazyLoading: scroll=${maxScroll}, stuck=${stuckCount}, imgs=${viewer.querySelectorAll('img').length}`);
if (maxScroll === prevHeight) { if (maxScroll === prevHeight) {
stuckCount++; stuckCount++;
} else { } else {
stuckCount = 0; stuckCount = 0;
} }
prevHeight = maxScroll; prevHeight = maxScroll;
// 현재 위치에서 끝까지 step 단위로 스크롤 (느리게)
const step = Math.min(300, maxScroll); const step = Math.min(300, maxScroll);
for (let s = window.scrollY; s <= maxScroll; s += step) { for (let s = w.scrollY; s <= maxScroll; s += step) {
window.scrollTo(0, Math.min(s, maxScroll)); w.scrollTo(0, Math.min(s, maxScroll));
fireScroll();
_setTimeout(fireScroll, 10);
await sleep(300); await sleep(300);
} }
window.scrollTo(0, maxScroll); w.scrollTo(0, maxScroll);
// 스크롤 후 추가된 img들도 강제 로딩 (백그라운드 탭 IO 대체) fireScroll();
forceLoadImages(viewer); forceLoadImages(viewer);
await sleep(1500); await sleep(1500);
} }
// 끝까지 다 내려간 상태에서 여유 대기 + 최종 강제 로딩
forceLoadImages(viewer); forceLoadImages(viewer);
await sleep(2000); await sleep(2000);
window.scrollTo(0, 0); w.scrollTo(0, 0);
fireScroll();
debugDumpViewer('triggerLazyLoading 완료');
log(`triggerLazyLoading: 완료, 최종 imgs=${viewer.querySelectorAll('img').length}`);
await sleep(1000); await sleep(1000);
}; };
// 공통: 이미지 URL 목록을 받아 ZIP 생성 + 다운로드 // viewer 내 이미지 슬롯 전체 개수 (img + 미로딩 placeholder div)
const downloadImagesAsZip = async (imageUrls, seriesName, episodeTitle, episodeNumber) => { const countTotalImgSlots = (root) => {
const zip = new JSZip(); const container = root || document;
const protocolDomain = window.location.origin; const viewers = container.querySelectorAll(
'.vw-imgs, .vw-imgs--double, .vw-imgs--single, ' +
for (let i = 0; i < imageUrls.length; i++) { '.webtoon-page, .manhwa-page, [class*="vw-imgs"]'
const url = imageUrls[i]; );
await new Promise((resolve) => { if (viewers.length === 0) return 0;
GM_xmlhttpRequest({ let total = 0;
method: 'GET', url, responseType: 'arraybuffer', viewers.forEach(v => {
headers: { total += v.querySelectorAll('img').length;
'Referer': protocolDomain, total += v.querySelectorAll(
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' 'div[style*="aspect-ratio"], ' +
}, 'div[class*="placeholder"], ' +
onload: (resp) => { 'div[class*="lazy"], ' +
if (resp.status === 200) { 'div.img-item, ' +
const ext = url.split('.').pop().split('?')[0] || 'jpg'; 'div[class*="img-wrap"]'
zip.file(`image${String(i).padStart(4, '0')}.${ext}`, new Blob([resp.response], { type: 'image/' + ext })); ).length;
} });
resolve(); return total;
},
onerror: () => resolve(),
ontimeout: () => resolve()
});
});
if ((i + 1) % 5 === 0) await sleep(1000);
}
const comicInfo = generateComicInfo(episodeTitle, seriesName, '', episodeNumber, imageUrls.length, imageUrls.length);
zip.file('ComicInfo.xml', comicInfo);
const blob = await zip.generateAsync({ type: "blob" });
const filename = `${seriesName} - ${episodeTitle}.zip`.replace(/[/\\:*?"<>|]/g, '_');
downloadZip(blob, filename);
log(`저장: ${filename} (${imageUrls.length}개)`);
}; };
// 공통: 현재 페이지에서 이미지 획득 + lazy 로딩 트리거 // 첫 번째 img의 URL 패턴으로 모든 이미지 URL 생성 (lazy 로딩 우회)
const generateEpisodeUrls = () => {
try {
const viewer = document.querySelector('.vw-imgs, [class*="vw-imgs"]');
if (!viewer) { log('generateUrls: viewer 없음'); return null; }
const totalSlots = countTotalImgSlots();
if (totalSlots === 0) { log('generateUrls: totalSlots=0'); return null; }
const firstImg = viewer.querySelector('img');
if (!firstImg) { log('generateUrls: img 없음'); return null; }
const src = firstImg.src || firstImg.getAttribute('src') || '';
if (!src || !src.startsWith('http')) { log('generateUrls: 유효한 src 없음'); return null; }
// URL 패턴: /p001.jpg → base 제거
const baseUrl = src.replace(/\/p\d+\.[a-z]+(?:\?.*)?$/i, '/');
const extMatch = src.match(/\.([a-z]+)(?:\?.*)?$/i);
const ext = extMatch ? extMatch[1] : 'jpg';
const numMatch = src.match(/p(\d+)\.[a-z]+/i);
const numDigits = numMatch ? numMatch[1].length : 3;
const urls = [];
for (let i = 1; i <= totalSlots; i++) {
urls.push(`${baseUrl}p${String(i).padStart(numDigits, '0')}.${ext}`);
}
log(`generateUrls: ${baseUrl}${urls.length}개 생성`);
return urls;
} catch (e) {
log('generateUrls 오류:', e);
return null;
}
};
// 공통: 현재 페이지에서 이미지 획득 + lazy 로딩 트리거 + URL 생성 fallback
const getImagesWithLazyLoad = async () => { const getImagesWithLazyLoad = async () => {
let urls = getEpisodeImages(); let urls = getEpisodeImages();
if (urls.length === 0) { if (urls.length === 0) {
@@ -333,14 +435,104 @@
if (urls.length > 0) break; if (urls.length > 0) break;
} }
} }
if (urls.length <= 3) { const prevLen = urls.length;
log(`lazy loading 트리거 (${urls.length}개 → 전체)...`); debugDumpViewer('getImagesWithLazyLoad 시작');
await triggerLazyLoading(); // 우선 페이지 끝까지 fast scroll 1회
const maxScroll = Math.max(
document.documentElement.scrollHeight,
document.body.scrollHeight, 0
);
const hasContent = maxScroll > window.innerHeight * 1.2;
if (hasContent) {
log(`getImagesWithLazyLoad: scrollable(${maxScroll}px) → fast scroll`);
window.scrollTo(0, maxScroll);
fireScroll();
_setTimeout(fireScroll, 10);
await sleep(2000);
forceLoadImages();
urls = getEpisodeImages(); urls = getEpisodeImages();
log(`getImagesWithLazyLoad: fast scroll 후 ${urls.length}`);
} }
// 부족하면 step-by-step lazy 로딩 (최대 3회)
for (let attempt = 0; attempt < 3; attempt++) {
const totalSlots = countTotalImgSlots();
const stillNeed = (
(totalSlots > 0 && urls.length < totalSlots) ||
urls.length <= 3 ||
(prevLen > 0 && urls.length < prevLen * 0.5)
);
log(`getImagesWithLazyLoad: loaded=${urls.length}, totalSlots=${totalSlots}, need=${stillNeed} (attempt ${attempt + 1})`);
if (!stillNeed) break;
log(`getImagesWithLazyLoad: ${urls.length}개 → step scroll (attempt ${attempt + 1})`);
await triggerLazyLoading();
const newUrls = getEpisodeImages();
if (newUrls.length <= urls.length) break;
urls = newUrls;
}
// 모든 data-* 속성 강제 검사
forceLoadImages();
urls = getEpisodeImages();
// 3개 이하면 HTML 덤프
if (urls.length <= 3) debugDumpViewer('getImagesWithLazyLoad 최종');
// 그래도 부족하면 URL 패턴으로 직접 생성 (fallback)
const totalSlots = countTotalImgSlots();
if (urls.length < totalSlots && totalSlots > 3) {
const generated = generateEpisodeUrls();
if (generated && generated.length > urls.length) {
log(`getImagesWithLazyLoad: URL 생성 fallback → ${generated.length}개 (원래 ${urls.length}개)`);
urls = generated;
}
}
log(`getImagesWithLazyLoad: 최종 ${urls.length}`);
return urls; return urls;
}; };
async function downloadImagesAsZip(imageUrls, seriesName, episodeTitle, episodeNumber) {
const zip = new JSZip();
const folderName = `${seriesName}_${episodeNumber}`.replace(/[<>:"/\\|?*]/g, '_').slice(0, 200);
const folder = zip.folder(folderName);
const fetchImage = (url) => new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'GET',
url: url,
responseType: 'blob',
headers: { 'Referer': window.location.origin + '/' },
onload: (res) => {
if (res.status >= 200 && res.status < 300) {
resolve(res.response);
} else {
reject(new Error(`HTTP ${res.status}: ${url}`));
}
},
onerror: (err) => reject(new Error(`GM_xhr 실패: ${url}`))
});
});
const total = imageUrls.length;
for (let i = 0; i < total; i++) {
const url = imageUrls[i];
const ext = url.match(/\.(jpe?g|png|webp|gif|avif)/i)?.[1] || 'jpg';
const filename = `p${String(i + 1).padStart(3, '0')}.${ext}`;
try {
const blob = await fetchImage(url);
folder.file(filename, blob, { binary: true });
} catch (e) {
log(`downloadImagesAsZip: ${filename} 실패 - ${e.message}`);
}
}
const comicInfoXml = generateComicInfo(
episodeTitle, seriesName, '', episodeNumber, total, total
);
folder.file('ComicInfo.xml', comicInfoXml);
const zipBlob = await zip.generateAsync({ type: 'blob' });
const safeName = `${seriesName}_${episodeNumber}.zip`.replace(/[<>:"/\\|?*]/g, '_');
downloadZip(zipBlob, safeName);
log(`downloadImagesAsZip: ${safeName} 저장 완료 (${total}개 중 ${folder.files ? Object.keys(folder.files).length - 1 : '?'}개 성공)`);
}
async function downloadCurrentEpisode() { async function downloadCurrentEpisode() {
try { try {
log('에피소드 다운로드 시작...'); log('에피소드 다운로드 시작...');
@@ -457,16 +649,17 @@
const queue = getQueue(); const queue = getQueue();
if (!queue) return; if (!queue) return;
const { isEpisodePage } = getListPageInfo(); const { isEpisodePage } = getListPageInfo();
if (!isEpisodePage) return; // 목록 페이지에서는 큐 처리 안 함 if (!isEpisodePage) return;
const idx = getQueueIndex(); const idx = getQueueIndex();
if (idx >= queue.length) { cleanupQueue(); return; } if (idx >= queue.length) { cleanupQueue(); return; }
log(`자동 다운로드: ${idx + 1}/${queue.length} - ${queue[idx].title}`); log(`자동 다운로드: ${idx + 1}/${queue.length} - ${queue[idx].title}`);
await sleep(7000); await sleep(5000);
try { try {
const imageUrls = await getImagesWithLazyLoad(); const imageUrls = await getImagesWithLazyLoad();
log(`자동 다운로드: ${idx + 1}/${queue.length} - ${queue[idx].title}, 이미지 ${imageUrls.length}`);
if (imageUrls.length > 0) { if (imageUrls.length > 0) {
const seriesName = sessionStorage.getItem(SERIES_KEY) || getSeriesName(); const seriesName = sessionStorage.getItem(SERIES_KEY) || getSeriesName();
const episodeTitle = getEpisodeTitle() || queue[idx].title; const episodeTitle = getEpisodeTitle() || queue[idx].title;
@@ -500,20 +693,20 @@
registerMenu(); registerMenu();
// 자동 다운로드 큐 확인 (목록→에피소드 이동 시) // 자동 다운로드 큐 확인 (목록→에피소드 이동 시)
setTimeout(processAutoQueue, 1000); _setTimeout(processAutoQueue, 1000);
// Next.js SPA 네비게이션 감지: URL 변경 시 메뉴 재등록 // Next.js SPA 네비게이션 감지: URL 변경 시 메뉴 재등록
const origPushState = history.pushState; const origPushState = history.pushState;
const origReplaceState = history.replaceState; const origReplaceState = history.replaceState;
history.pushState = function () { history.pushState = function () {
origPushState.apply(this, arguments); origPushState.apply(this, arguments);
setTimeout(registerMenu, 500); _setTimeout(registerMenu, 500);
}; };
history.replaceState = function () { history.replaceState = function () {
origReplaceState.apply(this, arguments); origReplaceState.apply(this, arguments);
setTimeout(registerMenu, 500); _setTimeout(registerMenu, 500);
}; };
window.addEventListener('popstate', () => setTimeout(registerMenu, 500)); window.addEventListener('popstate', () => _setTimeout(registerMenu, 500));
log('sbxh6Downloader loaded'); log('sbxh6Downloader loaded');
}; };