improving look and feel

This commit is contained in:
2025-04-14 20:47:26 -04:00
parent 29c358298b
commit 68ed19766d
12 changed files with 695 additions and 42 deletions

View File

@@ -4,6 +4,8 @@ from flask import Flask, request, jsonify, send_from_directory
from werkzeug.utils import secure_filename
import requests
import utils.mLogger as log
from controllers.file_controller import upload_file, download_file
from views import views
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'tmp/uploads'
@@ -11,46 +13,13 @@ app.config['UPLOAD_FOLDER'] = 'tmp/uploads'
if not os.path.exists(app.config['UPLOAD_FOLDER']):
os.makedirs(app.config['UPLOAD_FOLDER'])
# TinyURL API for generating short URLs
def generate_tiny_url(long_url):
response = requests.get(f'http://tinyurl.com/api-create.php?url={long_url}')
return response.text if response.status_code == 200 else None
# Route for file uploads
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
log.e("No File Part")
return jsonify({'error': 'No file part'}), 400
app.route('/upload', methods=['POST'])(upload_file)
file = request.files['file']
if file.filename == '':
log.e("No selected file")
return jsonify({'error': 'No selected file'}), 400
# Route for downloading the file
app.route('/download/<code>', methods=['GET'])(download_file)
filename = secure_filename(file.filename)
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
log.i(f"File upload: {file_path}")
file.save(file_path)
# Generate a download link
download_url = request.host_url + 'download/' + filename
tiny_url = generate_tiny_url(download_url)
return jsonify({'tiny_url': tiny_url}), 200
# Route for downloading the file (one-time)
@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
if os.path.exists(file_path):
# Serve the file and then delete it
response = send_from_directory(app.config['UPLOAD_FOLDER'], filename)
os.remove(file_path)
return response
else:
return jsonify({'error': 'File not found'}), 404
app.register_blueprint(views)
if __name__ == '__main__':
log.i("Running flask in debug...")

View File

View File

@@ -0,0 +1,135 @@
import os
import random
import string
import json
from datetime import datetime, timedelta
from flask import request, jsonify, send_from_directory, render_template
from werkzeug.utils import secure_filename
import utils.mLogger as log
from models.file_metadata import FileMetadata
# Make UPLOAD_FOLDER absolute
UPLOAD_FOLDER = os.path.abspath('tmp/uploads')
METADATA_FILE = 'file_metadata.json'
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
def load_metadata():
if os.path.exists(METADATA_FILE):
with open(METADATA_FILE, 'r') as f:
return json.load(f)
return {}
def save_metadata(metadata):
with open(METADATA_FILE, 'w') as f:
json.dump(metadata, f)
def generate_unique_code():
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
def upload_file():
if 'file' not in request.files:
log.e("No File Part")
return jsonify({'error': 'No file part'}), 400
file = request.files['file']
if file.filename == '':
log.e("No selected file")
return jsonify({'error': 'No selected file'}), 400
filename = secure_filename(file.filename)
file_path = os.path.join(UPLOAD_FOLDER, filename)
log.i(f"File upload: {file_path}")
file.save(file_path)
# Generate a unique 6-digit alphanumeric code
code = generate_unique_code()
# Get metadata from request
max_downloads = int(request.form.get('max_downloads', 1))
expiry_hours = int(request.form.get('expiry_hours', 24))
expiry_time = datetime.now() + timedelta(hours=expiry_hours)
# Save metadata
metadata = load_metadata()
metadata[code] = {
'filename': filename,
'path': file_path,
'max_downloads': max_downloads,
'downloads': 0,
'expiry_time': expiry_time.isoformat()
}
save_metadata(metadata)
return jsonify({'code': code}), 200
def download_file(code):
metadata = load_metadata()
if code not in metadata:
return render_template('error.html',
error_title='Invalid Code',
error_message='The code you entered is invalid or incorrect. Please check your code and try again.'
), 404
file_info = metadata[code]
file_path = file_info['path']
expiry_time = datetime.fromisoformat(file_info['expiry_time'])
# Check expiry
if datetime.now() > expiry_time:
del metadata[code]
save_metadata(metadata)
return render_template('error.html',
error_title='File Expired',
error_message='This file has expired and is no longer available for download.'
), 404
# Check download limit
if file_info['downloads'] >= file_info['max_downloads']:
del metadata[code]
save_metadata(metadata)
return render_template('error.html',
error_title='Download Limit Reached',
error_message='This file has reached its maximum number of downloads and is no longer available.'
), 404
# Serve the file
if os.path.exists(file_path):
file_info['downloads'] += 1
if file_info['downloads'] >= file_info['max_downloads']:
os.remove(file_path)
del metadata[code]
save_metadata(metadata)
directory = os.path.dirname(file_path)
filename = os.path.basename(file_path)
return send_from_directory(
directory,
filename,
as_attachment=True,
download_name=file_info['filename']
)
else:
del metadata[code]
save_metadata(metadata)
return render_template('error.html',
error_title='File Not Found',
error_message='The requested file could not be found on the server.'
), 404
def cleanup_expired_files():
metadata = load_metadata()
updated_metadata = {}
for code, file_info in metadata.items():
expiry_time = datetime.fromisoformat(file_info['expiry_time'])
if datetime.now() > expiry_time or file_info['downloads'] >= file_info['max_downloads']:
# Remove the file if it exists
if os.path.exists(file_info['path']):
os.remove(file_info['path'])
else:
updated_metadata[code] = file_info
save_metadata(updated_metadata)
log.i("Cleanup completed: Expired and overused files removed.")

