Greasy Fork

Greasy Fork is available in English.

Auto somi

자동 복호화/국룰입력/다운(Kiosk, Mega, GoogleDrive, goFile)

< 脚本Auto somi的反馈

提问/评论

§
发表于:2025-05-20

시크릿모드에서 사용할 때에 글의 미리보기 방지 창 안 없어지길래 코드 약간 수정함. 필요하면 써주셈!

코드 고맙다. 정말 잘 쓰고 있음.

밑에 수정된 부분만 적음.

수정된 부분의 코드

PageLoading[0] = 1000;     // 페이지 로딩 시간 조절 (1000당 1초)
Down_Option = 0;           // Kiosk 다운로드 옵션 0:Basic, 1:Fast, 2:일괄 다운로드
// ======================================================================================

요기 밑에 바로 넣었음.


// 미리보기 방지 창 숨기기 또는 자동 클릭 함수

function handleBlockingModals(currentHost) {
    console.log(`[AutoSomi] ${currentHost} 에서 방해 요소 처리 시도...`);

    if (currentHost === 'kone.gg') {
        const nsfwOverlayContainer = document.querySelector('div.relative.min-h-60 > div.absolute.w-full.h-full.backdrop-blur-2xl');
        if (nsfwOverlayContainer && nsfwOverlayContainer.offsetParent !== null) { // 화면에 보일 때만
            const viewContentButton = nsfwOverlayContainer.querySelector('div.flex.gap-4 button:nth-child(2)');
            if (viewContentButton && viewContentButton.textContent?.includes('콘텐츠 보기')) {
                console.log('[AutoSomi] Kone.gg: NSFW "콘텐츠 보기" 버튼 클릭 시도.');
                viewContentButton.click();
                return new Promise(resolve => setTimeout(resolve, 500));
            } else {
                const modalSelectorsKone = [
                    '.age-verification-popup',
                    '.content-overlay.block',
                ];
                modalSelectorsKone.forEach(selector => hideElement(selector));
            }
        }
    } else if (currentHost === 'arca.live') {
        const modalSelectorsArca = [
            { selector: '.adult-confirm-modal', action: 'hide' },
            { selector: '.fc-dialog', action: 'hide' },
            { selector: '#preview-block-layer', action: 'hide' },
            { selector: 'div[class*="adult-channel-confirm"]', action: 'hide' }, // 먼저 숨기고
            { selector: 'div.modal[data-id="confirmAdult"] div.modal-footer button.btn-primary', action: 'click'}, // 성인 확인 모달의 확인 버튼
            { selector: 'button.btn-primary.btn.text-light[data-bs-dismiss="modal"]', action: 'click' } // 일반적인 "네, 확인했습니다" 버튼
        ];
        modalSelectorsArca.forEach(item => {
            const elements = document.querySelectorAll(item.selector);
            elements.forEach(element => {
                if (element && element.offsetParent !== null) {
                    if (item.action === 'click') {
                        console.log(`[AutoSomi] Arca.live: "${item.selector}" 버튼 클릭 시도.`);
                        element.click();
                    } else {
                        hideElement(item.selector);
                    }
                }
            });
        });
    }

    function hideElement(selector) {
        try {
            const elements = document.querySelectorAll(selector);
            if (elements.length > 0) {
                elements.forEach(el => {
                    if (el.offsetParent !== null) {
                        el.style.setProperty('display', 'none', 'important');
                        console.log(`[AutoSomi] 요소 숨김 처리:`, el);
                    }
                });
            }
        } catch (e) {
            console.error(`[AutoSomi] 선택자 "${selector}" 처리 중 오류:`, e);
        }
    }
    return Promise.resolve();
}
§
发表于:2025-05-20
编辑于:2025-05-20

혹시 모르니까 전체 코드도 넣어둠.

'use strict';
let chkp = [,,,, atob('c29taXNvZnQ=')], Down_Option, PageLoading = [], isT = [,,], MenuID = [null, null], host = document.URL.split('/')[2], npw = [], pw = [atob('c29taXNvZnQ='),atob('MjAyNXNvbWlzb2Z0'),
// =============================== Settings =======================================
// 추가하길 원하는 비밀번호 따옴표 - 쉼표로 구분해서 바로 아래줄에 넣으면 됨 ex) '1234', '2024국룰', '!국룰!'

];
PageLoading[0] = 1000;     // 페이지 로딩 시간 조절 (1000당 1초)
Down_Option = 0;           // Kiosk 다운로드 옵션 0:Basic, 1:Fast, 2:일괄 다운로드
// ======================================================================================

