sigyllly's picture
Update main.py
a324286 verified
raw
history blame
4.64 kB
from flask import Flask, send_file, jsonify
import os
import subprocess
import json
from datetime import datetime
from pathlib import Path
from threading import Thread
app = Flask(__name__)
# Configuration
UPLOAD_FOLDER = "uploads"
COMPILE_FOLDER = "compile"
STATS_FILE = "download_stats.json"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(COMPILE_FOLDER, exist_ok=True)
def load_stats():
if os.path.exists(STATS_FILE):
with open(STATS_FILE, 'r') as f:
return json.load(f)
return {"downloads": 0, "last_download": None}
def save_stats(stats):
with open(STATS_FILE, 'w') as f:
json.dump(stats, f)
def compile_and_zip():
try:
# Generate unique names
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
cs_filename = f"script_{timestamp}.cs"
exe_filename = f"script_{timestamp}.exe"
zip_filename = f"output_{timestamp}.zip"
# Full paths
cs_path = os.path.join(COMPILE_FOLDER, cs_filename)
exe_path = os.path.join(COMPILE_FOLDER, exe_filename)
zip_path = os.path.join(UPLOAD_FOLDER, zip_filename)
# Write C# source
with open(cs_path, 'w') as f:
f.write("""
using System;
class Program
{
static void Main()
{
Console.WriteLine("Compiled C# Application");
Console.WriteLine("Generated at: {0}", DateTime.Now.ToString());
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
""")
# Compile with mcs
compile_cmd = [
"mcs",
'-optimize+',
'-out:' + exe_path,
cs_path
]
compile_result = subprocess.run(compile_cmd, capture_output=True, text=True)
if compile_result.returncode != 0:
print(f"Compile error: {compile_result.stderr}")
return None
# Create ZIP
zip_cmd = ['zip', '-j', zip_path, exe_path]
zip_result = subprocess.run(zip_cmd, capture_output=True, text=True)
if zip_result.returncode != 0:
print(f"ZIP error: {zip_result.stderr}")
return None
# Cleanup temporary files
try:
os.remove(cs_path)
os.remove(exe_path)
except Exception as e:
print(f"Cleanup error: {e}")
# Remove old ZIP files
for old_file in Path(UPLOAD_FOLDER).glob('*.zip'):
if old_file != Path(zip_path):
try:
os.remove(old_file)
except:
pass
return zip_path
except Exception as e:
print(f"Error: {str(e)}")
return None
def get_current_zip():
"""Get the current ZIP file or create one if none exists"""
files = list(Path(UPLOAD_FOLDER).glob('*.zip'))
if not files:
return compile_and_zip()
return str(max(files, key=os.path.getctime))
def compile_in_background():
"""Trigger compilation in a separate thread to avoid blocking the main app."""
Thread(target=compile_and_zip).start()
@app.route('/download/cnVuLmNtZA==')
def download_file():
stats = load_stats()
# Get current ZIP file
file_path = get_current_zip()
if not file_path:
return "Compilation failed", 500
if not os.path.exists(file_path):
return "File not found", 404
# Send the file
response = send_file(file_path, as_attachment=True)
def after_request(response):
# Update the download stats after the file has been sent
stats['downloads'] += 1
stats['last_download'] = datetime.now().isoformat()
save_stats(stats)
# Compile the new ZIP file in the background
compile_in_background()
return response
response = after_request(response)
return response
@app.route('/show')
def show_stats():
stats = load_stats()
return jsonify({
"total_downloads": stats['downloads'],
"last_download": stats['last_download']
})
@app.route('/')
def home():
return """
<h1>File Compiler Service</h1>
<ul>
<li><a href="/download/cnVuLmNtZA==">/download/cnVuLmNtZA==</a> - Download compiled file</li>
<li><a href="/show">/show</a> - View download statistics</li>
</ul>
"""
if __name__ == '__main__':
# Only compile if no ZIP exists
if not list(Path(UPLOAD_FOLDER).glob('*.zip')):
print("No existing ZIP file found, creating initial file...")
compile_and_zip()
app.run(host='0.0.0.0', port=7860, debug=True)