0
src/models/__init__.py Normal file
View File

View File

@@ -0,0 +1,23 @@
import os
import time
class FileMetadata:
def __init__(self, code, file_path, max_downloads=1, expiry_hours=24):
self.code = code
self.file_path = file_path
self.max_downloads = max_downloads
self.expiry_time = time.time() + (expiry_hours * 3600)
self.download_count = 0
def is_expired(self):
return time.time() > self.expiry_time
def increment_download_count(self):
self.download_count += 1
def can_download(self):
return self.download_count < self.max_downloads and not self.is_expired()
def delete_file(self):
if os.path.exists(self.file_path):
os.remove(self.file_path)

88
src/templates/error.html Normal file
View File

@@ -0,0 +1,88 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Error - File Download</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
color: #2d3748;
}
.container {
background: rgba(255, 255, 255, 0.95);
padding: 2.5rem;
border-radius: 1rem;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
width: 90%;
max-width: 450px;
text-align: center;
backdrop-filter: blur(10px);
}
.error-icon {
font-size: 4rem;
color: #e53e3e;
margin-bottom: 1rem;
}
h1 {
color: #2d3748;
font-size: 1.75rem;
margin-bottom: 1rem;
font-weight: 600;
}
.error-message {
color: #4a5568;
margin-bottom: 2rem;
line-height: 1.5;
}
.back-button {
background-color: #4299e1;
color: white;
padding: 0.75rem 1.5rem;
border: none;
border-radius: 0.75rem;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
text-decoration: none;
display: inline-block;
transition: all 0.2s;
}
.back-button:hover {
background-color: #3182ce;
transform: translateY(-1px);
}
.back-button:active {
transform: translateY(0);
}
</style>
</head>
<body>
<div class="container">
<div class="error-icon">⚠️</div>
<h1>{{ error_title }}</h1>
<p class="error-message">{{ error_message }}</p>
<a href="/" class="back-button">Try Another Code</a>
</div>
</body>
</html>

238
src/templates/index.html Normal file
View File