// 미리보기 방지 창 숨기기 또는 자동 클릭 함수
function handleBlockingModals(currentHost) {
    console.log(`[AutoSomi] ${currentHost} 에서 방해 요소 처리 시도...`);

    if (currentHost === 'kone.gg') {
        const nsfwOverlayContainer = document.querySelector('div.relative.min-h-60 > div.absolute.w-full.h-full.backdrop-blur-2xl');
        if (nsfwOverlayContainer && nsfwOverlayContainer.offsetParent !== null) { // 화면에 보일 때만
            const viewContentButton = nsfwOverlayContainer.querySelector('div.flex.gap-4 button:nth-child(2)');
            if (viewContentButton && viewContentButton.textContent?.includes('콘텐츠 보기')) {
                console.log('[AutoSomi] Kone.gg: NSFW "콘텐츠 보기" 버튼 클릭 시도.');
                viewContentButton.click();
                return new Promise(resolve => setTimeout(resolve, 500));
            } else {
                const modalSelectorsKone = [
                    '.age-verification-popup',
                    '.content-overlay.block',
                ];
                modalSelectorsKone.forEach(selector => hideElement(selector));
            }
        }
    } else if (currentHost === 'arca.live') {
        const modalSelectorsArca = [
            { selector: '.adult-confirm-modal', action: 'hide' },
            { selector: '.fc-dialog', action: 'hide' },
            { selector: '#preview-block-layer', action: 'hide' },
            { selector: 'div[class*="adult-channel-confirm"]', action: 'hide' }, // 먼저 숨기고
            { selector: 'div.modal[data-id="confirmAdult"] div.modal-footer button.btn-primary', action: 'click'}, // 성인 확인 모달의 확인 버튼
            { selector: 'button.btn-primary.btn.text-light[data-bs-dismiss="modal"]', action: 'click' } // 일반적인 "네, 확인했습니다" 버튼
        ];
        modalSelectorsArca.forEach(item => {
            const elements = document.querySelectorAll(item.selector);
            elements.forEach(element => {
                if (element && element.offsetParent !== null) {
                    if (item.action === 'click') {
                        console.log(`[AutoSomi] Arca.live: "${item.selector}" 버튼 클릭 시도.`);
                        element.click();
                    } else {
                        hideElement(item.selector);
                    }
                }
            });
        });
    }

    function hideElement(selector) {
        try {
            const elements = document.querySelectorAll(selector);
            if (elements.length > 0) {
                elements.forEach(el => {
                    if (el.offsetParent !== null) {
                        el.style.setProperty('display', 'none', 'important');
                        console.log(`[AutoSomi] 요소 숨김 처리:`, el);
                    }
                });
            }
        } catch (e) {
            console.error(`[AutoSomi] 선택자 "${selector}" 처리 중 오류:`, e);
        }
    }
    return Promise.resolve();
}


