import os import requests import shutil from urllib.parse import urlparse from flask import Flask, request, jsonify, send_from_directory app = Flask(__name__) # Create directories to simulate a file system if not os.path.exists('images'): os.makedirs('images') if not os.path.exists('files'): os.makedirs('files') # For simulating a terminal environment (virtual file system) current_directory = 'files' @app.route('/') def index(): return send_from_directory('static', 'index.html') @app.route('/download_image') def download_image(): url = request.args.get('url') if not url: return jsonify({'success': False, 'message': 'No URL provided.'}) try: response = requests.get(url) if response.status_code == 200: image_name = os.path.basename(urlparse(url).path) image_path = os.path.join('images', image_name) with open(image_path, 'wb') as file: file.write(response.content) file_size = os.path.getsize(image_path) file_size = f'{file_size / (1024 * 1024):.2f} MB' # Convert to MB return jsonify({ 'success': True, 'image_url': f'/images/{image_name}', 'file_size': file_size, 'message': f'Image downloaded: {image_name}' }) else: return jsonify({'success': False, 'message': 'Failed to fetch image.'}) except Exception as e: return jsonify({'success': False, 'message': str(e)}) @app.route('/images/') def serve_image(filename): return send_from_directory('images', filename) @app.route('/terminal', methods=['POST']) def terminal(): command = request.json.get('command') global current_directory output = "" if command.startswith("ls"): output = "\n".join(os.listdir(current_directory)) or "No files or directories." elif command.startswith("cat"): filename = command.split(" ")[1] try: with open(os.path.join(current_directory, filename), 'r') as f: output = f.read() except FileNotFoundError: output = f"Error: {filename} not found." elif command.startswith("mkdir"): folder_name = command.split(" ")[1] os.makedirs(os.path.join(current_directory, folder_name), exist_ok=True) output = f"Directory {folder_name} created." elif command.startswith("touch"): filename = command.split(" ")[1] with open(os.path.join(current_directory, filename), 'w') as f: pass output = f"File {filename} created." elif command.startswith("rm"): filename = command.split(" ")[1] try: os.remove(os.path.join(current_directory, filename)) output = f"File {filename} removed." except FileNotFoundError: output = f"Error: {filename} not found." elif command.startswith("cd"): folder_name = command.split(" ")[1] new_directory = os.path.join(current_directory, folder_name) if os.path.isdir(new_directory): current_directory = new_directory output = f"Changed directory to {folder_name}" else: output = f"Error: {folder_name} not found." elif command == "pwd": output = f"Current directory: {current_directory}" else: output = "Unknown command. Type 'help' for a list of available commands." return jsonify({'output': output}) if __name__ == '__main__': app.run(debug=True)