folder uploads - beta - can be unstable as fuck

This commit is contained in:
realcgcristi 2024-09-09 12:12:57 +03:00
parent 6db56ef6aa
commit f2e4d9a571
3 changed files with 222 additions and 73 deletions

106
app.py
View File

@ -3,12 +3,12 @@ from werkzeug.utils import secure_filename
import shortuuid import shortuuid
import os import os
from datetime import datetime from datetime import datetime
import zipfile
app = Flask(__name__) app = Flask(__name__)
UPLOAD_FOLDER = './uploads' UPLOAD_FOLDER = './uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
if not os.path.exists(UPLOAD_FOLDER): if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER) os.makedirs(UPLOAD_FOLDER)
@ -52,13 +52,8 @@ def upload_pastebin():
created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S') created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
data_store[vanity] = {'type': 'pastebin', 'content': content, 'created_at': created_at} data_store[vanity] = {'type': 'pastebin', 'content': content, 'created_at': created_at}
html_content = render_template('content.html', content=content, created_at=created_at) html_content = render_template('content.html', content=content, created_at=created_at)
html_file_path = os.path.join('templates', f'{vanity}.html') html_file_path = os.path.join('templates', f'{vanity}.html')
with open(html_file_path, 'w') as f:
f.write(html_content)
html_content = render_template('raw.html', content=content)
html_file_path = os.path.join('templates', f'{vanity}raw.html')
with open(html_file_path, 'w') as f: with open(html_file_path, 'w') as f:
f.write(html_content) f.write(html_content)
@ -78,7 +73,6 @@ def upload_file():
file.save(filepath) file.save(filepath)
data_store[vanity] = {'type': 'file', 'filename': filename} data_store[vanity] = {'type': 'file', 'filename': filename}
file_info = { file_info = {
'name': filename, 'name': filename,
'size': os.path.getsize(filepath), 'size': os.path.getsize(filepath),
@ -92,13 +86,45 @@ def upload_file():
return jsonify({'vanity': vanity}) return jsonify({'vanity': vanity})
def save_file(file, folder_path):
filename = secure_filename(file.filename)
file_path = os.path.join(folder_path, filename)
file.save(file_path)
def handle_uploaded_folder(files, base_path):
for file in files:
if file.filename.endswith('/'):
subfolder_path = os.path.join(base_path, secure_filename(file.filename))
os.makedirs(subfolder_path, exist_ok=True)
handle_uploaded_folder(request.files.getlist(file.filename), subfolder_path)
else:
save_file(file, base_path)
@app.route('/upload/folder', methods=['POST'])
def upload_folder():
if 'file' not in request.files:
return 'No files uploaded', 400
files = request.files.getlist('file')
if not files:
return 'No files selected', 400
vanity = shortuuid.uuid()[:6]
folder_path = os.path.join(app.config['UPLOAD_FOLDER'], vanity)
os.makedirs(folder_path)
handle_uploaded_folder(files, folder_path)
data_store[vanity] = {'type': 'folder', 'files': [file.filename for file in files]}
return jsonify({'vanity': vanity})
@app.route('/shorten', methods=['POST']) @app.route('/shorten', methods=['POST'])
def shorten_url(): def shorten_url():
original_url = request.form['url'] original_url = request.form['url']
vanity = shortuuid.uuid()[:6] vanity = shortuuid.uuid()[:6]
data_store[vanity] = {'type': 'url', 'url': original_url} data_store[vanity] = {'type': 'url', 'url': original_url}
html_content = f'<html><body><script>window.location.href="{original_url}";</script></body></html>' html_content = f'<html><body><script>window.location.href="{original_url}";</script></body></html>'
html_file_path = os.path.join('templates', f'{vanity}.html') html_file_path = os.path.join('templates', f'{vanity}.html')
with open(html_file_path, 'w') as f: with open(html_file_path, 'w') as f:
@ -112,10 +138,8 @@ def redirect_vanity(vanity):
if target: if target:
if target['type'] == 'pastebin': if target['type'] == 'pastebin':
return render_template(f'{vanity}.html') return render_template(f'{vanity}.html')
elif target['type'] == 'file': elif target['type'] == 'file':
file_path = os.path.join(app.config['UPLOAD_FOLDER'], f'{vanity}_{target["filename"]}') file_path = os.path.join(app.config['UPLOAD_FOLDER'], f'{vanity}_{target["filename"]}')
file_info = { file_info = {
'name': target['filename'], 'name': target['filename'],
@ -123,9 +147,11 @@ def redirect_vanity(vanity):
'modified_at': datetime.fromtimestamp(os.path.getmtime(file_path)).strftime('%Y-%m-%d %H:%M:%S'), 'modified_at': datetime.fromtimestamp(os.path.getmtime(file_path)).strftime('%Y-%m-%d %H:%M:%S'),
'url': url_for('download_file', vanity=vanity) 'url': url_for('download_file', vanity=vanity)
} }
return render_template('file.html', **file_info) return render_template('file.html', **file_info)
elif target['type'] == 'folder':
return redirect(url_for('folder_content', vanity=vanity))
elif target['type'] == 'url':
return render_template('content.html', url=target['url'])
return render_template('404.html'), 404 return render_template('404.html'), 404
@app.route('/<vanity>/raw', methods=['GET']) @app.route('/<vanity>/raw', methods=['GET'])
@ -134,11 +160,61 @@ def raw_vanity(vanity):
if target: if target:
if target['type'] == 'pastebin': if target['type'] == 'pastebin':
return render_template(f'{vanity}raw.html') return render_template(f'{vanity}raw.html')
return render_template('404.html'), 404 return render_template('404.html'), 404
@app.route('/folder/<vanity>', methods=['GET'])
def folder_content(vanity):
target = data_store.get(vanity)
if target and target['type'] == 'folder':
folder_path = os.path.join(app.config['UPLOAD_FOLDER'], vanity)
files = []
for root, _, filenames in os.walk(folder_path):
for filename in filenames:
file_path = os.path.join(root, filename)
relative_path = os.path.relpath(file_path, folder_path)
file_url = url_for('download_folder_file', vanity=vanity, file_name=relative_path)
files.append({'name': relative_path, 'url': file_url})
# Pagination
per_page = 10
page = int(request.args.get('page', 1))
start = (page - 1) * per_page
end = start + per_page
total_files = len(files)
files = files[start:end]
prev_url = url_for('folder_content', vanity=vanity, page=page-1) if page > 1 else None
next_url = url_for('folder_content', vanity=vanity, page=page+1) if end < total_files else None
return render_template('folder.html', files=files, prev_url=prev_url, next_url=next_url)
return 'Not Found', 404
@app.route('/folder/<vanity>/download', methods=['GET'])
def download_folder_as_zip(vanity):
target = data_store.get(vanity)
if target and target['type'] == 'folder':
folder_path = os.path.join(app.config['UPLOAD_FOLDER'], vanity)
zip_path = os.path.join(app.config['UPLOAD_FOLDER'], f'{vanity}.zip')
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, _, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
zipf.write(file_path, os.path.relpath(file_path, folder_path))
return send_from_directory(app.config['UPLOAD_FOLDER'], f'{vanity}.zip', as_attachment=True)
return 'Not Found', 404
@app.route('/folder/<vanity>/<file_name>', methods=['GET'])
def download_folder_file(vanity, file_name):
folder_path = os.path.join(app.config['UPLOAD_FOLDER'], vanity)
file_path = os.path.join(folder_path, file_name)
if os.path.isfile(file_path):
return send_from_directory(folder_path, file_name, as_attachment=True)
return 'Not Found', 404
if __name__ == '__main__': if __name__ == '__main__':
app.run(debug=True,port=7123) app.run(debug=True, port=7123)

57
templates/folder.html Normal file
View File

@ -0,0 +1,57 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Folder</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #121212;
color: #e0e0e0;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background: #1e1e1e;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
padding: 20px;
width: 400px;
text-align: center;
}
h1 {
margin-bottom: 20px;
color: #f5f5f5;
}
ul {
list-style-type: none;
padding: 0;
}
li {
margin: 10px 0;
}
a {
color: #61afef;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="container">
<h1>Folder</h1>
<ul>
{% for file in files %}
<li><a href="{{ file.url }}">{{ file.name }}</a></li>
{% endfor %}
</ul>
</div>
</body>
</html>

View File

@ -75,8 +75,7 @@
color: #f5f5f5; color: #f5f5f5;
} }
.footer {
.footer {
background-color: #2c2f33; background-color: #2c2f33;
color: #99aab5; color: #99aab5;
padding: 10px 0; padding: 10px 0;
@ -85,23 +84,22 @@
width: 100%; width: 100%;
text-align: center; text-align: center;
font-size: 14px; font-size: 14px;
} }
.footer a { .footer a {
color: #61afef; color: #61afef;
text-decoration: none; text-decoration: none;
} }
.footer a:hover { .footer a:hover {
text-decoration: underline; text-decoration: underline;
} }
.footer .container { .footer .container {
max-width: 1200px; max-width: 1200px;
margin: 0 auto; margin: 0 auto;
padding: 0 15px; padding: 0 15px;
} }
</style> </style>
</head> </head>
@ -111,6 +109,7 @@
<div class="upload-options"> <div class="upload-options">
<button id="textUploadBtn" onclick="showForm('text')">Upload Text</button> <button id="textUploadBtn" onclick="showForm('text')">Upload Text</button>
<button id="fileUploadBtn" onclick="showForm('file')">Upload File</button> <button id="fileUploadBtn" onclick="showForm('file')">Upload File</button>
<button id="folderUploadBtn" onclick="showForm('folder')">Upload Folder</button>
<button id="urlShortenerBtn" onclick="showForm('url')">Shorten URL</button> <button id="urlShortenerBtn" onclick="showForm('url')">Shorten URL</button>
</div> </div>
<div id="uploadFormContainer"> <div id="uploadFormContainer">
@ -130,6 +129,14 @@
</form> </form>
<div id="fileResult" class="result"></div> <div id="fileResult" class="result"></div>
</div> </div>
<div id="folderForm" class="upload-form">
<h2>Upload Folder</h2>
<form enctype="multipart/form-data">
<input type="file" name="file" webkitdirectory directory />
<button type="button" onclick="uploadFolder()">Upload Folder</button>
</form>
<div id="folderResult" class="result"></div>
</div>
<div id="urlForm" class="upload-form"> <div id="urlForm" class="upload-form">
<h2>Shorten URL</h2> <h2>Shorten URL</h2>
<form> <form>
@ -140,67 +147,76 @@
</div> </div>
</div> </div>
</div> </div>
<script> <script>
function showForm(type) { function showForm(type) {
document.getElementById('textForm').classList.remove('active'); document.querySelectorAll('.upload-form').forEach(form => {
document.getElementById('fileForm').classList.remove('active'); form.classList.remove('active');
document.getElementById('urlForm').classList.remove('active'); });
document.getElementById('textUploadBtn').classList.remove('active'); document.getElementById(type + 'Form').classList.add('active');
document.getElementById('fileUploadBtn').classList.remove('active');
document.getElementById('urlShortenerBtn').classList.remove('active');
if (type === 'text') {
document.getElementById('textForm').classList.add('active');
document.getElementById('textUploadBtn').classList.add('active');
} else if (type === 'file') {
document.getElementById('fileForm').classList.add('active');
document.getElementById('fileUploadBtn').classList.add('active');
} else if (type === 'url') {
document.getElementById('urlForm').classList.add('active');
document.getElementById('urlShortenerBtn').classList.add('active');
}
} }
function uploadText() { function uploadText() {
const form = document.querySelector('#textForm form'); const content = document.querySelector('#textForm textarea').value;
const formData = new FormData(form);
fetch('/upload/pastebin', { fetch('/upload/pastebin', {
method: 'POST', method: 'POST',
body: formData headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({ content }),
}) })
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
document.getElementById('textResult').innerHTML = `Text uploaded! <a href="/${data.vanity}">View Link</a>`; document.getElementById('textResult').innerHTML = `Text uploaded. Access it <a href="/${data.vanity}">here</a>.`;
}); });
} }
function uploadFile() { function uploadFile() {
const form = document.querySelector('#fileForm form'); const formData = new FormData();
const formData = new FormData(form); formData.append('file', document.querySelector('#fileForm input[type="file"]').files[0]);
fetch('/upload/file', { fetch('/upload/file', {
method: 'POST', method: 'POST',
body: formData body: formData,
}) })
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
document.getElementById('fileResult').innerHTML = `File uploaded! <a href="/${data.vanity}">Download Link</a>`; document.getElementById('fileResult').innerHTML = `File uploaded. Download it <a href="/download/${data.vanity}">here</a>.`;
});
}
function uploadFolder() {
const files = document.querySelector('#folderForm input[type="file"]').files;
if (files.length === 0) {
alert('Please select a folder.');
return;
}
const formData = new FormData();
for (const file of files) {
formData.append('file', file);
}
fetch('/upload/folder', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => {
document.getElementById('folderResult').innerHTML = `Folder uploaded. View its contents <a href="/${data.vanity}">here</a>.`;
}); });
} }
function shortenUrl() { function shortenUrl() {
const form = document.querySelector('#urlForm form'); const url = document.querySelector('#urlForm input[name="url"]').value;
const formData = new FormData(form);
fetch('/shorten', { fetch('/shorten', {
method: 'POST', method: 'POST',
body: formData headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({ url }),
}) })
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
document.getElementById('urlResult').innerHTML = `URL shortened! <a href="/${data.vanity}">View Link</a>`; document.getElementById('urlResult').innerHTML = `URL shortened. Access it <a href="/${data.vanity}">here</a>.`;
}); });
} }
</script> </script>