Spaces:
Paused
Paused
File size: 8,912 Bytes
108d181 6ef73e5 108d181 8a93644 108d181 6ef73e5 108d181 6ef73e5 108d181 8a93644 108d181 6ef73e5 108d181 8a93644 108d181 8a93644 108d181 6ef73e5 108d181 6ef73e5 cbef08f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
from flask import Flask, request, jsonify, Response, render_template_string, make_response
import random
import string
import html
import os
import sqlite3
from werkzeug.utils import secure_filename
app = Flask(__name__)
# Initialize SQLite database
def init_db():
conn = sqlite3.connect('/tmp/files.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS files
(code TEXT PRIMARY KEY, content TEXT)''')
conn.commit()
conn.close()
init_db()
def generate_unique_code():
chars = string.ascii_letters + string.digits
while True:
code = ''.join(random.choice(chars) for _ in range(6))
conn = sqlite3.connect('/tmp/files.db')
c = conn.cursor()
c.execute("SELECT code FROM files WHERE code = ?", (code,))
if not c.fetchone():
conn.close()
return code
conn.close()
def escape_html(unsafe):
return html.escape(unsafe)
@app.route('/', methods=['GET', 'POST'])
def handle_request():
if request.method == 'POST':
content = None
if 'multipart/form-data' in request.content_type:
if 'file' not in request.files:
return Response("No file uploaded", status=400)
file = request.files['file']
if file.filename == '':
return Response("No file selected", status=400)
content = file.read().decode('utf-8')
elif request.content_type == 'application/json':
data = request.get_json()
content = data.get('text')
if not content:
return Response("No text provided", status=400)
else:
return Response("Unsupported content type", status=400)
unique_code = generate_unique_code()
conn = sqlite3.connect('/tmp/files.db')
c = conn.cursor()
c.execute("INSERT INTO files (code, content) VALUES (?, ?)", (unique_code, content))
conn.commit()
conn.close()
domain = request.host
return jsonify({
'code': unique_code,
'url': f"https://{domain}/{unique_code}",
'rawUrl': f"https://{domain}/{unique_code}/raw"
})
# For GET requests to root, show the form
return render_template_string('''
<!DOCTYPE html>
<html>
<head>
<title>Code Share</title>
<style>
body { font-family: sans-serif; margin: 0; padding: 20px; }
.container { max-width: 800px; margin: 0 auto; }
.panel { background: #f4f4f4; padding: 20px; border-radius: 5px; margin-bottom: 20px; }
input[type="file"] { margin: 10px 0; }
textarea { width: 100%; height: 200px; margin: 10px 0; padding: 10px; border: 1px solid #ddd; border-radius: 5px; }
button { background: #0066cc; color: white; border: none; padding: 10px 15px;
border-radius: 5px; cursor: pointer; margin-right: 10px; }
button:hover { background: #0052a3; }
.tabs { display: flex; margin-bottom: 15px; }
.tab { padding: 10px 15px; cursor: pointer; border: 1px solid #ddd; border-radius: 5px 5px 0 0; margin-right: 5px; }
.tab.active { background: #f4f4f4; border-bottom: none; }
h2 { margin-top: 0; }
</style>
</head>
<body>
<div class="container">
<h1>Code Share</h1>
<div class="tabs">
<div class="tab active" onclick="switchTab('upload')">Upload File</div>
<div class="tab" onclick="switchTab('paste')">Paste Code</div>
</div>
<div id="uploadPanel" class="panel">
<h2>Upload a File</h2>
<form id="uploadForm" method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">Upload</button>
</form>
</div>
<div id="pastePanel" class="panel" style="display: none;">
<h2>Paste Your Code</h2>
<textarea id="codeText" placeholder="Paste your code here..."></textarea>
<button onclick="submitPastedCode()">Save</button>
</div>
<div id="result" style="margin-top: 20px;"></div>
</div>
<script>
function switchTab(tabName) {
if (tabName === 'upload') {
document.getElementById('uploadPanel').style.display = 'block';
document.getElementById('pastePanel').style.display = 'none';
document.querySelector('.tab:nth-child(1)').classList.add('active');
document.querySelector('.tab:nth-child(2)').classList.remove('active');
} else {
document.getElementById('uploadPanel').style.display = 'none';
document.getElementById('pastePanel').style.display = 'block';
document.querySelector('.tab:nth-child(1)').classList.remove('active');
document.querySelector('.tab:nth-child(2)').classList.add('active');
}
}
document.getElementById('uploadForm').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
try {
const response = await fetch('/', {
method: 'POST',
body: formData
});
const data = await response.json();
displayResult(data);
} catch (error) {
document.getElementById('result').innerHTML = '<p>Error: ' + error.message + '</p>';
}
});
async function submitPastedCode() {
const text = document.getElementById('codeText').value;
if (!text.trim()) {
alert('Please enter some code');
return;
}
try {
const response = await fetch('/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ text })
});
const data = await response.json();
displayResult(data);
} catch (error) {
document.getElementById('result').innerHTML = '<p>Error: ' + error.message + '</p>';
}
}
function displayResult(data) {
document.getElementById('result').innerHTML =
'<p>Code saved successfully!</p>' +
'<p>Code: <strong>' + data.code + '</strong></p>' +
'<p>URL: <a href="' + data.url + '">' + data.url + '</a></p>' +
'<p>Raw URL: <a href="' + data.rawUrl + '">' + data.rawUrl + '</a></p>';
}
</script>
</body>
</html>
''')
@app.route('/<code>', methods=['GET'])
def view_file(code):
return view_file_internal(code, False)
@app.route('/<code>/raw', methods=['GET'])
def view_raw_file(code):
return view_file_internal(code, True)
def view_file_internal(code, is_raw):
conn = sqlite3.connect('/tmp/files.db')
c = conn.cursor()
c.execute("SELECT content FROM files WHERE code = ?", (code,))
result = c.fetchone()
conn.close()
if not result:
return Response("File not found", status=404)
content = result[0]
if is_raw:
return Response(content, mimetype='text/plain')
else:
return render_template_string('''
<!DOCTYPE html>
<html>
<head>
<title>File {{ code }}</title>
<style>
body { font-family: sans-serif; margin: 0; padding: 20px; }
pre { background: #f4f4f4; padding: 10px; border-radius: 5px; overflow-x: auto; }
.container { max-width: 800px; margin: 0 auto; }
.header { display: flex; justify-content: space-between; align-items: center; }
.raw-link { text-decoration: none; color: #0066cc; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>File: {{ code }}</h1>
<a href="/{{ code }}/raw" class="raw-link">View Raw</a>
</div>
<pre>{{ content | e }}</pre>
</div>
</body>
</html>
''', code=code, content=escape_html(content))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860) |