fast-file-server / data.py
legenedserver's picture
Upload 4 files
2d83740 verified
Raw History Blame Contribute Delete
48.6 kB
#!/usr/bin/env python3 """ Fast File Server Pro - With Credits System """ import asyncio import os import json import time import hashlib import secrets from pathlib import Path from urllib.parse import quote from datetime import datetime, timedelta from collections import defaultdict, deque from aiohttp import web, WSMsgType # Configuration UPLOAD_DIR = Path("uploads") CHUNK_SIZE = 2 * 1024 * 1024 PORT = 8888 ADMIN_PASSWORD = "adminass" # Create directories UPLOAD_DIR.mkdir(exist_ok=True) # Store data banned_ips = {} websocket_clients = set() file_notifications = [] reports = [] speed_history = deque(maxlen=100) admin_sessions = set() file_owners = {} user_activity = defaultdict(list) # Load credits page with open('credits.html', 'r') as f: CREDITS_HTML = f.read() # Ban page template BAN_PAGE_TEMPLATE = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>πŸ”’ ACCESS DENIED</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Courier New', monospace; background: #0a0a0a; color: #ff0000; min-height: 100vh; display: flex; justify-content: center; align-items: center; overflow: hidden; } .bg-glitch { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: repeating-linear-gradient(0deg, rgba(255,0,0,0.03) 0px, rgba(255,0,0,0.03) 2px, transparent 2px, transparent 4px); pointer-events: none; } .container { text-align: center; padding: 40px; position: relative; z-index: 1; max-width: 800px; } .lock-icon { font-size: 8em; animation: pulse 2s ease-in-out infinite; } @keyframes pulse { 0%, 100% { transform: scale(1); opacity: 0.8; } 50% { transform: scale(1.1); opacity: 1; } } .glitch-text { font-size: 3em; font-weight: bold; text-transform: uppercase; margin: 20px 0; text-shadow: 3px 3px 0 #ff0000, -3px -3px 0 #0000ff; animation: glitch 0.5s infinite; } @keyframes glitch { 0% { transform: translate(0); } 20% { transform: translate(-2px, 2px); } 40% { transform: translate(2px, -2px); } 60% { transform: translate(-1px, -1px); } 80% { transform: translate(1px, 1px); } 100% { transform: translate(0); } } .warning-box { border: 3px solid #ff0000; padding: 30px; margin: 30px 0; background: rgba(255,0,0,0.05); box-shadow: 0 0 30px rgba(255,0,0,0.3); } .info-label { color: #ff4444; font-size: 0.9em; text-transform: uppercase; letter-spacing: 3px; margin-bottom: 10px; } .info-value { color: #ffffff; font-size: 1.2em; margin-bottom: 20px; } .ip-display { font-size: 1.5em; color: #ff0000; background: rgba(0,0,0,0.5); padding: 15px; border: 2px solid #ff0000; display: inline-block; margin: 10px 0; } .countdown { color: #ff8800; font-size: 1.2em; margin-top: 20px; } canvas { position: fixed; top: 0; left: 0; pointer-events: none; z-index: 0; } </style> </head> <body> <div class="bg-glitch"></div> <canvas id="matrixRain"></canvas> <div class="container"> <div class="lock-icon">πŸ”’</div> <div class="glitch-text">ACCESS DENIED</div> <div class="warning-box"> <div class="info-label">⚠ YOUR IP HAS BEEN BANNED ⚠</div> <div class="ip-display">{banned_ip}</div> <div class="info-label">REASON:</div> <div class="info-value">{ban_reason}</div> <div class="info-label">BANNED AT:</div> <div class="info-value">{banned_time}</div> <div class="countdown">⏰ This ban is permanent</div> </div> <div style="color: #666; font-size: 0.8em;"> [SYSTEM] Unauthorized access attempt logged<br> [WARNING] Further attempts will be recorded </div> </div> <script> const canvas = document.getElementById('matrixRain'); const ctx = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; const chars = '01をむウエγ‚ͺγ‚«γ‚­γ‚―γ‚±γ‚³'; const fontSize = 14; const columns = canvas.width / fontSize; const drops = Array(Math.floor(columns)).fill(0); function draw() { ctx.fillStyle = 'rgba(0, 0, 0, 0.05)'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = '#0F0'; ctx.font = fontSize + 'px monospace'; for (let i = 0; i < drops.length; i++) { ctx.fillText(chars[Math.floor(Math.random() * chars.length)], i * fontSize, drops[i] * fontSize); if (drops[i] * fontSize > canvas.height && Math.random() > 0.975) drops[i] = 0; drops[i]++; } } setInterval(draw, 50); // Auto-check if still banned setInterval(() => { fetch('/check-ban').then(r => { if (r.status !== 403) window.location.href = '/'; else location.reload(); }).catch(() => location.reload()); }, 1000); </script> </body> </html> """ # User HTML with credits link USER_HTML = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fast File Server Pro</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: linear-gradient(135deg, #0f0c29, #302b63, #24243e); min-height: 100vh; padding: 20px; color: white; } .header { background: rgba(255,255,255,0.1); backdrop-filter: blur(10px); padding: 20px; border-radius: 20px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; } .container { max-width: 1400px; margin: 0 auto; display: grid; grid-template-columns: 1fr 350px; gap: 20px; } .main-content { background: rgba(255,255,255,0.1); backdrop-filter: blur(10px); border-radius: 20px; padding: 30px; } .sidebar { background: rgba(255,255,255,0.1); backdrop-filter: blur(10px); border-radius: 20px; padding: 20px; max-height: 80vh; overflow-y: auto; } .upload-area { text-align: center; padding: 20px; } .upload-btn { background: linear-gradient(135deg, #667eea, #764ba2); color: white; border: none; padding: 20px 40px; border-radius: 30px; font-size: 1.2em; cursor: pointer; transition: all 0.3s ease; } .upload-btn:hover { transform: translateY(-3px); } .upload-modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); justify-content: center; align-items: center; z-index: 10000; } .upload-modal.active { display: flex; } .upload-popup { background: linear-gradient(135deg, #1e1e2f, #2d2d44); border: 2px solid rgba(102,126,234,0.5); border-radius: 30px; padding: 40px; width: 500px; max-width: 90%; } .file-drop-zone { border: 3px dashed rgba(102,126,234,0.5); border-radius: 20px; padding: 40px; text-align: center; margin: 20px 0; cursor: pointer; } .file-drop-zone.dragover { border-color: #667eea; background: rgba(102,126,234,0.1); } .progress-bar { width: 100%; height: 30px; background: rgba(255,255,255,0.1); border-radius: 15px; overflow: hidden; margin: 15px 0; } .progress-fill { height: 100%; background: linear-gradient(90deg, #667eea, #764ba2); width: 0%; transition: width 0.3s ease; display: flex; align-items: center; justify-content: center; font-weight: bold; } .file-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px; max-height: 500px; overflow-y: auto; padding: 10px; } .file-card { background: rgba(255,255,255,0.05); border-radius: 15px; padding: 15px; transition: all 0.3s ease; } .file-card:hover { background: rgba(255,255,255,0.1); transform: translateY(-3px); } .btn { padding: 10px 20px; border: none; border-radius: 20px; cursor: pointer; font-size: 0.9em; margin: 3px; transition: all 0.3s ease; } .btn-download { background: rgba(39,174,96,0.2); color: #27ae60; border: 1px solid #27ae60; } .btn-report { background: rgba(241,196,15,0.2); color: #f1c40f; border: 1px solid #f1c40f; } .btn-cancel { background: rgba(231,76,60,0.2); color: #e74c3c; border: 1px solid #e74c3c; } .btn:hover { transform: translateY(-2px); } .online-users { list-style: none; } .online-user { display: flex; justify-content: space-between; align-items: center; padding: 10px; background: rgba(255,255,255,0.05); margin: 5px 0; border-radius: 10px; } .online-dot { width: 10px; height: 10px; background: #27ae60; border-radius: 50%; display: inline-block; margin-right: 10px; } .search-box { width: 100%; padding: 12px; background: rgba(255,255,255,0.05); border: 2px solid rgba(255,255,255,0.1); border-radius: 25px; color: white; margin-bottom: 15px; } .footer { text-align: center; padding: 20px; margin-top: 20px; background: rgba(255,255,255,0.05); border-radius: 15px; font-size: 0.9em; color: #999; } .credits-link { color: #667eea; text-decoration: none; cursor: pointer; transition: all 0.3s ease; font-weight: bold; } .credits-link:hover { color: #764ba2; text-shadow: 0 0 10px rgba(102,126,234,0.5); } </style> </head> <body> <div class="header"> <h1>πŸš€ Fast File Server Pro</h1> <div> <span id="onlineCount" style="margin-right: 20px;">πŸ‘₯ 0 online</span> </div> </div> <div class="container"> <div class="main-content"> <div class="upload-area"> <button class="upload-btn" onclick="openUploadModal()">πŸ“€ Upload Files</button> </div> <input type="text" class="search-box" id="searchBox" placeholder="πŸ” Search files..." onkeyup="filterFiles()"> <div class="file-grid" id="fileGrid"> <p style="text-align: center; grid-column: 1/-1;">Loading files...</p> </div> </div> <div class="sidebar"> <h3>πŸ‘₯ Online Users</h3> <ul class="online-users" id="onlineUsersList"></ul> <h3 style="margin-top: 20px;">πŸ“’ Recent Uploads</h3> <div id="recentUploads"></div> </div> </div> <div class="footer"> <p>Fast File Server Pro v2.0 β€’ <a href="/credits" class="credits-link">🌟 Credits</a></p> </div> <div class="upload-modal" id="uploadModal"> <div class="upload-popup"> <h2>πŸ“€ Upload Files</h2> <div class="file-drop-zone" id="fileDropZone"> <p>πŸ“ Drop files here or click to select</p> <input type="file" id="fileInput" multiple style="display: none;"> </div> <div id="selectedFiles"></div> <div class="progress-bar" id="progressBar" style="display: none;"> <div class="progress-fill" id="progressFill">0%</div> </div> <div style="display: flex; gap: 10px; margin-top: 15px;"> <button class="btn btn-download" onclick="startUpload()" style="flex: 1;">Start Upload</button> <button class="btn btn-cancel" onclick="cancelUpload()" style="flex: 1;">Cancel</button> <button class="btn" onclick="closeUploadModal()" style="flex: 1; background: rgba(255,255,255,0.1);">Close</button> </div> </div> </div> <script> let selectedFiles = []; let uploadAbortController = null; let ws; function connectWebSocket() { ws = new WebSocket(`ws://${window.location.host}/ws`); ws.onmessage = (event) => { const data = JSON.parse(event.data); if (data.type === 'file_uploaded') { loadFiles(); } }; ws.onclose = () => setTimeout(connectWebSocket, 2000); } function openUploadModal() { document.getElementById('uploadModal').classList.add('active'); } function closeUploadModal() { if (uploadAbortController) { if (confirm('Upload in progress. Cancel?')) cancelUpload(); else return; } document.getElementById('uploadModal').classList.remove('active'); resetUpload(); } function resetUpload() { selectedFiles = []; document.getElementById('selectedFiles').innerHTML = ''; document.getElementById('progressBar').style.display = 'none'; document.getElementById('progressFill').style.width = '0%'; uploadAbortController = null; } const dropZone = document.getElementById('fileDropZone'); const fileInput = document.getElementById('fileInput'); dropZone.addEventListener('click', () => fileInput.click()); dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('dragover'); }); dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover')); dropZone.addEventListener('drop', (e) => { e.preventDefault(); dropZone.classList.remove('dragover'); handleFiles(Array.from(e.dataTransfer.files)); }); fileInput.addEventListener('change', (e) => { handleFiles(Array.from(e.target.files)); fileInput.value = ''; }); function handleFiles(files) { selectedFiles = [...selectedFiles, ...files]; document.getElementById('selectedFiles').innerHTML = selectedFiles.map((f, i) => ` <div style="padding:8px; background:rgba(255,255,255,0.05); margin:5px 0; border-radius:8px; display:flex; justify-content:space-between;"> <span>πŸ“„ ${f.name} (${formatSize(f.size)})</span> <button onclick="removeFile(${i})" style="background:none; border:none; color:red; cursor:pointer;">βœ•</button> </div> `).join(''); } function removeFile(index) { selectedFiles.splice(index, 1); document.getElementById('selectedFiles').innerHTML = selectedFiles.map((f, i) => ` <div style="padding:8px; background:rgba(255,255,255,0.05); margin:5px 0; border-radius:8px; display:flex; justify-content:space-between;"> <span>πŸ“„ ${f.name} (${formatSize(f.size)})</span> <button onclick="removeFile(${i})" style="background:none; border:none; color:red; cursor:pointer;">βœ•</button> </div> `).join(''); } async function startUpload() { if (selectedFiles.length === 0) { alert('Select files first!'); return; } uploadAbortController = new AbortController(); document.getElementById('progressBar').style.display = 'block'; const totalSize = selectedFiles.reduce((sum, f) => sum + f.size, 0); let uploaded = 0; for (const file of selectedFiles) { const formData = new FormData(); formData.append('file', file); try { const xhr = new XMLHttpRequest(); await new Promise((resolve, reject) => { xhr.upload.addEventListener('progress', (e) => { if (e.lengthComputable) { const current = uploaded + e.loaded; const progress = (current / totalSize) * 100; document.getElementById('progressFill').style.width = progress + '%'; document.getElementById('progressFill').textContent = progress.toFixed(1) + '%'; } }); xhr.addEventListener('load', () => xhr.status === 200 ? resolve() : reject(new Error('Failed'))); xhr.addEventListener('error', () => reject(new Error('Network error'))); xhr.addEventListener('abort', () => reject(new Error('Cancelled'))); uploadAbortController.signal.addEventListener('abort', () => xhr.abort()); xhr.open('POST', '/upload'); xhr.send(formData); }); uploaded += file.size; } catch (error) { if (error.message !== 'Cancelled') alert(`Failed: ${file.name}`); break; } } if (uploaded === totalSize) alert('All files uploaded!'); resetUpload(); loadFiles(); } function cancelUpload() { if (uploadAbortController) { uploadAbortController.abort(); uploadAbortController = null; } } async function loadFiles() { try { const response = await fetch('/files'); const files = await response.json(); const grid = document.getElementById('fileGrid'); if (files.length === 0) { grid.innerHTML = '<p style="text-align:center; grid-column:1/-1;">No files yet</p>'; return; } grid.innerHTML = files.map(f => ` <div class="file-card"> <div style="font-size:2em; text-align:center;">πŸ“„</div> <div style="font-weight:bold; word-break:break-word;">${f.name}</div> <div style="font-size:0.85em; color:#999;">${formatSize(f.size)}</div> <div style="display:flex; gap:5px; margin-top:10px;"> <button class="btn btn-download" onclick="downloadFile('${f.name}')">⬇ Download</button> <button class="btn btn-report" onclick="reportFile('${f.name}')">🚩 Report</button> </div> </div> `).join(''); } catch (error) { console.error(error); } } async function loadOnlineUsers() { try { const response = await fetch('/online-users'); const users = await response.json(); document.getElementById('onlineCount').textContent = `πŸ‘₯ ${users.length} online`; document.getElementById('onlineUsersList').innerHTML = users.map(u => ` <li class="online-user"><span><span class="online-dot"></span>${u.ip}</span></li> `).join('') || '<li>No users online</li>'; } catch (error) { console.error(error); } } function downloadFile(filename) { const link = document.createElement('a'); link.href = `/download/${encodeURIComponent(filename)}`; link.download = filename; document.body.appendChild(link); link.click(); document.body.removeChild(link); } async function reportFile(filename) { const reason = prompt('Why report this file?'); if (reason) { await fetch('/report', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({filename, reason}) }); alert('Report submitted!'); } } function filterFiles() { const query = document.getElementById('searchBox').value.toLowerCase(); document.querySelectorAll('.file-card').forEach(card => { const name = card.querySelector('div:nth-child(2)').textContent.toLowerCase(); card.style.display = name.includes(query) ? 'block' : 'none'; }); } function formatSize(bytes) { if (bytes < 1024) return bytes + ' B'; if (bytes < 1024*1024) return (bytes/1024).toFixed(2) + ' KB'; if (bytes < 1024*1024*1024) return (bytes/(1024*1024)).toFixed(2) + ' MB'; return (bytes/(1024*1024*1024)).toFixed(2) + ' GB'; } connectWebSocket(); loadFiles(); loadOnlineUsers(); setInterval(loadOnlineUsers, 5000); setInterval(loadFiles, 10000); </script> </body> </html> """ # Admin HTML (simplified for space - same as before but with credits link) ADMIN_HTML = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>πŸ” Admin Panel</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Courier New', monospace; background: #0a0e27; color: #00ff00; min-height: 100vh; padding: 20px; } .header { background: linear-gradient(135deg, #1a1a2e, #16213e); border: 2px solid #00ff00; padding: 20px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; } .dashboard { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 20px; } .stat-card { background: rgba(0,255,0,0.05); border: 1px solid #00ff00; padding: 20px; text-align: center; } .stat-value { font-size: 2.5em; font-weight: bold; } .stat-label { text-transform: uppercase; font-size: 0.8em; color: #00aa00; } .section { background: rgba(0,0,0,0.3); border: 1px solid #00ff00; margin-bottom: 20px; padding: 20px; } .section h2 { border-bottom: 1px solid #00ff00; padding-bottom: 10px; margin-bottom: 20px; text-transform: uppercase; } table { width: 100%; border-collapse: collapse; } th { text-align: left; padding: 10px; border-bottom: 2px solid #00ff00; text-transform: uppercase; font-size: 0.8em; } td { padding: 10px; border-bottom: 1px solid rgba(0,255,0,0.2); } .btn { padding: 8px 15px; border: none; cursor: pointer; font-family: 'Courier New', monospace; text-transform: uppercase; font-size: 0.8em; margin: 2px; } .btn-delete { background: #ff0000; color: white; } .btn-ban { background: #ff8800; color: white; } .btn-unban { background: #00aa00; color: white; } .btn-view { background: #0088ff; color: white; } .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); justify-content: center; align-items: center; z-index: 1000; } .modal.active { display: flex; } .modal-content { background: #0a0e27; border: 2px solid #00ff00; padding: 30px; max-width: 500px; width: 90%; } input, textarea { width: 100%; padding: 10px; margin: 10px 0; background: rgba(0,255,0,0.05); border: 1px solid #00ff00; color: #00ff00; font-family: 'Courier New', monospace; } .tabs { display: flex; gap: 10px; margin-bottom: 20px; } .tab { padding: 10px 20px; background: rgba(0,255,0,0.05); border: 1px solid #00ff00; cursor: pointer; text-transform: uppercase; } .tab.active { background: rgba(0,255,0,0.2); } .tab-content { display: none; } .tab-content.active { display: block; } .credits-link { color: #00ff00; text-align: center; display: block; margin-top: 20px; } </style> </head> <body> <div class="header"> <h1>πŸ” GeoFile Admin Panel</h1> <div> <span>Administrator</span> <button class="btn btn-delete" onclick="logout()">Logout</button> </div> </div> <div class="dashboard"> <div class="stat-card"><div class="stat-label">Files</div><div class="stat-value" id="totalFiles">0</div></div> <div class="stat-card"><div class="stat-label">Online</div><div class="stat-value" id="onlineUsers">0</div></div> <div class="stat-card"><div class="stat-label">Banned</div><div class="stat-value" style="color:#ff0000;" id="bannedCount">0</div></div> <div class="stat-card"><div class="stat-label">Reports</div><div class="stat-value" style="color:#ff8800;" id="reportCount">0</div></div> </div> <div class="tabs"> <div class="tab active" onclick="switchTab('reports')">Reports</div> <div class="tab" onclick="switchTab('files')">Files</div> <div class="tab" onclick="switchTab('users')">Users</div> <div class="tab" onclick="switchTab('banned')">Banned</div> </div> <div class="tab-content active" id="reportsTab"> <div class="section"><h2>Reports</h2><div id="reportsList"></div></div> </div> <div class="tab-content" id="filesTab"> <div class="section"><h2>All Files</h2><div id="filesList"></div></div> </div> <div class="tab-content" id="usersTab"> <div class="section"><h2>Online Users</h2><div id="usersList"></div></div> </div> <div class="tab-content" id="bannedTab"> <div class="section"><h2>Banned IPs</h2> <div style="display:flex; gap:10px; margin-bottom:20px;"> <input type="text" id="banIP" placeholder="IP" style="flex:1;"> <input type="text" id="banReason" placeholder="Reason" style="flex:2;"> <button class="btn btn-ban" onclick="banNewIP()">Ban</button> </div> <div id="bannedList"></div> </div> </div> <div class="modal" id="banModal"> <div class="modal-content"> <h2>Ban User</h2> <p>IP: <span id="modalIP"></span></p> <textarea id="modalReason" rows="4" placeholder="Reason..."></textarea> <div style="display:flex; gap:10px; margin-top:15px;"> <button class="btn btn-ban" onclick="confirmBan()">Confirm</button> <button class="btn btn-unban" onclick="closeModal()">Cancel</button> </div> </div> </div> <a href="/credits" class="credits-link">🌟 Credits</a> <script> let sessionToken = localStorage.getItem('adminToken') || ''; let currentBanIP = ''; if (!sessionToken) { const password = prompt('Admin Password:'); if (password) login(password); else window.location.href = '/'; } else { loadAllData(); setInterval(loadAllData, 5000); } async function login(password) { const res = await fetch('/admingeo/login', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({password}) }); if (res.ok) { const data = await res.json(); sessionToken = data.token; localStorage.setItem('adminToken', sessionToken); loadAllData(); setInterval(loadAllData, 5000); } else { alert('Wrong password!'); window.location.href = '/'; } } async function loadAllData() { await Promise.all([loadReports(), loadFiles(), loadUsers(), loadBanned(), loadStats()]); } async function loadStats() { const res = await fetch('/admingeo/stats', {headers: {'X-Admin-Token': sessionToken}}); const stats = await res.json(); document.getElementById('totalFiles').textContent = stats.total_files; document.getElementById('onlineUsers').textContent = stats.online_users; document.getElementById('bannedCount').textContent = stats.banned_count; document.getElementById('reportCount').textContent = stats.report_count; } async function loadReports() { const res = await fetch('/admingeo/reports', {headers: {'X-Admin-Token': sessionToken}}); const reports = await res.json(); document.getElementById('reportsList').innerHTML = reports.length === 0 ? '<p>No reports</p>' : ` <table><thead><tr><th>File</th><th>Reported By</th><th>Uploader</th><th>Reason</th><th>Actions</th></tr></thead><tbody> ${reports.map(r => `<tr> <td>πŸ“„ ${r.filename}</td><td>${r.reported_by_ip}</td><td>${r.file_uploader_ip||'Unknown'}</td> <td style="color:#ff8800;">${r.reason}</td> <td> <button class="btn btn-delete" onclick="deleteFile('${r.filename}')">Delete</button> <button class="btn btn-ban" onclick="openBanModal('${r.file_uploader_ip}', '${r.filename}')">Ban</button> <button class="btn btn-view" onclick="dismissReport('${r.filename}')">Dismiss</button> </td> </tr>`).join('')}</tbody></table>`; } async function loadFiles() { const res = await fetch('/admingeo/files', {headers: {'X-Admin-Token': sessionToken}}); const files = await res.json(); document.getElementById('filesList').innerHTML = files.length === 0 ? '<p>No files</p>' : ` <table><thead><tr><th>File</th><th>Size</th><th>Uploader</th><th>Actions</th></tr></thead><tbody> ${files.map(f => `<tr> <td>πŸ“„ ${f.name}</td><td>${(f.size/(1024*1024)).toFixed(2)} MB</td><td>${f.uploader_ip||'Unknown'}</td> <td> <button class="btn btn-delete" onclick="deleteFile('${f.name}')">Delete</button> ${f.uploader_ip ? `<button class="btn btn-ban" onclick="openBanModal('${f.uploader_ip}')">Ban</button>` : ''} </td> </tr>`).join('')}</tbody></table>`; } async function loadUsers() { const res = await fetch('/admingeo/users', {headers: {'X-Admin-Token': sessionToken}}); const users = await res.json(); document.getElementById('usersList').innerHTML = users.length === 0 ? '<p>No users</p>' : ` <table><thead><tr><th>IP</th><th>Files</th><th>Actions</th></tr></thead><tbody> ${users.map(u => `<tr> <td>${u.ip}</td><td>${u.files_uploaded||0}</td> <td><button class="btn btn-ban" onclick="openBanModal('${u.ip}')">Ban</button></td> </tr>`).join('')}</tbody></table>`; } async function loadBanned() { const res = await fetch('/admingeo/banned', {headers: {'X-Admin-Token': sessionToken}}); const banned = await res.json(); document.getElementById('bannedList').innerHTML = banned.length === 0 ? '<p>No banned IPs</p>' : ` <table><thead><tr><th>IP</th><th>Reason</th><th>Actions</th></tr></thead><tbody> ${banned.map(b => `<tr> <td style="color:#ff0000;">${b.ip}</td><td style="color:#ff8800;">${b.reason}</td> <td><button class="btn btn-unban" onclick="unbanIP('${b.ip}')">Unban</button></td> </tr>`).join('')}</tbody></table>`; } async function deleteFile(filename) { if (!confirm(`Delete "${filename}"?`)) return; await fetch(`/admingeo/delete/${encodeURIComponent(filename)}`, {method: 'DELETE', headers: {'X-Admin-Token': sessionToken}}); loadAllData(); } function openBanModal(ip) { currentBanIP = ip; document.getElementById('modalIP').textContent = ip; document.getElementById('banModal').classList.add('active'); } function closeModal() { document.getElementById('banModal').classList.remove('active'); } async function confirmBan() { const reason = document.getElementById('modalReason').value || 'No reason'; await fetch('/admingeo/ban', { method: 'POST', headers: {'Content-Type': 'application/json', 'X-Admin-Token': sessionToken}, body: JSON.stringify({ip: currentBanIP, reason}) }); closeModal(); loadAllData(); } async function banNewIP() { const ip = document.getElementById('banIP').value; const reason = document.getElementById('banReason').value || 'No reason'; if (!ip) return alert('Enter IP!'); await fetch('/admingeo/ban', { method: 'POST', headers: {'Content-Type': 'application/json', 'X-Admin-Token': sessionToken}, body: JSON.stringify({ip, reason}) }); document.getElementById('banIP').value = ''; document.getElementById('banReason').value = ''; loadAllData(); } async function unbanIP(ip) { await fetch('/admingeo/unban', { method: 'POST', headers: {'Content-Type': 'application/json', 'X-Admin-Token': sessionToken}, body: JSON.stringify({ip}) }); loadAllData(); } async function dismissReport(filename) { await fetch(`/admingeo/dismiss-report/${encodeURIComponent(filename)}`, {method: 'DELETE', headers: {'X-Admin-Token': sessionToken}}); loadAllData(); } function switchTab(tabName) { document.querySelectorAll('.tab').forEach(t => t.classList.remove('active')); document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active')); event.target.classList.add('active'); document.getElementById(tabName + 'Tab').classList.add('active'); } function logout() { localStorage.removeItem('adminToken'); window.location.href = '/'; } </script> </body> </html> """ # Route handlers async def handle_index(request): if request.remote in banned_ips: ban_info = banned_ips[request.remote] return web.Response(text=BAN_PAGE_TEMPLATE.format( banned_ip=request.remote, ban_reason=ban_info.get('reason', 'Violation'), banned_time=datetime.fromtimestamp(ban_info.get('banned_at', time.time())).strftime('%Y-%m-%d %H:%M:%S') ), content_type='text/html', status=403) return web.Response(text=USER_HTML, content_type='text/html') async def handle_credits(request): return web.Response(text=CREDITS_HTML, content_type='text/html') async def handle_check_ban(request): if request.remote in banned_ips: return web.Response(status=403) return web.Response(text='OK') async def handle_admin_panel(request): return web.Response(text=ADMIN_HTML, content_type='text/html') async def handle_admin_login(request): try: data = await request.json() if data.get('password') == ADMIN_PASSWORD: token = secrets.token_hex(32) admin_sessions.add(token) return web.json_response({'success': True, 'token': token}) return web.json_response({'error': 'Invalid password'}, status=403) except: return web.json_response({'error': 'Invalid request'}, status=400) def verify_admin(request): return request.headers.get('X-Admin-Token', '') in admin_sessions async def handle_upload(request): if request.remote in banned_ips: return web.json_response({'error': 'Banned'}, status=403) reader = await request.multipart() field = await reader.next() if not field or field.name != 'file': return web.json_response({'error': 'No file'}, status=400) filename = Path(field.filename).name if field.filename else 'unknown' filepath = UPLOAD_DIR / filename counter = 1 while filepath.exists(): stem, suffix = filepath.stem, filepath.suffix filepath = UPLOAD_DIR / f"{stem}_{counter}{suffix}" counter += 1 try: size = 0 with open(filepath, 'wb') as f: while True: chunk = await field.read_chunk(CHUNK_SIZE) if not chunk: break f.write(chunk) size += len(chunk) file_owners[filepath.name] = request.remote for ws in websocket_clients.copy(): try: await ws.send_json({'type': 'file_uploaded', 'filename': filepath.name}) except: websocket_clients.discard(ws) return web.json_response({'success': True, 'filename': filepath.name, 'size': size}) except Exception as e: if filepath.exists(): filepath.unlink() return web.json_response({'error': str(e)}, status=500) async def handle_download(request): if request.remote in banned_ips: return web.Response(status=403) filename = request.match_info.get('filename') if '..' in filename or '/' in filename: return web.Response(status=400) filepath = UPLOAD_DIR / filename if not filepath.exists(): return web.Response(text='Not found', status=404) response = web.StreamResponse() response.headers['Content-Type'] = 'application/octet-stream' response.headers['Content-Disposition'] = f'attachment; filename="{quote(filename)}"' response.headers['Content-Length'] = str(filepath.stat().st_size) await response.prepare(request) with open(filepath, 'rb') as f: while True: chunk = f.read(CHUNK_SIZE) if not chunk: break await response.write(chunk) await asyncio.sleep(0) return response async def handle_list_files(request): files = [] for fp in UPLOAD_DIR.iterdir(): if fp.is_file(): s = fp.stat() files.append({'name': fp.name, 'size': s.st_size, 'modified': s.st_mtime}) files.sort(key=lambda x: x['modified'], reverse=True) return web.json_response(files) async def handle_report(request): try: data = await request.json() reports.append({ 'filename': data.get('filename'), 'reason': data.get('reason'), 'reported_by_ip': request.remote, 'file_uploader_ip': file_owners.get(data.get('filename'), 'Unknown'), 'reported_at': time.time() }) return web.json_response({'success': True}) except: return web.json_response({'error': 'Invalid'}, status=400) async def handle_online_users(request): users = [] seen = set() for ws in websocket_clients.copy(): if not ws.closed: try: ip = ws._req.remote if hasattr(ws, '_req') else 'Unknown' if ip not in seen: seen.add(ip) users.append({'ip': ip}) except: pass return web.json_response(users) async def ws_handler(request): ws = web.WebSocketResponse() await ws.prepare(request) websocket_clients.add(ws) try: async for _ in ws: pass finally: websocket_clients.discard(ws) return ws # Admin handlers async def admin_stats(request): if not verify_admin(request): return web.json_response({'error': 'Unauthorized'}, status=403) return web.json_response({ 'total_files': len(list(UPLOAD_DIR.iterdir())), 'online_users': len([w for w in websocket_clients if not w.closed]), 'banned_count': len(banned_ips), 'report_count': len(reports) }) async def admin_reports(request): if not verify_admin(request): return web.json_response({'error': 'Unauthorized'}, status=403) return web.json_response(reports) async def admin_files(request): if not verify_admin(request): return web.json_response({'error': 'Unauthorized'}, status=403) files = [] for fp in UPLOAD_DIR.iterdir(): if fp.is_file(): s = fp.stat() files.append({'name': fp.name, 'size': s.st_size, 'modified': s.st_mtime, 'uploader_ip': file_owners.get(fp.name, 'Unknown')}) files.sort(key=lambda x: x['modified'], reverse=True) return web.json_response(files) async def admin_users(request): if not verify_admin(request): return web.json_response({'error': 'Unauthorized'}, status=403) users = {} for ws in websocket_clients: if not ws.closed: try: ip = ws._req.remote if hasattr(ws, '_req') else 'Unknown' if ip not in users: users[ip] = {'ip': ip, 'files_uploaded': sum(1 for f, o in file_owners.items() if o == ip)} except: pass return web.json_response(list(users.values())) async def admin_banned(request): if not verify_admin(request): return web.json_response({'error': 'Unauthorized'}, status=403) return web.json_response([{'ip': ip, 'reason': i.get('reason', ''), 'banned_at': i.get('banned_at', 0)} for ip, i in banned_ips.items()]) async def admin_ban(request): if not verify_admin(request): return web.json_response({'error': 'Unauthorized'}, status=403) try: data = await request.json() ip, reason = data.get('ip'), data.get('reason', 'No reason') if not ip: return web.json_response({'error': 'No IP'}, status=400) banned_ips[ip] = {'reason': reason, 'banned_at': time.time(), 'banned_by': request.remote} # Delete their files for fn, owner in list(file_owners.items()): if owner == ip: (UPLOAD_DIR / fn).unlink(missing_ok=True) del file_owners[fn] # Disconnect for ws in websocket_clients.copy(): try: if hasattr(ws, '_req') and ws._req.remote == ip: await ws.close() except: pass return web.json_response({'success': True}) except Exception as e: return web.json_response({'error': str(e)}, status=500) async def admin_unban(request): if not verify_admin(request): return web.json_response({'error': 'Unauthorized'}, status=403) try: data = await request.json() ip = data.get('ip') if ip in banned_ips: del banned_ips[ip] return web.json_response({'success': True}) return web.json_response({'error': 'Not found'}, status=404) except: return web.json_response({'error': 'Invalid'}, status=400) async def admin_delete(request): if not verify_admin(request): return web.json_response({'error': 'Unauthorized'}, status=403) fn = request.match_info.get('filename') fp = UPLOAD_DIR / fn if fp.exists(): fp.unlink() if fn in file_owners: del file_owners[fn] return web.json_response({'success': True}) return web.json_response({'error': 'Not found'}, status=404) async def admin_dismiss(request): if not verify_admin(request): return web.json_response({'error': 'Unauthorized'}, status=403) fn = request.match_info.get('filename') global reports reports = [r for r in reports if r['filename'] != fn] return web.json_response({'success': True}) async def init_app(): app = web.Application(client_max_size=1024**4) app.router.add_get('/', handle_index) app.router.add_get('/credits', handle_credits) app.router.add_get('/check-ban', handle_check_ban) app.router.add_post('/upload', handle_upload) app.router.add_get('/download/{filename}', handle_download) app.router.add_get('/files', handle_list_files) app.router.add_post('/report', handle_report) app.router.add_get('/online-users', handle_online_users) app.router.add_get('/ws', ws_handler) app.router.add_get('/admingeo', handle_admin_panel) app.router.add_post('/admingeo/login', handle_admin_login) app.router.add_get('/admingeo/stats', admin_stats) app.router.add_get('/admingeo/reports', admin_reports) app.router.add_get('/admingeo/files', admin_files) app.router.add_get('/admingeo/users', admin_users) app.router.add_get('/admingeo/banned', admin_banned) app.router.add_post('/admingeo/ban', admin_ban) app.router.add_post('/admingeo/unban', admin_unban) app.router.add_delete('/admingeo/delete/{filename}', admin_delete) app.router.add_delete('/admingeo/dismiss-report/{filename}', admin_dismiss) return app def main(): print(""" ╔══════════════════════════════════════════╗ β•‘ πŸš€ Fast File Server Pro v2.0 β•‘ β•‘ http://localhost:8888 β•‘ β•‘ Admin: /admingeo | Pass: adminass β•‘ β•‘ Credits: /credits β•‘ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• """) app = init_app() web.run_app(app, host='0.0.0.0', port=PORT, print=lambda x: None) if __name__ == '__main__': main()
#!/usr/bin/env python3
"""
Fast File Server Pro - With Credits System
"""
import asyncio
import os
import json
import time
import hashlib
import secrets
from pathlib import Path
from urllib.parse import quote
from datetime import datetime, timedelta
from collections import defaultdict, deque
from aiohttp import web, WSMsgType
# Configuration
UPLOAD_DIR = Path("uploads")
CHUNK_SIZE = 2 * 1024 * 1024
PORT = 8888
ADMIN_PASSWORD = "adminass"
# Create directories
UPLOAD_DIR.mkdir(exist_ok=True)
# Store data
banned_ips = {}
websocket_clients = set()
file_notifications = []
reports = []
speed_history = deque(maxlen=100)
admin_sessions = set()
file_owners = {}
user_activity = defaultdict(list)
# Load credits page
with open('credits.html', 'r') as f:
CREDITS_HTML = f.read()
# Ban page template
BAN_PAGE_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>πŸ”’ ACCESS DENIED</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Courier New', monospace;
background: #0a0a0a;
color: #ff0000;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}
.bg-glitch {
position: fixed;
top: 0; left: 0;
width: 100%; height: 100%;
background: repeating-linear-gradient(0deg, rgba(255,0,0,0.03) 0px, rgba(255,0,0,0.03) 2px, transparent 2px, transparent 4px);
pointer-events: none;
}
.container {
text-align: center;
padding: 40px;
position: relative;
z-index: 1;
max-width: 800px;
}
.lock-icon {
font-size: 8em;
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { transform: scale(1); opacity: 0.8; }
50% { transform: scale(1.1); opacity: 1; }
}
.glitch-text {
font-size: 3em;
font-weight: bold;
text-transform: uppercase;
margin: 20px 0;
text-shadow: 3px 3px 0 #ff0000, -3px -3px 0 #0000ff;
animation: glitch 0.5s infinite;
}
@keyframes glitch {
0% { transform: translate(0); }
20% { transform: translate(-2px, 2px); }
40% { transform: translate(2px, -2px); }
60% { transform: translate(-1px, -1px); }
80% { transform: translate(1px, 1px); }
100% { transform: translate(0); }
}
.warning-box {