Spaces:
Paused
Paused
Download static/script.js from ttnikal/Filesharing: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/spaces/ttnikal/Filesharing/resolve/main/static/script.js
- Command line
-
hf download hf://spaces/ttnikal/Filesharing/static/script.js
-
curl -L -o script.js https://huggingface.co/spaces/ttnikal/Filesharing/resolve/main/static/script.js
11.3 kB
| document.addEventListener('DOMContentLoaded', () => { | |
| const dropZone = document.getElementById('drop-zone'); | |
| const fileInput = document.getElementById('file-input'); | |
| const browseBtn = document.getElementById('browse-btn'); | |
| const fileList = document.getElementById('file-list'); | |
| const refreshBtn = document.getElementById('refresh-btn'); | |
| const zipSelectedBtn = document.getElementById('zip-selected-btn'); | |
| const progressContainer = document.getElementById('upload-progress-container'); | |
| const progressItems = document.getElementById('progress-items'); | |
| const uploadSection = document.getElementById('upload-section'); | |
| const terminalSection = document.getElementById('terminal-section'); | |
| // 1. Fixed User identification | |
| const urlParams = new URLSearchParams(window.location.search); | |
| let userId = urlParams.get('uid') || localStorage.getItem('nexus_user_id'); | |
| // UI Mode Toggle | |
| if (urlParams.has('uid')) { | |
| if (uploadSection) uploadSection.style.display = 'none'; | |
| if (terminalSection) terminalSection.style.display = 'none'; | |
| document.querySelector('header p').innerText = "Personal File Manager"; | |
| } | |
| if (!userId) { | |
| userId = 'u' + Math.random().toString(36).substring(2, 10); | |
| } | |
| // Always sync localStorage | |
| localStorage.setItem('nexus_user_id', userId); | |
| // Remove query param from URL without reloading | |
| if (urlParams.has('uid')) { | |
| window.history.replaceState({}, document.title, window.location.pathname); | |
| } | |
| // Load initial file list | |
| loadFiles(); | |
| // 2. Fixed Event Listeners (ensure buttons work) | |
| if (browseBtn && fileInput) { | |
| browseBtn.onclick = (e) => { | |
| e.preventDefault(); | |
| fileInput.click(); | |
| }; | |
| fileInput.onchange = () => handleFiles(fileInput.files); | |
| } | |
| if (refreshBtn) refreshBtn.onclick = loadFiles; | |
| if (zipSelectedBtn) zipSelectedBtn.onclick = zipSelectedFiles; | |
| // 3. Optimized Drag & Drop | |
| if (dropZone) { | |
| dropZone.ondragover = (e) => { | |
| e.preventDefault(); | |
| dropZone.classList.add('drag-over'); | |
| }; | |
| dropZone.ondragleave = () => dropZone.classList.remove('drag-over'); | |
| dropZone.ondrop = (e) => { | |
| e.preventDefault(); | |
| dropZone.classList.remove('drag-over'); | |
| handleFiles(e.dataTransfer.files); | |
| }; | |
| } | |
| async function handleFiles(files) { | |
| if (!files || files.length === 0) return; | |
| progressContainer.classList.remove('hidden'); | |
| for (const file of Array.from(files)) { | |
| try { | |
| await uploadFile(file); | |
| } catch (err) { | |
| console.error("Upload failed", err); | |
| } | |
| } | |
| setTimeout(() => { | |
| progressContainer.classList.add('hidden'); | |
| progressItems.innerHTML = ''; | |
| loadFiles(); | |
| }, 1500); | |
| } | |
| function uploadFile(file) { | |
| return new Promise((resolve, reject) => { | |
| const xhr = new XMLHttpRequest(); | |
| const formData = new FormData(); | |
| formData.append('files', file); | |
| const item = document.createElement('div'); | |
| item.className = 'progress-item'; | |
| item.innerHTML = ` | |
| <div class="progress-info"> | |
| <span>${file.name}</span> | |
| <span class="percent">0%</span> | |
| </div> | |
| <div class="progress-bar-bg"> | |
| <div class="progress-bar-fill"></div> | |
| </div> | |
| `; | |
| progressItems.appendChild(item); | |
| const fill = item.querySelector('.progress-bar-fill'); | |
| const percent = item.querySelector('.percent'); | |
| xhr.upload.onprogress = (e) => { | |
| if (e.lengthComputable) { | |
| const p = Math.round((e.loaded / e.total) * 100); | |
| fill.style.width = p + '%'; | |
| percent.textContent = p + '%'; | |
| } | |
| }; | |
| xhr.onload = () => { | |
| if (xhr.status === 200) resolve(JSON.parse(xhr.responseText)); | |
| else reject(xhr.statusText); | |
| }; | |
| xhr.onerror = () => reject("Network error"); | |
| xhr.open('POST', '/upload', true); | |
| xhr.setRequestHeader('X-User-Id', userId); | |
| xhr.send(formData); | |
| }); | |
| } | |
| async function loadFiles() { | |
| if (!fileList) return; | |
| try { | |
| const response = await fetch('/files', { | |
| headers: { 'X-User-Id': userId } // Fixed syntax error here | |
| }); | |
| if (!response.ok) throw new Error("Failed to fetch"); | |
| const files = await response.json(); | |
| renderFileList(files); | |
| } catch (error) { | |
| console.error(error); | |
| fileList.innerHTML = '<p class="error">Error connecting to server.</p>'; | |
| } | |
| } | |
| function renderFileList(files) { | |
| if (!files || files.length === 0) { | |
| fileList.innerHTML = '<p class="empty-msg">No files. They expire in 24h.</p>'; | |
| return; | |
| } | |
| const baseUrl = window.location.origin; | |
| fileList.innerHTML = files.map(file => { | |
| const downloadUrl = `${baseUrl}/download/${file.name}`; | |
| const wgetCmd = `wget "${downloadUrl}"`; | |
| const isZip = file.display_name.toLowerCase().endsWith('.zip'); | |
| return ` | |
| <div class="file-item"> | |
| <input type="checkbox" class="file-checkbox" data-name="${file.name}" style="margin-right:10px;"> | |
| <div class="file-icon"><i class="${getFileIcon(file.display_name)}"></i></div> | |
| <div class="file-info"> | |
| <div class="file-name">${file.display_name}</div> | |
| <div class="file-meta">${formatBytes(file.size)} • ${new Date(file.mtime * 1000).toLocaleString()}</div> | |
| <div class="file-links"> | |
| <div class="link-group"> | |
| <code class="direct-url">${downloadUrl}</code> | |
| <button class="copy-btn" data-copy="${downloadUrl}"><i class="fas fa-copy"></i></button> | |
| </div> | |
| <div class="link-group"> | |
| <code class="wget-cmd">${wgetCmd}</code> | |
| <button class="copy-btn" data-copy='${wgetCmd}'><i class="fas fa-copy"></i></button> | |
| </div> | |
| </div> | |
| </div> | |
| <div class="file-actions"> | |
| ${isZip ? `<button class="action-btn unzip-btn" data-name="${file.name}" title="Unzip"><i class="fas fa-box-open"></i></button>` : ''} | |
| <a href="/download/${file.name}" class="action-btn download-btn"><i class="fas fa-download"></i></a> | |
| <button class="action-btn delete-btn" data-name="${file.name}"><i class="fas fa-trash"></i></button> | |
| </div> | |
| </div>`; | |
| }).join(''); | |
| // Re-attach listeners for dynamic content | |
| document.querySelectorAll('.copy-btn').forEach(btn => { | |
| btn.onclick = () => copyToClipboard(btn.getAttribute('data-copy'), btn); | |
| }); | |
| document.querySelectorAll('.delete-btn').forEach(btn => { | |
| btn.onclick = () => deleteFile(btn.getAttribute('data-name')); | |
| }); | |
| document.querySelectorAll('.unzip-btn').forEach(btn => { | |
| btn.onclick = () => unzipFile(btn.getAttribute('data-name')); | |
| }); | |
| } | |
| async function zipSelectedFiles() { | |
| const checked = Array.from(document.querySelectorAll('.file-checkbox:checked')).map(c => c.getAttribute('data-name')); | |
| if (checked.length === 0) { | |
| alert('Pehle kuch files select karo (checkbox se).'); | |
| return; | |
| } | |
| const archiveName = prompt('Archive ka naam (optional):', 'archive') || 'archive'; | |
| zipSelectedBtn.disabled = true; | |
| const oldText = zipSelectedBtn.innerHTML; | |
| zipSelectedBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Zipping...'; | |
| try { | |
| const res = await fetch('/api/zip', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json', 'X-User-Id': userId }, | |
| body: JSON.stringify({ files: checked, name: archiveName }) | |
| }); | |
| if (!res.ok) { | |
| const err = await res.json().catch(() => ({})); | |
| throw new Error(err.detail || 'Zip failed'); | |
| } | |
| const data = await res.json(); | |
| await loadFiles(); | |
| alert(`✅ Zip ban gaya: ${data.name}\nLink: ${data.url}`); | |
| } catch (e) { | |
| alert('Zip failed: ' + e.message); | |
| } finally { | |
| zipSelectedBtn.disabled = false; | |
| zipSelectedBtn.innerHTML = oldText; | |
| } | |
| } | |
| async function unzipFile(name) { | |
| if (!confirm('Is zip file ko extract karna hai?')) return; | |
| try { | |
| const res = await fetch('/api/unzip', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json', 'X-User-Id': userId }, | |
| body: JSON.stringify({ file: name }) | |
| }); | |
| if (!res.ok) { | |
| const err = await res.json().catch(() => ({})); | |
| throw new Error(err.detail || 'Unzip failed'); | |
| } | |
| const data = await res.json(); | |
| await loadFiles(); | |
| alert(`✅ ${data.count} file(s) extracted!\nView: ${data.view_url}`); | |
| } catch (e) { | |
| alert('Unzip failed: ' + e.message); | |
| } | |
| } | |
| window.copySetupCmd = () => { | |
| const text = document.getElementById('cli-setup-cmd').innerText; | |
| navigator.clipboard.writeText(text).then(() => { | |
| alert('Setup command copied! Paste it in your terminal.'); | |
| }); | |
| }; | |
| function copyToClipboard(text, btn) { | |
| navigator.clipboard.writeText(text).then(() => { | |
| const icon = btn.querySelector('i'); | |
| icon.className = 'fas fa-check'; | |
| setTimeout(() => icon.className = 'fas fa-copy', 2000); | |
| }); | |
| } | |
| async function deleteFile(name) { | |
| if (!confirm('Delete this file?')) return; | |
| try { | |
| await fetch(`/delete/${name}`, { | |
| method: 'DELETE', | |
| headers: { 'X-User-Id': userId } | |
| }); | |
| loadFiles(); | |
| } catch (error) { | |
| alert('Delete failed'); | |
| } | |
| } | |
| function getFileIcon(filename) { | |
| const ext = filename.split('.').pop().toLowerCase(); | |
| const icons = { | |
| pdf: 'fas fa-file-pdf', png: 'fas fa-file-image', jpg: 'fas fa-file-image', | |
| zip: 'fas fa-file-archive', mp3: 'fas fa-file-audio', mp4: 'fas fa-file-video' | |
| }; | |
| return icons[ext] || 'fas fa-file'; | |
| } | |
| function formatBytes(bytes) { | |
| if (bytes === 0) return '0 B'; | |
| const i = Math.floor(Math.log(bytes) / Math.log(1024)); | |
| return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + ['B', 'KB', 'MB', 'GB'][i]; | |
| } | |
| }); | |