initial test version
This commit is contained in:
parent
d0ff7ffd3a
commit
d40befddd1
97
main.py
Executable file
97
main.py
Executable file
@ -0,0 +1,97 @@
|
||||
import os
|
||||
import uuid
|
||||
import time
|
||||
import json
|
||||
import threading
|
||||
from flask import Flask, request, redirect, send_from_directory, abort
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# config
|
||||
UPLOAD_FOLDER = './uploads'
|
||||
MAX_FILE_SIZE = 1024 * 1024 * 100 # last number = megabytes
|
||||
EXPIRATION_TIME = 60 * 60 * 24 * 7 # last number = days
|
||||
DATA_FILE = 'data.json'
|
||||
URL_PREFIX = 'http://localhost:5000/'
|
||||
|
||||
if not os.path.exists(UPLOAD_FOLDER):
|
||||
os.makedirs(UPLOAD_FOLDER)
|
||||
|
||||
def load_data():
|
||||
if os.path.exists(DATA_FILE):
|
||||
with open(DATA_FILE, 'r') as f:
|
||||
return json.load(f)
|
||||
return {}
|
||||
|
||||
data = load_data()
|
||||
|
||||
def save_data():
|
||||
with open(DATA_FILE, 'w') as f:
|
||||
json.dump(data, f)
|
||||
|
||||
def cleanup_files():
|
||||
while True:
|
||||
time.sleep(60 * 60)
|
||||
now = time.time()
|
||||
for key, item in list(data.items()):
|
||||
if 'expiry' in item and now > item['expiry']:
|
||||
try:
|
||||
os.remove(item['path'])
|
||||
except Exception as e:
|
||||
print(f"Error removing file {item['path']}: {e}")
|
||||
del data[key]
|
||||
save_data()
|
||||
|
||||
threading.Thread(target=cleanup_files, daemon=True).start()
|
||||
|
||||
@app.route('/', methods=['POST'])
|
||||
def upload_file():
|
||||
file = request.files.get('file')
|
||||
if not file:
|
||||
return "No file uploaded\n", 400
|
||||
if file.content_length > MAX_FILE_SIZE:
|
||||
return "File too large\n", 400
|
||||
|
||||
filename = file.filename
|
||||
key = uuid.uuid4().hex[:6]
|
||||
filepath = os.path.join(UPLOAD_FOLDER, f"{key}_{filename}")
|
||||
file.save(filepath)
|
||||
|
||||
data[key] = {
|
||||
'type': 'file',
|
||||
'path': filepath,
|
||||
'expiry': time.time() + EXPIRATION_TIME
|
||||
}
|
||||
save_data()
|
||||
return f"{URL_PREFIX}{key}\n"
|
||||
|
||||
@app.route('/shorten', methods=['POST'])
|
||||
def shorten_url():
|
||||
url = request.form.get('url')
|
||||
if not url:
|
||||
return "No URL provided\n", 400
|
||||
|
||||
key = uuid.uuid4().hex[:6]
|
||||
data[key] = {
|
||||
'type': 'url',
|
||||
'url': url,
|
||||
'expiry': time.time() + EXPIRATION_TIME
|
||||
}
|
||||
save_data()
|
||||
return f"{URL_PREFIX}{key}\n"
|
||||
|
||||
@app.route('/<key>', methods=['GET'])
|
||||
def get_content(key):
|
||||
item = data.get(key)
|
||||
if not item:
|
||||
abort(404)
|
||||
|
||||
if item['type'] == 'file':
|
||||
return send_from_directory(UPLOAD_FOLDER, os.path.basename(item['path']))
|
||||
elif item['type'] == 'url':
|
||||
return redirect(item['url'])
|
||||
else:
|
||||
abort(404)
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host='0.0.0.0', port=5000)
|
Loading…
Reference in New Issue
Block a user