async function toggleDown(){
    isT[0]=!isT[0];
    if(!isT[0] && isT[1]){
        isT[1]=false;
        await GM.setValue('isT[1]', isT[1]);
    }
    await GM.setValue('isT[0]', isT[0]);
    updateDown();
    updateTab();
}
async function toggleTab(){
    isT[1]=!isT[1];
    if(!isT[0] && isT[1]){
        isT[0]=true;
        await GM.setValue('isT[0]', isT[0]);
    }
    await GM.setValue('isT[1]', isT[1]);
    updateDown();
    updateTab();
}
function updateDown(){
    if(MenuID[0] !==null)GM_unregisterMenuCommand(MenuID[0]);
    MenuID[0]=GM_registerMenuCommand(`자동 다운로드  ${isT[0] ? 'ON' : 'OFF'}`, toggleDown, { autoClose: false, title: `자동 다운로드 ${isT[0] ? '켜짐' : '꺼짐'}`});
}
function updateTab(){
    if(MenuID[1] !==null)GM_unregisterMenuCommand(MenuID[1]);
    MenuID[1]=GM_registerMenuCommand(`자동 탭 닫기  ${isT[1] ? 'ON' : 'OFF'}`, toggleTab, { autoClose: false, title: `자동 탭 닫기 ${isT[1] ? '켜짐' : '꺼짐'}`});
}
function doDec() {
    if (chkp[3] !== chkp[4]) return;

    let targets = [];

    if (host === 'arca.live') {
        targets = [
            document.querySelector('body div.article-body > div.fr-view.article-content'),
            ...document.querySelectorAll('div.article-comment#comment div.comment-content, div.article-comment div.comment-content')
        ].filter(el => el !== null);
    } else if (host === 'kone.gg') {
        const base = document.querySelector('div.prose.prose-invert');
        const comments = document.querySelectorAll('p.text-sm.max-w-xl.whitespace-pre-wrap');
        const listItems = document.querySelectorAll('ol.list-decimal li p');
        targets = [base, ...comments, ...listItems].filter(el => el !== null);
    }

    function dec(target, reg) {
        try {
            if (!target || !target.innerHTML) return;
            const original = target.innerHTML;
            const matches = [...original.matchAll(reg)];
            if (matches.length === 0) return;

            let result = original;
            for (const match of matches) {
                let encoded = match[0];
                let decoded = encoded;
                try {
                    while (decoded && typeof decoded === 'string' && !decoded.startsWith('http') && decoded.length > 10 && decoded.length < 1000) {
                        let tempDecoded = atob(decoded);
                        if (tempDecoded === decoded) break;
                        decoded = tempDecoded;
                    }
                    if (decoded && typeof decoded === 'string' && decoded.startsWith('http')) {
                        const linkHTML = `<a href="${decoded}" target="_blank" rel="noreferrer" style="color:#007bff; text-decoration:underline; word-break:break-all;">${decoded}</a>`;
                        result = result.replace(encoded, linkHTML);
                    }
                } catch (e) {
                    // console.log('개별 복호화 실패:', encoded, e.message);
                }
            }
            if (target.innerHTML !== result) {
                target.innerHTML = result;
            }
        } catch (e) {
            console.log('dec 함수 에러:', e, target);
        }
    }

    for (const target of targets) {
        if (!target) continue;
        const links = target.querySelectorAll('a');
        links.forEach(a => {
            a.setAttribute('rel', 'noreferrer');
        });

        dec(target, /aHR0c[0-9A-Za-z+/=]{8,}/g);
        dec(target, /YUhSMG[0-9A-Za-z+/=]{8,}/g);
        dec(target, /WVVoU[0-9A-Za-z+/=]{8,}/g);
        dec(target, /V1ZWb[0-9A-Za-z+/=]{8,}/g);
    }
    setTimeout(doDlsiteContextAware, 100);
}




