// UserScript
// @name Grok Files Auto Delete with Pause Button 2
// @namespace http://tampermonkey.net/
// @version 1.2
// @description grok.com/files에서 자동 삭제 + 화면에 Pause/Resume 버튼 표시
// @author Grok Helper
// @match https://grok.com/files?sort=size&fileType=image&createdBy=user
// @grant none
// @run-at document-end
// /UserScript

(function() {
'use strict';

⎗
✓
let isPaused = false;
let deleteInterval = null;
let emptyCheckDone = false;
let isEmpty = false;
let count = 0;
let reCount = 0;
// 이전에 삭제한 파일 이름 저장
let lastDeletedFileName = "";

console.log("🚀 Grok Files Auto Delete with Pause 버튼 스크립트 시작!");

// Pause/Resume 버튼을 화면에 추가하는 함수
function addPauseButton() {
    if (document.getElementById('grok-pause-btn')) return;

    const btn = document.createElement('button');
    btn.id = 'grok-pause-btn';
    btn.style.position = 'fixed';
    btn.style.top = '80px';
    btn.style.right = '20px';
    btn.style.zIndex = '99999';
    btn.style.padding = '12px 20px';
    btn.style.backgroundColor = '#ff4444';
    btn.style.color = 'white';
    btn.style.border = 'none';
    btn.style.borderRadius = '8px';
    btn.style.fontSize = '16px';
    btn.style.cursor = 'pointer';
    btn.style.boxShadow = '0 4px 12px rgba(0,0,0,0.3)';
    btn.textContent = '⏸️ Pause';

    btn.addEventListener('click', () => {
        isPaused = !isPaused;
        if (isPaused) {
            btn.textContent = '▶️ Resume';
            btn.style.backgroundColor = '#44aa44';
            console.log("⏸️ 삭제 일시정지됨");
        } else {
            btn.textContent = '⏸️ Pause';
            btn.style.backgroundColor = '#ff4444';
            console.log("▶️ 삭제 재개됨");
        }
    });

    document.body.appendChild(btn);
}

// 빈 화면 감지 알림 표시
function showEmptyAlert() {
    if (document.getElementById('grok-empty-alert')) return;

    const alertBox = document.createElement('div');
    alertBox.id = 'grok-empty-alert';
    alertBox.style.position = 'fixed';
    alertBox.style.top = '140px';
    alertBox.style.right = '20px';
    alertBox.style.zIndex = '99999';
    alertBox.style.padding = '15px 20px';
    alertBox.style.backgroundColor = '#cc0000';
    alertBox.style.color = 'white';
    alertBox.style.borderRadius = '8px';
    alertBox.style.boxShadow = '0 4px 15px rgba(0,0,0,0.4)';
    alertBox.style.maxWidth = '300px';
    alertBox.style.fontSize = '15px';
    alertBox.innerHTML = `
        ⚠️ <b>빈 화면 감지됨</b><br>
        파일 목록이 로드되지 않았습니다.<br>
        <b>Images 캐시를 지우고</b> 다시 시도하세요.<br>
        <small>Ctrl + Shift + R (강력 새로고침) 추천</small>
    `;

    document.body.appendChild(alertBox);

    // 15초 후 자동 사라짐
    setTimeout(() => {
        if (alertBox.parentNode) alertBox.parentNode.removeChild(alertBox);
    }, 15000);
}

// 파일 이름 추출 함수 (파일명 부분 가져오기)
function getFileName(item) {
    const nameElement = item.querySelector('span[style*="mask-image"]') ||
                        item.querySelector('span') ||
                        item;
    return nameElement ? nameElement.innerText.trim() : "";
}


// 빈 화면인지 검사하는 함수
function checkIfEmptyScreen() {
    if (emptyCheckDone) return;
    emptyCheckDone = true;

    // 파일 목록이 있을 법한 컨테이너나 파일 아이템을 찾음
    const fileItems = document.querySelectorAll('div[data-testid^="file-"], .file-item, button[aria-label="Delete file"], img[src*="upload"]');
    const hasFiles = fileItems.length > 0;

    // 또는 페이지에 "No files" 같은 텍스트가 있는지 확인
    const pageText = document.body.innerText.toLowerCase();
    const hasNoFilesText = pageText.includes('No Files') || pageText.includes('empty') || pageText.includes('Upload files or ask Grok to create one.');

    if (!hasFiles && (fileItems.length === 0 || hasNoFilesText)) {
        console.warn("⚠️ 빈 화면 감지! 파일 목록이 로드되지 않았습니다.");
        isEmpty = true;
        showEmptyAlert();

        // 필요하면 여기서 자동 강력 새로고침 (주석 해제하면 자동)
        // setTimeout(() => { location.reload(true); }, 3000);
    } else {
        console.log(`✅ 파일 목록 로드 확인됨 (${fileItems.length}개 정도 감지)`);
    }
}

// 실제 삭제 작업 함수
async function performDelete() {
    checkIfEmptyScreen();
    while (true) {
        if (isPaused) {
            await new Promise(r => setTimeout(r, 800));
            continue;
        }


        const deleteBtn = document.querySelector('button[aria-label="Delete file"]') ||
                          Array.from(document.querySelectorAll('button')).find(btn =>
                              (btn.getAttribute('aria-label') || '').toLowerCase().includes('delete') ||
                              btn.innerHTML.toLowerCase().includes('trash')
                          );
        // 현재 삭제하려는 파일의 이름 가져오기
        const currentItem = deleteBtn.closest('li') || deleteBtn.closest('a') || deleteBtn.parentElement;
        let currentFileName = getFileName(currentItem);
        if (!currentFileName.toLowerCase().includes('image.png')) {
            console.log("이미지 파일이 아닙니다. 작동 중지함");
            break;
        } else {
            console.log("이미지 파일 OK");
        }

        // 레퍼런스 파일 삭제 모달

        let modalDeleteBtn = document.querySelector('button.text-fg-danger');

        if (modalDeleteBtn) {
            console.log("✅ 모달 Delete 버튼 발견 → 강제 클릭");

            // 레퍼런스 삭제
            modalDeleteBtn.click();

            const clickEvent = new MouseEvent('click', {
                bubbles: true,
                cancelable: true,
                view: window
            });
            modalDeleteBtn.dispatchEvent(clickEvent);
            reCount++;
            console.log(`🗑️ 레퍼런스 삭제 완료: ${reCount}개`);
            currentFileName = "modal";
        }
        // 이전에 삭제한 파일과 이름이 같으면 리로드
        if (currentFileName != "image.png" && currentFileName == lastDeletedFileName) {
            console.log(`🔄 같은 이름 파일 감지: "${currentFileName}" → 페이지 리로드`);
            await new Promise(r => setTimeout(r, 1000));
            location.reload();
            return;
        } else {
            console.log(`🔄 다른 파일 이름: "${currentFileName}"`);
        }

        if (!deleteBtn && !isEmpty) {
            console.log(`✅ 현재 페이지에서 더 이상 삭제할 파일이 없습니다. 총 ${count}개 삭제 완료.`);
            location.reload();
            break;
        }



        deleteBtn.scrollIntoView({ behavior: "smooth", block: "center" });
        await new Promise(r => setTimeout(r, 200));
        deleteBtn.click();
        await new Promise(r => setTimeout(r, 200));

        const confirmBtn = document.querySelector('button[aria-label="Delete"]') ||
                           Array.from(document.querySelectorAll('button')).find(b =>
                               b.textContent.trim().toLowerCase().includes('delete') && b.textContent.length < 50
                           );

        if (confirmBtn) {
            confirmBtn.click();
            lastDeletedFileName = currentFileName;
            count++;
            console.log(`🗑️ 삭제 완료: ${count}개`);
            await new Promise(r => setTimeout(r, 150));
        } else {
            await new Promise(r => setTimeout(r, 150));
        }
    }
}

// 페이지 로드 후 버튼 추가 + 삭제 시작
setTimeout(() => {
    addPauseButton();
    // 빈 화면 검사는 2.5초 후에 실행 (목록 로딩 시간 고려)
    // setTimeout(checkIfEmptyScreen, 2500);
    performDelete();
}, 3000);  // 페이지가 어느 정도 로드된 후 시작 (빈 화면 문제 완화)

})();

Edit

Pub: 10 Apr 2026 18:37 UTC

Edit: 12 Apr 2026 17:51 UTC

Views: 295