@@ -0,0 +1,238 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Download File</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
color: #2d3748;
}
.container {
background: rgba(255, 255, 255, 0.95);
padding: 2.5rem;
border-radius: 1rem;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
width: 90%;
max-width: 450px;
backdrop-filter: blur(10px);
transition: transform 0.2s;
}
.container:hover {
transform: translateY(-2px);
}
h1 {
color: #2d3748;
font-size: 1.75rem;
margin-bottom: 1.5rem;
text-align: center;
font-weight: 600;
}
.code-input {
display: flex;
gap: 0.5rem;
justify-content: center;
margin-bottom: 1.5rem;
}
.code-input input {
width: 3.5rem;
height: 3.5rem;
font-size: 1.5rem;
text-align: center;
border: 2px solid #e2e8f0;
border-radius: 0.75rem;
background: white;
outline: none;
transition: all 0.2s;
}
.code-input input:focus {
border-color: #4299e1;
box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.15);
}
button {
width: 100%;
background-color: #4299e1;
color: white;
padding: 0.75rem;
border: none;
border-radius: 0.75rem;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
}
button:hover {
background-color: #3182ce;
transform: translateY(-1px);
}
button:active {
transform: translateY(0);
}
button:disabled {
background-color: #a0aec0;
cursor: not-allowed;
transform: none;
}
.message {
margin-top: 1rem;
padding: 0.75rem;
border-radius: 0.5rem;
text-align: center;
display: none;
}
.message.error {
background-color: #fff5f5;
color: #c53030;
border: 1px solid #feb2b2;
}
.message.success {
background-color: #f0fff4;
color: #2f855a;
border: 1px solid #9ae6b4;
}
.spinner {
display: none;
width: 1.25rem;
height: 1.25rem;
border: 2px solid white;
border-top-color: transparent;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
</style>
<script>
document.addEventListener('DOMContentLoaded', () => {
const form = document.querySelector('form');
const inputs = document.querySelectorAll('.code-input input');
const button = document.querySelector('button');
const spinner = document.querySelector('.spinner');
const message = document.querySelector('.message');
const showMessage = (text, type) => {
message.textContent = text;
message.className = 'message ' + type;
message.style.display = 'block';
setTimeout(() => {
message.style.display = 'none';
}, 5000);
};
inputs.forEach((input, index) => {
input.addEventListener('input', (e) => {
const value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '');
e.target.value = value;
if (value && index < inputs.length - 1) {
inputs[index + 1].focus();
}
const isComplete = Array.from(inputs).every(input => input.value.length === 1);
button.disabled = !isComplete;
});
input.addEventListener('keydown', (e) => {
if (e.key === 'Backspace' && !e.target.value && index > 0) {
inputs[index - 1].focus();
}
});
// Allow pasting the entire code
input.addEventListener('paste', (e) => {
e.preventDefault();
const pastedText = e.clipboardData.getData('text').toUpperCase().replace(/[^A-Z0-9]/g, '');
if (pastedText.length === 6) {
inputs.forEach((input, i) => {
input.value = pastedText[i] || '';
});
button.disabled = false;
}
});
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
const code = Array.from(inputs).map(input => input.value).join('');
if (code.length !== 6) {
showMessage('Please enter a valid 6-character code.', 'error');
return;
}
button.disabled = true;
spinner.style.display = 'block';
button.textContent = 'Downloading...';
try {
window.location.assign(`/download/${code}`);
showMessage('Download started!', 'success');
} catch (error) {
showMessage('Error starting download. Please try again.', 'error');
} finally {
setTimeout(() => {
button.disabled = false;
spinner.style.display = 'none';
button.textContent = 'Download';
}, 2000);
}
});
});
</script>
</head>
<body>
<div class="container">
<h1>Enter Your 6-Digit Code</h1>
<form action="/download" method="GET">
<div class="code-input">
<input type="text" maxlength="1" required pattern="[A-Za-z0-9]" inputmode="text" autocomplete="off">
<input type="text" maxlength="1" required pattern="[A-Za-z0-9]" inputmode="text" autocomplete="off">
<input type="text" maxlength="1" required pattern="[A-Za-z0-9]" inputmode="text" autocomplete="off">
<input type="text" maxlength="1" required pattern="[A-Za-z0-9]" inputmode="text" autocomplete="off">
<input type="text" maxlength="1" required pattern="[A-Za-z0-9]" inputmode="text" autocomplete="off">
<input type="text" maxlength="1" required pattern="[A-Za-z0-9]" inputmode="text" autocomplete="off">
</div>
<button type="submit" disabled>
Download
<div class="spinner"></div>
</button>
<div class="message"></div>
</form>
</div>
</body>
</html>

View File

@@ -5,7 +5,7 @@ import os
'''
Constants
'''
LOG_FILE_NAME = "AngelEyes"
LOG_FILE_NAME = "SimpleFileUploader"
LEVEL_INFO = 1
LEVEL_WARNING = 2
LEVEL_ERROR = 3

7
src/views/__init__.py Normal file
View File

@@ -0,0 +1,7 @@
from flask import Blueprint, render_template
views = Blueprint('views', __name__)
@views.route('/')
def home():
return render_template('index.html')