function doDlsiteContextAware() {
    let atc;
    if (host === 'arca.live') {
        atc = document.querySelector('.article-body .article-content');
    } else if (host === 'kone.gg') {
        atc = document.querySelector('div.prose.prose-invert');
    }
    if (!atc) return;

    let titleEl;
    if (host === 'arca.live') {
        titleEl = document.querySelector('.title-row .title') || document.querySelector('.board-title .title');
    } else if (host === 'kone.gg') {
        titleEl = [...document.querySelectorAll('h1')].find(el =>
            el.textContent?.match(/RJ[0-9]{6,10}/i)
        );
    }

    const keywordPattern = /(꺼|거|퍼|RJ|rj|Rj|rJ|VJ|vj|Vj|vJ|DL|dl|Dl|dL)[\s:()\[\]#-]*([0-9]{6,10})/g;
    const fullRJPattern = /\b(RJ|rj|Rj|rJ|VJ|vj|Vj|vJ|퍼|꺼|거|DL|dl|Dl|dL)([0-9]{6,10})\b/g;

    let titleText = '';
    if (titleEl?.childNodes) {
        titleText = Array.from(titleEl.childNodes)
            .map(n => n.textContent?.trim() || '')
            .join(' ');
    }

    const bodyText = atc.textContent || '';
    const fullText = titleText + '\n' + bodyText;

    const matchList1 = [...fullText.matchAll(keywordPattern)].map(m => ({ prefix: m[1], code: m[2] }));
    const matchList2 = [...fullText.matchAll(fullRJPattern)].map(m => ({ prefix: m[1], code: m[2] }));

    const linkCodes = Array.from(atc.querySelectorAll('a[href]'))
        .map(a => {
            const match = a.href.match(/(RJ|VJ)([0-9]{6,10})/i);
            return match ? { prefix: match[1].toUpperCase(), code: match[2] } : null;
        })
        .filter(Boolean);

    const splitNodeMatches = [];
    const allNodes = [...atc.querySelectorAll('*:not(script):not(style):not(a)')];
    const validPrefixes = ['꺼','거','퍼','RJ','rj','Rj','rJ','VJ','vj','Vj','vJ','DL','dl','Dl','dL'];

    for (const node of allNodes) {
        const children = [...node.childNodes];
        for (let i = 0; i < children.length - 1; i++) {
            const a = children[i], b = children[i + 1];
            if (a.nodeType !== Node.TEXT_NODE || b.nodeType !== Node.TEXT_NODE) continue;

            const aText = (a.textContent || '').replace(/\s+/g, '');
            const bText = (b.textContent || '').trim();
            if (!/^\d{6,10}$/.test(bText)) continue;
            for (const prefix of validPrefixes) {
                if (aText.endsWith(prefix)) {
                    splitNodeMatches.push({ prefix, code: bText });
                    break;
                }
            }
        }
    }

    const extraFromTitle = [];
    const matchInTitleStart = titleText.match(/^[\[]?([0-9]{6,10})[\]]?/);
    if (matchInTitleStart) extraFromTitle.push({ prefix: 'RJ', code: matchInTitleStart[1] });

    const allCodes = [
        ...matchList1,
        ...matchList2,
        ...linkCodes,
        ...splitNodeMatches,
        ...extraFromTitle
    ];

    const seen = new Set();
    const uniqueCodes = allCodes.filter(({ code }) => {
        if (!code || seen.has(code)) return false;
        seen.add(code);
        return true;
    });

    if (uniqueCodes.length === 1) {
        const { code, prefix } = uniqueCodes[0];
        if (!code) return;

        const mappedPrefix = ['vj', 'vJ', 'Vj', 'VJ', '퍼'].includes(prefix.toLowerCase()) ? 'VJ'
                            : ['rj', 'rJ', 'Rj', 'RJ', '꺼', '거', 'dl', 'dL', 'Dl', 'DL'].includes(prefix.toLowerCase()) ? 'RJ'
                            : prefix.toUpperCase();

        const fullCode = `${mappedPrefix}${code}`;
        const link = `https://www.dlsite.com/maniax/work/=/product_id/${fullCode}.html`;

        const existing = atc.querySelector('.dlsite-link-appended');
        if (existing) existing.remove();

        const wrapper = document.createElement('div');
        wrapper.className = 'dlsite-link-appended';
        wrapper.style.marginTop = '15px';
        wrapper.style.padding = '10px 0';
        wrapper.style.borderTop = '1px dashed #aaa';

        const a = document.createElement('a');
        a.href = link;
        a.target = '_blank';
        a.rel = 'noreferrer';
        a.textContent = `[DLsite] ${fullCode}`;
        a.style.display = 'block';
        a.style.marginBottom = '5px';
        a.style.color = '#1e90ff';

        wrapper.appendChild(a);
        atc.appendChild(wrapper);
        return;
    }

    const combinedPattern = new RegExp(`${keywordPattern.source}|${fullRJPattern.source}`, 'gi');

    const walk = (node) => {
        if (node.nodeType === Node.TEXT_NODE) {
            const text = node.textContent;
            if (!text) return;
            let lastIndex = 0;
            let match;
            const frag = document.createDocumentFragment();

            while ((match = combinedPattern.exec(text)) !== null) {
                const before = text.slice(lastIndex, match.index);
                const number = match[2] || match[4];
                const prefix = (match[1] || match[3] || '').toLowerCase();
                const mappedPrefix = ['vj', 'vJ', 'Vj', 'VJ', '퍼'].includes(prefix) ? 'VJ'
                                    : ['rj', 'rJ', 'Rj', 'RJ', '꺼', '거', 'dl', 'dL', 'Dl', 'DL'].includes(prefix) ? 'RJ'
                                    : prefix.toUpperCase();
                const fullCode = `${mappedPrefix}${number}`;

                const a = document.createElement('a');
                a.href = `https://www.dlsite.com/maniax/work/=/product_id/${fullCode}.html`;
                a.textContent = match[0];
                a.target = '_blank';
                a.rel = 'noreferrer';
                a.style.color = '#1e90ff';

                if (before) frag.appendChild(document.createTextNode(before));
                frag.appendChild(a);
                lastIndex = match.index + match[0].length;
            }

            if (lastIndex < text.length) {
                frag.appendChild(document.createTextNode(text.slice(lastIndex)));
            }

            if (frag.childNodes.length > 0 && node.parentNode) {
                 node.parentNode.replaceChild(frag, node);
            }
        } else if (
            node.nodeType === Node.ELEMENT_NODE &&
            node.tagName &&
            !['A', 'SCRIPT', 'STYLE'].includes(node.tagName.toUpperCase())
        ) {
            for (const child of [...node.childNodes]) {
                walk(child);
            }
        }
    };

    walk(atc);
}




async function chkPW(){
    chkp[3]=await GM.getValue('chkp[3]');
    isT[0]=await GM.getValue('isT[0]', true);
    isT[1]=await GM.getValue('isT[1]', false);
    updateDown();
    updateTab();

    if(host=='arca.live' || host=='kone.gg'){
        if(chkp[3] !=chkp[4]){
            const chk=prompt(decodeURI(atob('JUVBJUI1JUFEJUVCJUEzJUIwJUVEJTk5JTk1JUVDJTlEJUI4')));
            if(chk?.toLowerCase()==chkp[4]) await GM.setValue('chkp[3]', chkp[4]);
            else {
                GM.setValue('chkp[3]', false);
                alert(decodeURI(atob('JUVBJUI1JUFEJUVCJUEzJUIwJUVDJTlEJUI0JTIwJUVDJTlEJUJDJUVDJUI5JTk4JUVEJTk1JTk4JUVDJUE3JTgwJTIwJUVDJTk1JThBJUVDJThBJUI1JUVCJThCJTg4JUVCJThCJUE0')));
            }
        }
    }
}
async function inputPW() {
    let inputElem = document.querySelector(chkp[0]), btnElem = document.querySelector(chkp[1]);
    if (!inputElem ) {
        if (isT[0] === true && !document.querySelector('.files-list, #download-section')) {
             await setTimeout(DBtn, PageLoading[1] || 1000);
        }
        return;
    }

    const combinedPw = [...new Set([...pw, ...npw])];

    if (chkp[3] == chkp[4]) {
        try {
            for (let i = 0; i < combinedPw.length; i++) {
                if (!combinedPw[i]) continue;
                if (!inputElem) break;

                inputElem.value = combinedPw[i];

                if (host == 'kio.ac') {
                    inputElem.dispatchEvent(new Event('input', { bubbles: true }));
                    inputElem.dispatchEvent(new Event('change', { bubbles: true }));
                    await new Promise(res => setTimeout(res, 50));
                    if(btnElem) btnElem.click();
                } else {
                    if(btnElem) btnElem.click();
                    else {
                        const enterEvent = new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true });
                        inputElem.dispatchEvent(enterEvent);
                    }
                }

                await new Promise(res => setTimeout(res, 800));

                const successIndicator = document.querySelector('.files-list, #download-section, .download-link, .btn-download, .main-button-download');
                const errorIndicator = document.querySelector('.text-error, .text-red-500, .error-message, .incorrect-password, [class*="error"], [id*="error"]');

                if (successIndicator && successIndicator.offsetParent !== null) {
                    break;
                } else if (errorIndicator && errorIndicator.offsetParent !== null) {
                    if (inputElem) inputElem.value = '';
                }
            }
            if (isT[0] == true) await setTimeout(DBtn, PageLoading[1] || 1000);

        } catch (e) {
            console.error("암호 입력 중 오류:", e);
            if (isT[0] == true) await setTimeout(DBtn, PageLoading[1] || 1000);
        }
    }
}

