#!/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 = """
đ ACCESS DENIED
đ
ACCESS DENIED
â YOUR IP HAS BEEN BANNED â
{banned_ip}
REASON:
{ban_reason}
BANNED AT:
{banned_time}
â° This ban is permanent
[SYSTEM] Unauthorized access attempt logged
[WARNING] Further attempts will be recorded
"""
# User HTML with credits link
USER_HTML = """
Fast File Server Pro
"""
# Admin HTML (simplified for space - same as before but with credits link)
ADMIN_HTML = """
đ Admin Panel
Reports
Files
Users
Banned
Ban User
IP:
đ Credits
"""
# 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()