Download app/static/app.js from DOOOOOGF/dsasddas: direct link, hf CLI and curl.
- Browser
- Download file 28 kB
-
https://huggingface.co/spaces/DOOOOOGF/dsasddas/resolve/main/app/static/app.js
- Command line
-
hf download hf://spaces/DOOOOOGF/dsasddas/app/static/app.js
-
curl -L -o app.js https://huggingface.co/spaces/DOOOOOGF/dsasddas/resolve/main/app/static/app.js
28 kB
| // ============================================================ | |
| // AUTH MODULE | |
| // ============================================================ | |
| const AuthModule = (() => { | |
| let _lockoutTimer = null; | |
| // ── Helpers ──────────────────────────────────────────────── | |
| function showOverlay() { | |
| const overlay = document.getElementById('auth-overlay'); | |
| overlay.style.display = 'flex'; | |
| overlay.classList.remove('hidden'); | |
| // Re-animate the card on re-show | |
| const card = overlay.querySelector('.auth-card'); | |
| card.style.animation = 'none'; | |
| void card.offsetWidth; // reflow | |
| card.style.animation = ''; | |
| document.getElementById('auth-password-input').focus(); | |
| } | |
| function hideOverlay() { | |
| const overlay = document.getElementById('auth-overlay'); | |
| overlay.style.display = 'none'; | |
| overlay.classList.add('hidden'); | |
| document.getElementById('logout-btn').style.display = 'inline-flex'; | |
| } | |
| function showError(msg) { | |
| const el = document.getElementById('auth-error-msg'); | |
| document.getElementById('auth-error-text').textContent = msg; | |
| // Re-trigger shake animation | |
| el.classList.remove('visible'); | |
| void el.offsetWidth; | |
| el.classList.add('visible'); | |
| } | |
| function hideError() { | |
| document.getElementById('auth-error-msg').classList.remove('visible'); | |
| } | |
| function startLockoutCountdown(seconds) { | |
| const lockoutEl = document.getElementById('auth-lockout-msg'); | |
| const countdownEl = document.getElementById('lockout-countdown'); | |
| const loginBtn = document.getElementById('auth-login-btn'); | |
| lockoutEl.classList.add('visible'); | |
| hideError(); | |
| loginBtn.disabled = true; | |
| let remaining = seconds; | |
| countdownEl.textContent = remaining; | |
| if (_lockoutTimer) clearInterval(_lockoutTimer); | |
| _lockoutTimer = setInterval(() => { | |
| remaining--; | |
| countdownEl.textContent = remaining; | |
| if (remaining <= 0) { | |
| clearInterval(_lockoutTimer); | |
| _lockoutTimer = null; | |
| lockoutEl.classList.remove('visible'); | |
| loginBtn.disabled = false; | |
| document.getElementById('auth-password-input').focus(); | |
| } | |
| }, 1000); | |
| } | |
| function setLoginLoading(isLoading) { | |
| const btn = document.getElementById('auth-login-btn'); | |
| btn.disabled = isLoading; | |
| btn.innerHTML = isLoading | |
| ? '<i class="fa-solid fa-circle-notch fa-spin"></i> 验证中...' | |
| : '<i class="fa-solid fa-unlock"></i> 解锁'; | |
| } | |
| // ── Core Actions ─────────────────────────────────────────── | |
| async function checkSession() { | |
| try { | |
| const res = await fetch('/api/auth/status'); | |
| if (!res.ok) { showOverlay(); return; } | |
| const data = await res.json(); | |
| if (data.authenticated) { | |
| hideOverlay(); | |
| } else { | |
| showOverlay(); | |
| } | |
| } catch (_) { | |
| showOverlay(); | |
| } | |
| } | |
| async function login() { | |
| const pw = document.getElementById('auth-password-input').value; | |
| if (!pw) { | |
| showError('请输入密钥!'); | |
| return; | |
| } | |
| setLoginLoading(true); | |
| hideError(); | |
| try { | |
| const res = await fetch('/api/auth/login', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify({ password: pw }) | |
| }); | |
| const data = await res.json(); | |
| if (res.ok) { | |
| // Success | |
| document.getElementById('auth-password-input').value = ''; | |
| hideOverlay(); | |
| // Kick off the app now that we're authenticated | |
| fetchTasks(); | |
| fetchFiles(); | |
| fetchSystemStatus(); | |
| } else if (res.status === 429) { | |
| // IP locked out — extract remaining seconds from error message | |
| const match = data.detail && data.detail.match(/(\d+)\s*seconds/); | |
| const secs = match ? parseInt(match[1]) : 900; | |
| startLockoutCountdown(secs); | |
| } else { | |
| showError(data.detail || '密码错误,请重试。'); | |
| } | |
| } catch (err) { | |
| showError('网络错误,请稍后重试。'); | |
| } finally { | |
| setLoginLoading(false); | |
| } | |
| } | |
| async function logout() { | |
| try { | |
| await fetch('/api/auth/logout', { method: 'POST' }); | |
| } catch (_) { /* ignore */ } | |
| document.getElementById('logout-btn').style.display = 'none'; | |
| showOverlay(); | |
| } | |
| // ── Password eye toggle ──────────────────────────────────── | |
| function initEyeToggle() { | |
| const btn = document.getElementById('auth-toggle-pw-btn'); | |
| const input = document.getElementById('auth-password-input'); | |
| const icon = document.getElementById('pw-eye-icon'); | |
| btn.addEventListener('click', () => { | |
| const isHidden = input.type === 'password'; | |
| input.type = isHidden ? 'text' : 'password'; | |
| icon.className = isHidden ? 'fa-regular fa-eye-slash' : 'fa-regular fa-eye'; | |
| }); | |
| } | |
| // ── Init ─────────────────────────────────────────────────── | |
| function init() { | |
| initEyeToggle(); | |
| document.getElementById('auth-login-btn').addEventListener('click', login); | |
| document.getElementById('auth-password-input').addEventListener('keydown', (e) => { | |
| if (e.key === 'Enter') login(); | |
| }); | |
| document.getElementById('logout-btn').addEventListener('click', logout); | |
| // Check existing session on load | |
| checkSession(); | |
| } | |
| return { init, showOverlay, logout }; | |
| })(); | |
| // ============================================================ | |
| // GLOBAL FETCH WRAPPER — intercepts 401 responses app-wide | |
| // ============================================================ | |
| const _originalFetch = window.fetch.bind(window); | |
| window.fetch = async function(...args) { | |
| const response = await _originalFetch(...args); | |
| // If any API call returns 401, the session expired — re-show lock screen | |
| if (response.status === 401) { | |
| const url = typeof args[0] === 'string' ? args[0] : args[0].url || ''; | |
| // Don't intercept the login/status calls themselves | |
| if (!url.includes('/api/auth/')) { | |
| AuthModule.showOverlay(); | |
| } | |
| } | |
| return response; | |
| }; | |
| // ============================================================ | |
| // Global state variables | |
| // ============================================================ | |
| let tasks = []; | |
| let files = []; | |
| let activeLogTaskId = null; | |
| let logPollInterval = null; | |
| let generalPollInterval = null; | |
| // Code Templates Definition | |
| const templates = { | |
| url: `# 单文件 URL 下载模板 | |
| # 内置了 download_file(url, filename=None) 辅助函数 | |
| # 它会自动以流式块方式下载文件并上报进度条进度 | |
| url = "https://raw.githubusercontent.com/huggingface/hub-docs/main/assets/hf-logo.png" | |
| download_file(url, "huggingface-logo.png") | |
| `, | |
| hf: `# Hugging Face Hub 模型/文件下载模板 | |
| # 可以使用 huggingface_hub 库直接下载 Hugging Face Spaces/Models 中的文件 | |
| # 我们的环境变量已经定义了 SAVE_DIR 指向任务文件夹 | |
| from huggingface_hub import hf_hub_download | |
| repo_id = "gpt2" | |
| filename = "config.json" | |
| print(f"正在从 Hugging Face 仓库 {repo_id} 下载 {filename} ...") | |
| # 必须指定 local_dir=SAVE_DIR | |
| filepath = hf_hub_download( | |
| repo_id=repo_id, | |
| filename=filename, | |
| local_dir=SAVE_DIR, | |
| local_dir_use_symlinks=False | |
| ) | |
| print(f"文件已下载并保存到: {filepath}") | |
| # 完成后可以上报 100% 进度 | |
| report_progress(100) | |
| `, | |
| torrent: `# 种子 / 磁力链接下载模板 | |
| # 内置了 download_torrent(torrent_path_or_magnet) 辅助函数 | |
| # 使用系统级 BitTorrent 引擎 aria2c 下载种子或磁力链接,支持节点发现和断点续传 | |
| # 1. 磁力链接下载示例: | |
| magnet_link = "magnet:?xt=urn:btih:d984f1aa9d0d828fa605f6e8c89f5c490ff664c3" # 替换为您的磁力链接 | |
| # download_torrent(magnet_link) | |
| # 2. .torrent 种子文件下载示例: | |
| # 先通过常规 URL 下载 .torrent 种子文件,再调用 BitTorrent 引擎解析下载 | |
| torrent_url = "https://example.com/test.torrent" | |
| # torrent_file = download_file(torrent_url, "temp.torrent") | |
| # download_torrent(torrent_file) | |
| `, | |
| 'tg-channel': `# Telegram 频道媒体下载模板 | |
| # 内置了 download_tg_channel(channel_username_or_id, bot_token=None, session_string=None, limit=20) | |
| # 您的 api_id 和 api_hash 应当预先配置在 Hugging Face Space 的加密环境变量 (Secrets) 中: | |
| # - TG_API_ID (Telegram App API ID) | |
| # - TG_API_HASH (Telegram App API Hash) | |
| # 提示:如果您在本地测试或无法提供 session_string,可以使用 TG_BOT_TOKEN 环境变量让机器人登录并下载公开频道的公开文件。 | |
| # 对于私有频道,建议配置 TG_SESSION_STRING (可以使用 Telethon StringSession 在本地生成,以避免在 Docker 中交互式登录)。 | |
| # 示例:下载指定频道的最近 10 个媒体文件 | |
| channel = "huggingface" # 频道用户名或频道ID | |
| download_tg_channel(channel, limit=10) | |
| `, | |
| 'multi-url': `# 多 URL 批量并发或循环下载模板 | |
| import time | |
| urls = [ | |
| "https://raw.githubusercontent.com/huggingface/hub-docs/main/assets/hf-logo.png", | |
| "https://raw.githubusercontent.com/huggingface/transformers/main/docs/source/en/imgs/transformers_logo.png" | |
| ] | |
| total = len(urls) | |
| for index, url in enumerate(urls): | |
| filename = f"logo_{index + 1}.png" | |
| print(f"正在下载第 {index + 1}/{total} 个文件...") | |
| # 执行下载 | |
| download_file(url, filename) | |
| # 估算总进度并上报 | |
| progress = int(((index + 1) / total) * 100) | |
| report_progress(progress) | |
| time.sleep(0.5) # 稍微等待 | |
| `, | |
| 'custom-script': `# 自定义脚本逻辑模板 (例如自定义请求或解压文件) | |
| import os | |
| import time | |
| import requests | |
| print("开始执行自定义数据采集流程...") | |
| report_progress(10) | |
| # 使用 requests 获取特定内容 | |
| print("正在请求测试 API 数据...") | |
| response = requests.get("https://httpbin.org/json") | |
| if response.status_code == 200: | |
| data = response.json() | |
| print("获取数据成功,正在保存...") | |
| # 存储到 SAVE_DIR | |
| target_path = os.path.join(SAVE_DIR, "test_api_response.json") | |
| with open(target_path, "w", encoding="utf-8") as f: | |
| import json | |
| json.dump(data, f, indent=4, ensure_ascii=False) | |
| print(f"结果已成功写入: {target_path}") | |
| else: | |
| print(f"API 请求失败: {response.status_code}") | |
| report_progress(60) | |
| time.sleep(1) | |
| # 生成一个大的日志 | |
| print("数据校验中...") | |
| report_progress(100) | |
| ` | |
| }; | |
| // Initialize Application | |
| document.addEventListener('DOMContentLoaded', () => { | |
| // Set default template | |
| document.getElementById('code-editor').value = templates.url; | |
| // Initialize auth module first — it will show the lock screen | |
| // and call fetchTasks/fetchFiles/fetchSystemStatus after login | |
| AuthModule.init(); | |
| // Event Listeners Setup (UI only, no API calls) | |
| initEventListeners(); | |
| // Start background poll every 3 seconds — runs regardless, | |
| // but API calls return 401 while unauthenticated (triggering re-lock) | |
| generalPollInterval = setInterval(() => { | |
| fetchTasks(); | |
| fetchFiles(); | |
| }, 3000); | |
| }); | |
| // Event Listeners Initialization | |
| function initEventListeners() { | |
| // Template dropdown logic | |
| const templateBtn = document.getElementById('template-btn'); | |
| const templatesDropdown = document.getElementById('templates-dropdown'); | |
| templateBtn.addEventListener('click', (e) => { | |
| e.stopPropagation(); | |
| document.getElementById('templates-list').parentElement.classList.toggle('active'); | |
| }); | |
| document.addEventListener('click', () => { | |
| document.getElementById('templates-list').parentElement.classList.remove('active'); | |
| }); | |
| document.querySelectorAll('#templates-list a').forEach(item => { | |
| item.addEventListener('click', (e) => { | |
| e.preventDefault(); | |
| const templateKey = item.getAttribute('data-template'); | |
| if (templates[templateKey]) { | |
| document.getElementById('code-editor').value = templates[templateKey]; | |
| } | |
| }); | |
| }); | |
| // Code Editor tab key handling (standard tab indent in textarea) | |
| const textarea = document.getElementById('code-editor'); | |
| textarea.addEventListener('keydown', function(e) { | |
| if (e.key === 'Tab') { | |
| e.preventDefault(); | |
| const start = this.selectionStart; | |
| const end = this.selectionEnd; | |
| this.value = this.value.substring(0, start) + " " + this.value.substring(end); | |
| this.selectionStart = this.selectionEnd = start + 4; | |
| } | |
| }); | |
| // Submit Task | |
| document.getElementById('submit-task-btn').addEventListener('click', submitTask); | |
| // Refresh Buttons | |
| document.getElementById('refresh-tasks-btn').addEventListener('click', fetchTasks); | |
| document.getElementById('refresh-files-btn').addEventListener('click', fetchFiles); | |
| // Logs modal close | |
| document.querySelectorAll('#close-modal-btn, #close-modal-btn-footer').forEach(btn => { | |
| btn.addEventListener('click', closeLogsModal); | |
| }); | |
| // Copy logs | |
| document.getElementById('copy-logs-btn').addEventListener('click', copyLogsToClipboard); | |
| } | |
| // Fetch Tasks API | |
| async function fetchTasks() { | |
| try { | |
| const response = await fetch('/api/tasks'); | |
| if (!response.ok) throw new Error("获取任务列表失败"); | |
| tasks = await response.json(); | |
| renderTasks(); | |
| updateActiveTasksBadge(); | |
| } catch (error) { | |
| console.error("Error fetching tasks:", error); | |
| } | |
| } | |
| // Fetch Files API | |
| async function fetchFiles() { | |
| try { | |
| const response = await fetch('/api/files'); | |
| if (!response.ok) throw new Error("获取文件列表失败"); | |
| files = await response.json(); | |
| renderFiles(); | |
| } catch (error) { | |
| console.error("Error fetching files:", error); | |
| } | |
| } | |
| // Fetch System Storage Status | |
| async function fetchSystemStatus() { | |
| const storageBadge = document.getElementById('storage-status'); | |
| try { | |
| const response = await fetch('/api/files'); | |
| if (response.ok) { | |
| // Check if we are running in persistent environment | |
| // (Just a visual simulation or custom check from location) | |
| const isHF = window.location.hostname.includes('hf.space'); | |
| storageBadge.querySelector('.badge-text').textContent = isHF | |
| ? "Hugging Face Spaces 持久存储 (数据持久)" | |
| : "本地开发存储 (data/)"; | |
| storageBadge.querySelector('.dot').className = "dot green"; | |
| } | |
| } catch (error) { | |
| storageBadge.querySelector('.badge-text').textContent = "存储连接错误"; | |
| storageBadge.querySelector('.dot').className = "dot amber"; | |
| } | |
| } | |
| // Render Tasks List | |
| function renderTasks() { | |
| const container = document.getElementById('tasks-list-container'); | |
| if (tasks.length === 0) { | |
| container.innerHTML = ` | |
| <div class="empty-state"> | |
| <i class="fa-solid fa-circle-info"></i> | |
| <p>暂无下载任务,在左侧创建新任务以开始</p> | |
| </div> | |
| `; | |
| return; | |
| } | |
| container.innerHTML = tasks.map(task => { | |
| const date = new Date(task.created_at).toLocaleString(); | |
| // Progress display | |
| const isRunning = task.status === 'running'; | |
| const progressVal = task.progress || 0; | |
| let actionButtons = ''; | |
| if (isRunning || task.status === 'pending') { | |
| actionButtons = ` | |
| <button class="btn btn-sm btn-danger" onclick="cancelTask('${task.id}')"> | |
| <i class="fa-solid fa-ban"></i> 取消任务 | |
| </button> | |
| `; | |
| } else { | |
| actionButtons = ` | |
| <button class="btn btn-sm btn-secondary" onclick="confirmDeleteTask('${task.id}')"> | |
| <i class="fa-solid fa-trash-can"></i> 删除历史 | |
| </button> | |
| `; | |
| } | |
| const errorDiv = task.error_message | |
| ? `<div class="task-error"><strong>错误原因:</strong> ${task.error_message}</div>` | |
| : ''; | |
| return ` | |
| <div class="task-item ${task.status}" id="task-${task.id}"> | |
| <div class="task-meta"> | |
| <div class="task-info-left"> | |
| <div class="task-folder"> | |
| <i class="fa-regular fa-folder-open"></i> ${task.folder_name} | |
| </div> | |
| <div class="task-id">ID: ${task.id} | 创建时间: ${date}</div> | |
| </div> | |
| <span class="status-pill ${task.status}">${translateStatus(task.status)}</span> | |
| </div> | |
| <div class="task-progress-box"> | |
| <div class="progress-info"> | |
| <span>进度</span> | |
| <span>${progressVal}%</span> | |
| </div> | |
| <div class="progress-bar-bg"> | |
| <div class="progress-bar-fill" style="width: ${progressVal}%"></div> | |
| </div> | |
| </div> | |
| ${errorDiv} | |
| <div class="task-actions"> | |
| <button class="btn btn-sm btn-outline" onclick="openLogsModal('${task.id}')"> | |
| <i class="fa-solid fa-terminal"></i> 运行日志 | |
| </button> | |
| ${actionButtons} | |
| </div> | |
| </div> | |
| `; | |
| }).join(''); | |
| } | |
| // Render Files List Table | |
| function renderFiles() { | |
| const tbody = document.getElementById('files-list-tbody'); | |
| if (files.length === 0) { | |
| tbody.innerHTML = ` | |
| <tr> | |
| <td colspan="4" class="table-empty"> | |
| <i class="fa-solid fa-folder-open"></i> 暂无已下载的文件 | |
| </td> | |
| </tr> | |
| `; | |
| return; | |
| } | |
| tbody.innerHTML = files.map(file => { | |
| const sizeReadable = formatBytes(file.size); | |
| const date = new Date(file.modified).toLocaleString(); | |
| return ` | |
| <tr> | |
| <td> | |
| <div class="file-name-cell"> | |
| <i class="fa-regular fa-file"></i> | |
| <div> | |
| <div>${file.name}</div> | |
| <span class="file-path">${file.path}</span> | |
| </div> | |
| </div> | |
| </td> | |
| <td>${sizeReadable}</td> | |
| <td>${date}</td> | |
| <td style="text-align: center;"> | |
| <div style="display: flex; gap: 8px; justify-content: center;"> | |
| <a href="/api/files/download/${encodeURIComponent(file.path)}" class="btn btn-sm btn-outline" style="text-decoration:none;" download> | |
| <i class="fa-solid fa-download"></i> | |
| </a> | |
| <button class="btn btn-sm btn-outline btn-danger" style="padding: 6px 10px;" onclick="deleteFile('${file.path}')" title="删除文件"> | |
| <i class="fa-solid fa-trash"></i> | |
| </button> | |
| </div> | |
| </td> | |
| </tr> | |
| `; | |
| }).join(''); | |
| } | |
| // Helper: Translate backend status strings | |
| function translateStatus(status) { | |
| switch (status) { | |
| case 'pending': return '排队中'; | |
| case 'running': return '下载中'; | |
| case 'completed': return '已完成'; | |
| case 'failed': return '执行失败'; | |
| case 'cancelled': return '已取消'; | |
| default: return status; | |
| } | |
| } | |
| // Helper: Format Bytes to human readable | |
| function formatBytes(bytes, decimals = 2) { | |
| if (bytes === 0) return '0 Bytes'; | |
| const k = 1024; | |
| const dm = decimals < 0 ? 0 : decimals; | |
| const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; | |
| const i = Math.floor(Math.log(bytes) / Math.log(k)); | |
| return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; | |
| } | |
| // Helper: Update Active Tasks counter in header | |
| function updateActiveTasksBadge() { | |
| const activeTasks = tasks.filter(t => t.status === 'running' || t.status === 'pending'); | |
| document.getElementById('active-tasks-count').querySelector('.badge-number').textContent = activeTasks.length; | |
| } | |
| // Submit New Task | |
| async function submitTask() { | |
| const folderInput = document.getElementById('folder-name-input'); | |
| const editor = document.getElementById('code-editor'); | |
| const folderName = folderInput.value.trim(); | |
| const code = editor.value.trim(); | |
| if (!folderName) { | |
| alert("请输入存储文件夹名称!"); | |
| folderInput.focus(); | |
| return; | |
| } | |
| if (!code) { | |
| alert("请输入 Python 下载代码!"); | |
| editor.focus(); | |
| return; | |
| } | |
| const submitBtn = document.getElementById('submit-task-btn'); | |
| submitBtn.disabled = true; | |
| submitBtn.innerHTML = `<i class="fa-solid fa-circle-notch fa-spin"></i> 提交任务中...`; | |
| try { | |
| const response = await fetch('/api/tasks', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify({ folder_name: folderName, code: code }) | |
| }); | |
| if (!response.ok) { | |
| const err = await response.json(); | |
| throw new Error(err.detail || "提交下载任务失败"); | |
| } | |
| // Reset folder inputs and refresh | |
| folderInput.value = ''; | |
| await fetchTasks(); | |
| } catch (error) { | |
| alert(error.message); | |
| } finally { | |
| submitBtn.disabled = false; | |
| submitBtn.innerHTML = `<i class="fa-solid fa-play"></i> 开始下载任务`; | |
| } | |
| } | |
| // Cancel Running Task | |
| async function cancelTask(taskId) { | |
| if (!confirm("确定要取消此下载任务吗?")) return; | |
| try { | |
| const response = await fetch(`/api/tasks/${taskId}/cancel`, { method: 'POST' }); | |
| if (!response.ok) throw new Error("取消任务失败"); | |
| fetchTasks(); | |
| } catch (error) { | |
| alert(error.message); | |
| } | |
| } | |
| // Delete History Task Entry | |
| function confirmDeleteTask(taskId) { | |
| const container = document.createElement('div'); | |
| container.style.cssText = ` | |
| position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; | |
| background: rgba(0,0,0,0.6); display: flex; align-items: center; | |
| justify-content: center; z-index: 1000; backdrop-filter: blur(5px); | |
| `; | |
| const dialog = document.createElement('div'); | |
| dialog.className = 'card panel'; | |
| dialog.style.cssText = ` | |
| max-width: 420px; width: 100%; padding: 24px; display: flex; | |
| flex-direction: column; gap: 16px; background: #0f1322; | |
| border: 1px solid rgba(255,255,255,0.1); | |
| `; | |
| dialog.innerHTML = ` | |
| <h3 style="font-size:1.15rem; font-weight:600;"><i class="fa-solid fa-circle-question" style="color:var(--primary);"></i> 删除确认</h3> | |
| <p style="font-size:0.9rem; color:var(--text-secondary);">您想要如何删除此任务历史?</p> | |
| <div style="display:flex; flex-direction:column; gap:10px; margin-top: 10px;"> | |
| <button class="btn btn-outline" id="del-history-only">仅删除任务历史 (保留下载文件)</button> | |
| <button class="btn btn-danger" id="del-all">彻底删除任务及下载的文件</button> | |
| <button class="btn btn-secondary" id="del-cancel" style="margin-top: 5px;">取消</button> | |
| </div> | |
| `; | |
| container.appendChild(dialog); | |
| document.body.appendChild(container); | |
| document.getElementById('del-history-only').addEventListener('click', () => { | |
| deleteTask(taskId, false); | |
| document.body.removeChild(container); | |
| }); | |
| document.getElementById('del-all').addEventListener('click', () => { | |
| if (confirm("警告: 这将永久删除该文件夹下已下载的所有文件,无法恢复!确认继续?")) { | |
| deleteTask(taskId, true); | |
| } | |
| document.body.removeChild(container); | |
| }); | |
| document.getElementById('del-cancel').addEventListener('click', () => { | |
| document.body.removeChild(container); | |
| }); | |
| } | |
| async function deleteTask(taskId, deleteFiles) { | |
| try { | |
| const response = await fetch(`/api/tasks/${taskId}?delete_files=${deleteFiles}`, { | |
| method: 'DELETE' | |
| }); | |
| if (!response.ok) throw new Error("删除任务失败"); | |
| fetchTasks(); | |
| fetchFiles(); | |
| } catch (error) { | |
| alert(error.message); | |
| } | |
| } | |
| // Delete File directly from Explorer | |
| async function deleteFile(filePath) { | |
| if (!confirm(`确定要彻底删除该文件吗?\n${filePath}`)) return; | |
| try { | |
| const response = await fetch(`/api/files/${encodeURIComponent(filePath)}`, { | |
| method: 'DELETE' | |
| }); | |
| if (!response.ok) throw new Error("删除文件失败"); | |
| fetchFiles(); | |
| } catch (error) { | |
| alert(error.message); | |
| } | |
| } | |
| // Open Logs Modal | |
| function openLogsModal(taskId) { | |
| activeLogTaskId = taskId; | |
| const modal = document.getElementById('logs-modal'); | |
| document.getElementById('modal-task-id').textContent = taskId.substring(0, 8) + '...'; | |
| document.getElementById('logs-content').textContent = '正在连接日志流...'; | |
| modal.classList.add('active'); | |
| // Immediate fetch logs | |
| fetchLogs(); | |
| // Poll logs every 1 second | |
| logPollInterval = setInterval(fetchLogs, 1000); | |
| } | |
| // Close Logs Modal | |
| function closeLogsModal() { | |
| const modal = document.getElementById('logs-modal'); | |
| modal.classList.remove('active'); | |
| if (logPollInterval) { | |
| clearInterval(logPollInterval); | |
| logPollInterval = null; | |
| } | |
| activeLogTaskId = null; | |
| } | |
| // Fetch Logs API | |
| async function fetchLogs() { | |
| if (!activeLogTaskId) return; | |
| try { | |
| const response = await fetch(`/api/tasks/${activeLogTaskId}/logs`); | |
| if (!response.ok) throw new Error("获取日志失败"); | |
| const data = await response.json(); | |
| const logsBox = document.getElementById('logs-content'); | |
| logsBox.textContent = data.logs || '控制台暂无输出。'; | |
| // Handle Auto Scroll | |
| const autoScroll = document.getElementById('auto-scroll-logs').checked; | |
| if (autoScroll) { | |
| const modalBody = document.querySelector('.modal-body'); | |
| modalBody.scrollTop = modalBody.scrollHeight; | |
| } | |
| } catch (error) { | |
| console.error("Error fetching logs:", error); | |
| } | |
| } | |
| // Copy Console Logs to Clipboard | |
| function copyLogsToClipboard() { | |
| const text = document.getElementById('logs-content').textContent; | |
| navigator.clipboard.writeText(text).then(() => { | |
| alert("日志已成功复制到剪贴板!"); | |
| }).catch(err => { | |
| console.error("Could not copy logs: ", err); | |
| }); | |
| } | |