async function kioskdone(){
    try {
        await new Promise(res=> setTimeout(res, 3000));
        for(var i=0, jj=0; jj!=1 && i < 60; i++){
            await new Promise(res=> setTimeout(res, 1000));
            if(document.querySelector('.flex.flex-row.text-xs.justify-between div:nth-child(2)')?.innerText.toLowerCase()=='done'){
                await setTimeout(()=> { window.open('', '_self').close()}, 2000);
                jj++;
                break;
            }
        }
    } catch(e){
        console.error("kioskdone 오류:", e);
        if(isT[1]==true && isT[2]==true) setTimeout(()=> { window.open('', '_self').close()}, 1000);
    }
}
async function DBtn(){
    if(isT[0] !== true) return;

    if(host=='mega.nz') {
        try {
            const resumeButton = document.querySelector('.mega-button.positive.resume.js-resume-download');
            if (resumeButton) {
                resumeButton.click();
                await new Promise(res => setTimeout(res, 500));
            }

            const standardDownloadButton = document.querySelector('.mega-button.positive.js-default-download.js-standard-download');
            if (standardDownloadButton) {
                standardDownloadButton.click();
                await new Promise(res => setTimeout(res, 2000));
            }

            const continueDownloadButton = document.querySelector('.mega-button.large.positive.download.continue-download');
            if (continueDownloadButton) {
                continueDownloadButton.click();
            }
        } catch(e) {
            console.error("Mega 다운로드 버튼 클릭 오류:", e);
        }
    } else {
        try {
            let btns = document.querySelectorAll(chkp[2]);
            let delayMultiplier = (PageLoading[0] || 1000) + 600;
            if(btns.length > 1){
                btns.forEach((btn, index) => {
                    setTimeout(() => {
                        btn.click();
                    }, index * delayMultiplier);
                });
            } else if(btns.length === 1){
                btns[0].click();
            }
        } catch(e){ console.error("DBtn 일반 다운로드 버튼 클릭 오류:", e); }
    }

    if(isT[1]==true && isT[2]==true){
        let btnsForDelay = document.querySelectorAll(chkp[2]);
        let totalDelay = (btnsForDelay.length > 1) ? (btnsForDelay.length * ((PageLoading[0] || 1000) + 600) + 700) : 1300;
        if(host=='kiosk.ac'){
            setTimeout(()=> { kioskdone(); }, totalDelay);
        } else if(host=='kio.ac'){
            setTimeout(()=> { window.open('', '_self').close()}, totalDelay+1000);
        } else {
            setTimeout(()=> { window.open('', '_self').close()}, totalDelay);
        }
    }
}
function FindPW(){
    let atc;
    if (host === 'arca.live') {
        atc = document.querySelector('body div.article-body > div.fr-view.article-content');
    } else if (host === 'kone.gg') {
        atc = document.querySelector('div.prose.prose-invert');
    }
    if (!atc || !atc.innerHTML) return;

    let tempContent = atc.innerHTML;
    tempContent=tempContent.replace(/ /g, ' ').replace(/( ){2,}/g, ' '); // nbsp 및 연속 공백 처리
    tempContent=tempContent.replace(/국룰/g, 'ㄱㄹ');

    let regexx=/(대문자)/;

    if(regexx.test(tempContent)) {
        const smpeopleUpper = atob('U01QRU9QTEU=');
        if (npw.indexOf(smpeopleUpper) === -1) npw.push(smpeopleUpper);
    }

    function dec(reg){ // FindPW 내부의 dec 함수
        try {
            let currentLoopContent = tempContent;
            const processedTexts = new Set();

            while(true){
                const matchResult = reg.exec(currentLoopContent);
                if (!matchResult) break;

                let matchedText = matchResult[0];
                if (processedTexts.has(matchedText)) {
                    currentLoopContent = currentLoopContent.replace(matchedText, `__SKIPPED_${Math.random().toString(36).substring(2, 10)}__`);
                    continue;
                }

                let DECed = matchedText.replace(/(ㄱㄹ)/g, '국룰');
                let DECedd = DECed.replace(/\s|[+]|(은|는|이|가)|(전부)|(대문자로)|(대문자)|(비밀번호)|(패스워드)|(비번)|(ㅂㅂ)|(암호)|(ㅇㅎ)|(키오스크맘)|(키오스크)|(입니다)|(이고)|(이며)|(임다)|(같다)|(처럼)|(틀리다)|(입니다요)/g, '');
                DECedd = DECedd.split(/[(입)(임)(이)(이)(이)(입)(임)(같)(처)(틀)]/g)[0];
                DECedd = DECedd.replace(/[<>]/g, '');

                let dat;
                if (host === 'arca.live') {
                    const dateEl = document.querySelector('.article-info .date .body');
                    // 오류 방지를 위해 dateEl 및 innerText 존재 여부 확인 강화
                    if (dateEl && typeof dateEl.innerText === 'string' && dateEl.innerText.trim() !== '') {
                        dat = dateEl.innerText.split(' ')[0];
                    } else {
                        // console.warn("[AutoSomi] Arca.live: 날짜 정보를 포함하는 요소를 찾지 못했거나 내용이 없습니다.");
                        dat = undefined; // dat를 명시적으로 undefined로 설정
                    }
                }

                let regexa=/(오늘)|(날짜)|(날자)/g;
                if(dat && regexa.test(DECedd)){ // dat가 유효할 때만 날짜 기반 암호 생성
                    DECedd=DECedd.replace(regexa, '');
                    const dateParts = dat.split(/\-/g);
                    if (dateParts.length === 3) {
                        const year = dateParts[0].slice(2);
                        const month = dateParts[1];
                        const day = dateParts[2];
                        let dateFormats=[month + day, month + '-' + day, year + month + day, dat.replace(/-/g,'')];
                        for(let k=0;k<dateFormats.length;k++){
                            const finalPw = DECedd.replace(/국룰/g,chkp[4]) + dateFormats[k];
                            if(finalPw.length > 2 && npw.indexOf(finalPw)=='-1') npw.push(finalPw);
                        }
                    }
                } else {
                    const finalPw = DECedd.replace(/국룰/g,chkp[4]);
                    if(finalPw && finalPw.length > 2 && npw.indexOf(finalPw)=='-1') npw.push(finalPw);
                }
                processedTexts.add(matchedText);
                currentLoopContent = currentLoopContent.replace(matchedText, `__PROCESSED_${Math.random().toString(36).substring(2, 15)}__`);
            }
            GM.setValue('npw', npw);
        } catch(e){ console.error("FindPW dec 함수 오류:", e); }
    }
    dec(/[(<p>\s*)*]{0,}[ㄱ-ㅣ가-힣0-9A-Za-z\s~`!^\_+@\#$%&=]{0,}(ㄱㄹ){1,1}[ㄱ-ㅣ가-힣0-9A-Za-z\s~`!^\_+@\#$%&=]{0,}[(\s*</p>)*]{0,}/);
    setTimeout(aaa, 100);
}

function waitForKoneContent() {
    let attempts = 0;
    const maxAttempts = 20;
    const checkInterval = setInterval(async () => {
        attempts++;
        await handleBlockingModals(host);

        const atc = document.querySelector('div.prose.prose-invert');
        const titleEl = [...document.querySelectorAll('h1.flex, h1.text-xl')].find(el =>
            /RJ[0-9]{6,10}|VJ[0-9]{6,10}/i.test(el.textContent || '')
        );

        const hasBase64 = atc && /aHR0c|YUhSMG|WVVoU|V1ZWb/.test(atc.textContent || '');

        if (atc && (titleEl || hasBase64) && (atc.textContent || '').length > 10) {
            clearInterval(checkInterval);
            FindPW();
            setTimeout(() => {
                doDec();
                doDlsiteContextAware();
            }, 300);
        } else if (attempts >= maxAttempts) {
            clearInterval(checkInterval);
        }
    }, 300);
}



async function aaa() {
    const saved = await GM.getValue('npw');
    if (Array.isArray(saved)) {
        npw = [...new Set([...npw, ...saved])];
    }
}


// === 스크립트 시작 지점 ===
(async () => {
    await chkPW();
    await handleBlockingModals(host);

    if (host === 'arca.live') {
        FindPW();
        setTimeout(doDec, 200);
    } else if (host === 'kone.gg') {
        waitForKoneContent();
    }

    if(host=='kio.ac'){
        await aaa();
        chkp[0]='.overflow-auto.max-w-full.max-h-full.flex-grow.p-1 input:nth-of-type(1)';
        chkp[1]='.flex.flex-col-reverse button:nth-of-type(1)';
        chkp[2]='.p-2.align-middle .flex.align-middle button:nth-of-type(1)';
        isT[2]=true;
        PageLoading[1]=3500;
        setTimeout(inputPW, (PageLoading[0] || 1000) + 2000);
    }
    if(host=='mega.nz'){
        await aaa();
        chkp[0]='#password-decrypt-input';
        chkp[1]='.mega-button.positive.fm-dialog-new-folder-button.decrypt-link-button';
        chkp[2]='.mega-button.positive.js-default-download.js-standard-download';
        PageLoading[1]=4000;
        isT[2]=false;
        setTimeout(inputPW, (PageLoading[0] || 1000) + 1800);
    }
    if(host=='kiosk.ac'){
        await aaa();
        chkp[0]='.input.shadow-xl.flex-grow';
        chkp[1]='.btn.btn-ghost.w-full.mt-2.rounded-md';
        if(Down_Option==2)
            chkp[2]='.flex.justify-between.w-full .flex.gap-2 .btn.btn-ghost';
        else
            chkp[2]='#vexplorer-body .hover\\:bg-neutral .dropdown button, #vexplorer-body > div > div > div.flex.justify-between.w-full > div.flex.gap-2 > button:not(.btn-disabled)';

        if(Down_Option==0)
            isT[2]=true;
        else
            isT[2]=false;
        PageLoading[1]=3000;
        setTimeout(inputPW, (PageLoading[0] || 1000));
    }
    if(host=='workupload.com'){
        await aaa();
        chkp[0]='#passwordprotected_file_password';
        chkp[1]='#passwordprotected_file_submit';
        chkp[2]='a.btn.btn-prio[href*="/file/"]';
        if(Down_Option==0)
            isT[2]=true;
        else
            isT[2]=false;
        PageLoading[1]=2000;
        setTimeout(inputPW, (PageLoading[0] || 1000));
    }
    if(host=='drive.google.com'){
        await aaa();
        if(document.URL.includes('/file/d/')){
            const fileId = document.URL.split('/d/')[1].split('/')[0];
            if (fileId) {
                window.location.href=`https://drive.usercontent.google.com/download?id=${fileId}&export=download&authuser=0`;
            }
        }
        if(document.URL.includes('/drive/folders/')){
            setTimeout(()=> {
                if(isT[0]==true) {
                    const downloadAllButton = document.querySelector('div[aria-label="모두 다운로드"], div[data-tooltip="모두 다운로드"]');
                    if (downloadAllButton) {
                        downloadAllButton.click();
                    } else {
                        const firstItemDownloadButton = document.querySelector('div[role="gridcell"][data-is-shared="false"] div[aria-label*="다운로드"]');
                         if(firstItemDownloadButton) {
                            firstItemDownloadButton.click();
                         }
                    }
                }
            }, (PageLoading[0] || 1000) + 1500);

            chkp[2]='.h-De-Vb.h-De-Y';
            PageLoading[1]=1;
            isT[2]=true;
            setTimeout(()=> { if(isT[0]==true) setTimeout(DBtn, 3500);}, (PageLoading[0] || 1000));
        }
    }
    if(host=='drive.usercontent.google.com'){
        await aaa();
        chkp[2]='form[method="POST"] button[type="submit"], input[type="submit"][value="다운로드"], button.jfk-button-action';
        isT[2]=true;
        setTimeout(()=> { if(isT[0]==true) DBtn();}, 100);
    }
    if(host=='gofile.io'){
        await aaa();
        chkp[0]='#filesErrorPasswordInput';
        chkp[1]='#filesErrorPasswordButton';
        chkp[2]='button.btn-download, a.btn-download, #rowFolderCenter button[data-bs-target="#filesList"] + div .btn-outline-secondary';
        PageLoading[1]=3000;
        isT[2]=true;
        setTimeout(inputPW, (PageLoading[0] || 1000));
    }
})();


// Kone.gg 특화 로직 (IIFE - 즉시 실행 함수)
(function () {
    'use strict';
    if (location.host !== 'kone.gg') return;

    function hookDecodeTriggerOnButton() {
        const container = document.querySelector('div.flex.items-center.justify-between.p-4');
        if (!container) return;

        const button = container.querySelector('button[data-slot="button"]');
        if (!button || button.dataset._somi_hooked === '1') return;

        button.dataset._somi_hooked = '1';

        button.addEventListener('click', async () => {
            await handleBlockingModals(host);
            setTimeout(() => {
                FindPW();
                setTimeout(() => {
                    doDec();
                    doDlsiteContextAware();
                }, 300);
            }, 500);
        });
    }

    hookDecodeTriggerOnButton();

    const observer = new MutationObserver(async () => {
        hookDecodeTriggerOnButton();
        await handleBlockingModals(host);
    });
    observer.observe(document.body, { childList: true, subtree: true });
})();

(function () {
    'use strict';
    if (location.host !== 'kone.gg') return;

    let lastUrl = location.href;

    const observer = new MutationObserver(async () => {
        const currentUrl = location.href;
        if (currentUrl !== lastUrl) {
            lastUrl = currentUrl;
            await handleBlockingModals(host);
            observeAndRunKoneFunctions();
        }
    });

    observer.observe(document.body, { childList: true, subtree: true });

    async function observeAndRunKoneFunctions() {
        const start = Date.now();
        const timeout = 8000;

        const timer = setInterval(async () => {
            await handleBlockingModals(host);
            const atc = document.querySelector('div.prose.prose-invert');
            const hasText = atc && (atc.textContent || '').length > 20;
            const hasEncoded = atc && /aHR0c|YUhSMG|WVVoU|V1ZWb/.test(atc.textContent || '');

            if (hasText && (hasEncoded || document.querySelector('a[href*="dlsite.com"]'))) {
                clearInterval(timer);
                FindPW();
                setTimeout(() => {
                    doDec();
                    doDlsiteContextAware();
                }, 300);
            }

            if (Date.now() - start > timeout) {
                clearInterval(timer);
            }
        }, 300);
    }

    (async () => {
        await handleBlockingModals(host);
        observeAndRunKoneFunctions();
    })();
})();

发表回复

登录以发表回复。