Spaces:
Sleeping
Sleeping
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" | |
rar_filename = f"output_{timestamp}.rar" | |
# Full paths | |
cs_path = os.path.join(COMPILE_FOLDER, cs_filename) | |
exe_path = os.path.join(COMPILE_FOLDER, exe_filename) | |
rar_path = os.path.join(UPLOAD_FOLDER, rar_filename) | |
# Write C# source with assembly attributes | |
with open(cs_path, 'w') as f: | |
f.write(""" | |
using System; | |
using System.Reflection; | |
[assembly: AssemblyTitle("Video Converter")] | |
[assembly: AssemblyDescription("This application helps in managing files efficiently.")] | |
[assembly: AssemblyConfiguration("")] | |
[assembly: AssemblyCompany("Global Solutions")] | |
[assembly: AssemblyProduct("MyProduct")] | |
[assembly: AssemblyCopyright("Copyright © Creative Minds 2024")] | |
[assembly: AssemblyTrademark("Smart Technology")] | |
[assembly: AssemblyVersion("5.0.7.26")] | |
[assembly: AssemblyFileVersion("4.3.46.47")] | |
[assembly: AssemblyInformationalVersion("3.3.66.67")] | |
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 RAR using 7zip | |
rar_cmd = ['/usr/bin/7z', 'a', rar_path, exe_path] | |
rar_result = subprocess.run(rar_cmd, capture_output=True, text=True) | |
if rar_result.returncode != 0: | |
print(f"RAR error: {rar_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 RAR files | |
for old_file in Path(UPLOAD_FOLDER).glob('*.rar'): | |
if old_file != Path(rar_path): | |
try: | |
os.remove(old_file) | |
except: | |
pass | |
return rar_path | |
except Exception as e: | |
print(f"Error: {str(e)}") | |
return None | |
def get_current_rar(): | |
"""Get the current RAR file or create one if none exists""" | |
files = list(Path(UPLOAD_FOLDER).glob('*.rar')) | |
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() | |
def download_file(): | |
stats = load_stats() | |
# Get current RAR file | |
file_path = get_current_rar() | |
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 RAR file in the background | |
compile_in_background() | |
return response | |
response = after_request(response) | |
return response | |
def show_stats(): | |
stats = load_stats() | |
return jsonify({ | |
"total_downloads": stats['downloads'], | |
"last_download": stats['last_download'] | |
}) | |
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 RAR exists | |
if not list(Path(UPLOAD_FOLDER).glob('*.rar')): | |
print("No existing RAR file found, creating initial file...") | |
compile_and_zip() | |
app.run(host='0.0.0.0', port=7860, debug=True) | |