Compare commits

..

2 Commits

Author SHA1 Message Date
052acdb394 minor fixes 2024-09-16 13:02:12 +02:00
3e40c79b81 raw embed fix 2024-09-16 12:53:05 +02:00
4 changed files with 88 additions and 48 deletions

65
app.py
View File

@ -236,23 +236,22 @@ def serve_user_page(username, filename=None):
@app.route('/<vanity>/raw', methods=['GET', 'POST']) @app.route('/<vanity>/raw', methods=['GET', 'POST'])
@app.route('/<vanity>/raw/<password>', methods=['GET', 'POST']) @app.route('/<vanity>/raw/<password>', methods=['GET', 'POST'])
def redirect_vanity(vanity, password=None): def redirect_vanity(vanity, password=None):
app.logger.info(f"Accessing vanity: {vanity}, password: {password}") app.logger.info(f"Accessing redirect_vanity: vanity={vanity}, password={password}")
app.logger.info(f"Request path: {request.path}")
app.logger.info(f"Request method: {request.method}")
app.logger.info(f"Request URL: {request.url}")
app.logger.info(f"Request endpoint: {request.endpoint}")
app.logger.info(f"Request view args: {request.view_args}")
db = get_db() db = get_db()
cursor = db.cursor() cursor = db.cursor()
is_download = 'download' in request.path is_download = 'download' in request.path
is_raw = 'raw' in request.path is_raw = 'raw' in request.path
# First, try to find the content with the full vanity (including extension)
cursor.execute("SELECT content.*, users.username FROM content LEFT JOIN users ON content.user_id = users.id WHERE content.vanity = ?", (vanity,)) cursor.execute("SELECT content.*, users.username FROM content LEFT JOIN users ON content.user_id = users.id WHERE content.vanity = ?", (vanity,))
content = cursor.fetchone() content = cursor.fetchone()
# If not found, try without the extension
if not content:
vanity_without_extension = os.path.splitext(vanity)[0]
cursor.execute("SELECT content.*, users.username FROM content LEFT JOIN users ON content.user_id = users.id WHERE content.vanity LIKE ?", (f"{vanity_without_extension}%",))
content = cursor.fetchone()
if content: if content:
content_type, content_data, created_at, user_id, is_private, stored_password, username = content[1], content[2], content[3], content[4], content[5], content[6], content[7] content_type, content_data, created_at, user_id, is_private, stored_password, username = content[1], content[2], content[3], content[4], content[5], content[6], content[7]
app.logger.info(f"Content found: type={content_type}, data={content_data}, is_private={is_private}") app.logger.info(f"Content found: type={content_type}, data={content_data}, is_private={is_private}")
@ -283,9 +282,9 @@ def redirect_vanity(vanity, password=None):
is_embeddable = file_extension in ['.jpg', '.jpeg', '.png', '.gif', '.svg', '.pdf'] is_embeddable = file_extension in ['.jpg', '.jpeg', '.png', '.gif', '.svg', '.pdf']
file_url = url_for('redirect_vanity', vanity=vanity, _external=True) file_url = url_for('redirect_vanity', vanity=vanity, _external=True)
if is_download or (not is_embeddable and not is_raw): if is_download:
return send_file(file_path, as_attachment=True) return send_file(file_path, as_attachment=True)
elif is_raw and is_embeddable: elif is_raw:
return send_file(file_path) return send_file(file_path)
else: else:
return render_template('file_info.html', return render_template('file_info.html',
@ -1073,13 +1072,17 @@ def rename_user_file(username):
@app.route('/upload/file', methods=['POST']) @app.route('/upload/file', methods=['POST'])
def upload_file(): def upload_file():
app.logger.info("Starting file upload process")
if 'file' not in request.files: if 'file' not in request.files:
app.logger.error("No file part in the request")
return jsonify({'success': False, 'error': 'No file part'}), 400 return jsonify({'success': False, 'error': 'No file part'}), 400
file = request.files['file'] file = request.files['file']
if file.filename == '': if file.filename == '':
app.logger.error("No selected file")
return jsonify({'success': False, 'error': 'No selected file'}), 400 return jsonify({'success': False, 'error': 'No selected file'}), 400
if file: if file:
try: try:
app.logger.info(f"Processing file: {file.filename}")
filename = secure_filename(file.filename) filename = secure_filename(file.filename)
extension = os.path.splitext(filename)[1].lower() extension = os.path.splitext(filename)[1].lower()
vanity = shortuuid.uuid()[:8] vanity = shortuuid.uuid()[:8]
@ -1087,23 +1090,56 @@ def upload_file():
new_filename = vanity_with_extension new_filename = vanity_with_extension
file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], new_filename) file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], new_filename)
app.logger.info(f"Saving file to: {file_path}")
file.save(file_path) file.save(file_path)
user_id = current_user.id if current_user.is_authenticated else None user_id = current_user.id if current_user.is_authenticated else None
app.logger.info(f"User ID: {user_id}")
password = request.form.get('password') password = request.form.get('password')
is_private = 1 if password else 0 is_private = 1 if password else 0
app.logger.info(f"Is private: {is_private}")
db = get_db() db = get_db()
cursor = db.cursor() cursor = db.cursor()
app.logger.info("Inserting file info into database")
cursor.execute("INSERT INTO content (vanity, type, data, created_at, user_id, is_private, password) VALUES (?, ?, ?, ?, ?, ?, ?)", cursor.execute("INSERT INTO content (vanity, type, data, created_at, user_id, is_private, password) VALUES (?, ?, ?, ?, ?, ?, ?)",
(vanity_with_extension, 'file', new_filename, datetime.now(), user_id, is_private, password)) (vanity_with_extension, 'file', new_filename, datetime.now(), user_id, is_private, password))
db.commit() db.commit()
short_url = url_for('redirect_vanity', vanity=vanity_with_extension, _external=True) # Determine the scheme based on the original request
short_url = short_url.replace('/download', '') scheme = 'https' if request.is_secure else 'http'
app.logger.info(f"Using scheme: {scheme}")
app.logger.info("Generating URLs")
app.logger.info(f"vanity_with_extension: {vanity_with_extension}")
# Log the URL generation process step by step
app.logger.info("Generating short URL:")
app.logger.info(f"1. Calling url_for with: 'redirect_vanity', vanity={vanity_with_extension}")
app.logger.info(f" Full parameters: endpoint='redirect_vanity', vanity={vanity_with_extension}, _external=True, _scheme={scheme}")
# Capture the result of url_for and remove the /raw suffix
short_url = url_for('redirect_vanity', vanity=vanity_with_extension, _external=True, _scheme=scheme)
short_url = short_url.rstrip('/raw')
app.logger.info(f"2. Result of url_for (after removing /raw): {short_url}")
app.logger.info(f"3. Inspecting short_url:")
app.logger.info(f" - Base: {short_url.split('?')[0]}")
app.logger.info(f" - Query parameters: {short_url.split('?')[1] if '?' in short_url else 'None'}")
app.logger.info("Generating download URL:")
download_url = short_url + '/download' download_url = short_url + '/download'
deletion_url = url_for('delete_content', vanity=vanity_with_extension, _external=True) app.logger.info(f"4. Download URL: {download_url}")
app.logger.info("Generating deletion URL:")
app.logger.info(f"5. Calling url_for with: 'delete_content', vanity={vanity_with_extension}")
app.logger.info(f" Full parameters: endpoint='delete_content', vanity={vanity_with_extension}, _external=True, _scheme={scheme}")
# Capture the result of url_for for deletion
deletion_url = url_for('delete_content', vanity=vanity_with_extension, _external=True, _scheme=scheme)
app.logger.info(f"6. Result of deletion url_for: {deletion_url}")
# Add debug logging # Add debug logging
app.logger.info(f"File uploaded: {new_filename}") app.logger.info(f"File uploaded: {new_filename}")
@ -1113,12 +1149,14 @@ def upload_file():
# Check if the request is from ShareX # Check if the request is from ShareX
if 'X-API-Key' in request.headers: if 'X-API-Key' in request.headers:
app.logger.info("Request from ShareX detected")
return json.dumps({ return json.dumps({
'status': 'success', 'status': 'success',
'url': short_url, 'url': short_url,
'deletion_url': deletion_url, 'deletion_url': deletion_url,
}) })
else: else:
app.logger.info("Returning JSON response")
return jsonify({ return jsonify({
'success': True, 'success': True,
'vanity': vanity_with_extension, 'vanity': vanity_with_extension,
@ -1131,6 +1169,7 @@ def upload_file():
app.logger.error(f"Error uploading file: {str(e)}") app.logger.error(f"Error uploading file: {str(e)}")
return jsonify({'success': False, 'error': str(e)}), 500 return jsonify({'success': False, 'error': str(e)}), 500
app.logger.error("Unknown error occurred")
return jsonify({'success': False, 'error': 'Unknown error occurred'}), 500 return jsonify({'success': False, 'error': 'Unknown error occurred'}), 500
# Add this function to validate passwords # Add this function to validate passwords

View File

@ -9,7 +9,7 @@
<meta property="og:url" content="{{ request.url }}"> <meta property="og:url" content="{{ request.url }}">
<meta property="og:description" content="File size: {{ file_size|filesizeformat }} | Uploaded by: {{ username }} | Date: {{ created_at.strftime('%Y-%m-%d %H:%M:%S') }}"> <meta property="og:description" content="File size: {{ file_size|filesizeformat }} | Uploaded by: {{ username }} | Date: {{ created_at.strftime('%Y-%m-%d %H:%M:%S') }}">
{% if is_embeddable %} {% if is_embeddable %}
<meta property="og:image" content="{{ file_url }}"> <meta property="og:image" content="{{ file_url }}/raw">
{% endif %} {% endif %}
<meta property="og:site_name" content="sxbin"> <meta property="og:site_name" content="sxbin">
<meta property="theme-color" content="#4CAF50"> <meta property="theme-color" content="#4CAF50">
@ -110,20 +110,21 @@
<div class="info-item"><strong>File size:</strong> {{ file_size|filesizeformat }}</div> <div class="info-item"><strong>File size:</strong> {{ file_size|filesizeformat }}</div>
<div class="info-item"><strong>Uploaded by:</strong> {{ username }}</div> <div class="info-item"><strong>Uploaded by:</strong> {{ username }}</div>
<div class="info-item"><strong>Date:</strong> {{ created_at.strftime('%Y-%m-%d %H:%M:%S') }}</div> <div class="info-item"><strong>Date:</strong> {{ created_at.strftime('%Y-%m-%d %H:%M:%S') }}</div>
<div class="info-item"><strong>File type:</strong> {{ filename.split('.')[-1].upper() if '.' in filename else 'Unknown' }}</div>
{% if is_embeddable %} {% if is_embeddable %}
<div class="embed-container"> <div class="embed-container">
{% if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.gif', '.svg')) %} {% if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.gif', '.svg')) %}
<img src="{{ file_url }}" alt="{{ filename }}"> <img src="{{ file_url }}/raw" alt="{{ filename }}">
{% elif filename.lower().endswith('.pdf') %} {% elif filename.lower().endswith('.pdf') %}
<embed src="{{ file_url }}" type="application/pdf" width="100%" height="600px"> <embed src="{{ file_url }}/raw" type="application/pdf" width="100%" height="600px">
{% endif %} {% endif %}
</div> </div>
{% endif %} {% endif %}
<div class="btn-container"> <div class="btn-container">
<a href="{{ url_for('redirect_vanity', vanity=vanity, _external=True) }}/download" class="btn">Download</a> <a href="{{ file_url }}/download" class="btn">Download</a>
<a href="{{ url_for('redirect_vanity', vanity=vanity, _external=True) }}/raw" class="btn">View Raw</a> <a href="{{ file_url }}/raw" class="btn">View Raw</a>
{% if current_user.is_authenticated and current_user.id == user_id %} {% if current_user.is_authenticated and current_user.id == user_id %}
{% if filename.lower().endswith(('.txt', '.html', '.css', '.js', '.py', '.md')) or '.' not in filename %} {% if filename.lower().endswith(('.txt', '.html', '.css', '.js', '.py', '.md')) or '.' not in filename %}
<a href="{{ url_for('edit_content', vanity=vanity) }}" class="btn edit-btn">Edit</a> <a href="{{ url_for('edit_content', vanity=vanity) }}" class="btn edit-btn">Edit</a>

View File

@ -9,14 +9,14 @@
<meta property="og:url" content="{{ request.url }}"> <meta property="og:url" content="{{ request.url }}">
<meta property="og:description" content="File size: {{ file_size|filesizeformat }} | Uploaded by: {{ username }} | Date: {{ created_at.strftime('%Y-%m-%d %H:%M:%S') }}"> <meta property="og:description" content="File size: {{ file_size|filesizeformat }} | Uploaded by: {{ username }} | Date: {{ created_at.strftime('%Y-%m-%d %H:%M:%S') }}">
{% if is_embeddable %} {% if is_embeddable %}
<meta property="og:image" content="{{ file_url }}"> <meta property="og:image" content="{{ file_url }}/raw">
{% endif %} {% endif %}
<meta property="og:site_name" content="sxbin"> <meta property="og:site_name" content="sxbin">
<meta property="theme-color" content="#4CAF50"> <meta property="theme-color" content="#4CAF50">
</head> </head>
<body> <body>
<script> <script>
window.location.href = "{{ file_url }}/download"; window.location.href = "{{ file_url }}";
</script> </script>
</body> </body>
</html> </html>

View File

@ -3,11 +3,14 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pastebin {{ vanity }} - sxbin</title> <title>{{ filename }} - sxbin</title>
<meta property="og:title" content="Pastebin {{ vanity }} - sxbin"> <meta property="og:title" content="{{ filename }}">
<meta property="og:type" content="website"> <meta property="og:type" content="website">
<meta property="og:url" content="{{ request.url }}"> <meta property="og:url" content="{{ request.url }}">
<meta property="og:description" content="{{ content.data[:200] }}"> <meta property="og:description" content="File size: {{ file_size|filesizeformat }} | Uploaded by: {{ username }} | Date: {{ created_at.strftime('%Y-%m-%d %H:%M:%S') }}">
{% if is_embeddable %}
<meta property="og:image" content="{{ file_url }}">
{% endif %}
<meta property="og:site_name" content="sxbin"> <meta property="og:site_name" content="sxbin">
<meta property="theme-color" content="#4CAF50"> <meta property="theme-color" content="#4CAF50">
<style> <style>
@ -149,25 +152,32 @@
<body> <body>
<a href="/" class="home-button">&#8962;</a> <a href="/" class="home-button">&#8962;</a>
<div class="container"> <div class="container">
<h2>Content</h2> <h2>{{ filename }}</h2>
<p>Uploaded by: {{ content.username }}</p> <div class="info-item"><strong>File size:</strong> {{ file_size|filesizeformat }}</div>
<p>Created at: {{ created_at }}</p> <div class="info-item"><strong>Uploaded by:</strong> {{ username }}</div>
<div class="info-item"><strong>Date:</strong> {{ created_at.strftime('%Y-%m-%d %H:%M:%S') }}</div>
<div class="highlight"> {% if is_embeddable %}
{{ highlighted_content|safe }} <div class="embed-container">
</div> {% if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.gif', '.svg')) %}
<div class="btn-container"> <img src="{{ file_url }}/raw" alt="{{ filename }}">
<button onclick="copyToClipboard()" class="btn">Copy</button> {% elif filename.lower().endswith('.pdf') %}
<a href="{{ url_for('raw_vanity', vanity=vanity) }}" class="btn">View Raw</a> <embed src="{{ file_url }}/raw" type="application/pdf" width="100%" height="600px">
{% if current_user.is_authenticated and current_user.id == content.user_id %}
<a href="{{ url_for('edit_content', vanity=vanity) }}" class="btn">Edit</a>
{% if is_private %}
<button onclick="openEditPasswordModal()" class="btn">Edit Password</button>
{% else %}
<button onclick="openAddPasswordModal()" class="btn">Add Password</button>
{% endif %} {% endif %}
<form action="{{ url_for('delete_content', vanity=vanity) }}" method="post"> </div>
<button type="submit" class="btn">Delete</button> {% else %}
<div class="info-item"><strong>File type:</strong> {{ filename.split('.')[-1].upper() if '.' in filename else 'Unknown' }}</div>
{% endif %}
<div class="btn-container">
<a href="{{ file_url }}/download" class="btn">Download</a>
<a href="{{ file_url }}/raw" class="btn">View Raw</a>
{% if current_user.is_authenticated and current_user.id == user_id %}
{% if filename.lower().endswith(('.txt', '.html', '.css', '.js', '.py', '.md')) or '.' not in filename %}
<a href="{{ url_for('edit_content', vanity=vanity) }}" class="btn edit-btn">Edit</a>
{% endif %}
<form action="{{ url_for('delete_content', vanity=vanity) }}" method="post" style="display: inline;">
<button type="submit" class="btn delete-btn" onclick="return confirm('Are you sure you want to delete this file?')">Delete</button>
</form> </form>
{% endif %} {% endif %}
</div> </div>
@ -184,16 +194,6 @@
</footer> </footer>
<script> <script>
const rawContent = {{ raw_content|tojson }};
function copyToClipboard() {
navigator.clipboard.writeText(rawContent).then(() => {
alert('Copied to clipboard!');
}).catch(err => {
console.error('Failed to copy text: ', err);
});
}
const themeToggle = document.getElementById('theme-toggle'); const themeToggle = document.getElementById('theme-toggle');
const html = document.documentElement; const html = document.documentElement;