File size: 11,283 Bytes
6ea4293
 
 
 
 
 
a6dbd9e
6ea4293
 
bf75543
 
6ea4293
fced522
bf75543
 
 
 
 
 
 
 
 
 
1f5ec06
 
bf75543
 
 
 
 
 
1f5ec06
 
6ea4293
 
 
fced522
 
 
 
 
 
 
 
 
 
a6dbd9e
fced522
 
 
 
 
 
 
 
 
 
 
 
 
 
6ea4293
 
fced522
6ea4293
 
fced522
 
 
 
 
 
6ea4293
 
 
 
 
 
fced522
6ea4293
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fced522
6ea4293
 
 
 
 
fced522
6ea4293
fced522
 
 
6ea4293
fced522
6ea4293
 
1f5ec06
6ea4293
 
 
 
 
fced522
6ea4293
1f5ec06
fced522
1f5ec06
fced522
6ea4293
 
 
fced522
 
6ea4293
 
 
 
fced522
 
6ea4293
 
 
 
 
 
 
a6dbd9e
 
6ea4293
 
a6dbd9e
fced522
6ea4293
 
 
 
1f5ec06
 
fced522
1f5ec06
 
 
fced522
1f5ec06
6ea4293
 
 
a6dbd9e
fced522
 
6ea4293
fced522
 
 
 
 
 
 
 
 
 
a6dbd9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ea4293
 
46bab04
 
 
 
 
 
 
fced522
6ea4293
fced522
 
 
6ea4293
fced522
6ea4293
fced522
 
6ea4293
1f5ec06
 
fced522
1f5ec06
6ea4293
 
fced522
6ea4293
fced522
6ea4293
 
 
 
fced522
 
6ea4293
 
 
 
fced522
 
 
 
6ea4293
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
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];
    }
});