Spaces:
Sleeping
Sleeping
File size: 4,639 Bytes
a324286 45a1acf a324286 66f8fc1 45a1acf 0b709b9 a324286 436e9c0 a324286 436e9c0 a324286 0b709b9 a324286 0b709b9 a324286 0b709b9 45a1acf a324286 0b709b9 436e9c0 45a1acf a324286 838901f 436e9c0 |
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 |
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)
|