from flask import Flask, send_from_directory, abort
from flask_cors import CORS
import os

app = Flask(__name__)
CORS(app)

# Thư mục gốc chứa dữ liệu
BASE_DIR = "/app"

@app.route("/files/<path:filename>")
def serve_file(filename):
    # Bảo vệ: không cho truy cập ra ngoài BASE_DIR
    safe_path = os.path.join(BASE_DIR, filename)
    if not os.path.isfile(safe_path):
        return abort(404, description="File not found")
    directory = os.path.dirname(safe_path)
    file = os.path.basename(safe_path)
    return send_from_directory(directory, file)

@app.route("/")
def index():
    file_links = []
    for root, _, files in os.walk(BASE_DIR):
        for f in files:
            rel_path = os.path.relpath(os.path.join(root, f), BASE_DIR)
            url_path = f"/files/{rel_path}"
            file_links.append(f"<a href='{url_path}'>{rel_path}</a>")
    file_links.sort()
    return "<h2>Available Files</h2>" + "<br>".join(file_links)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080, debug=True)
