diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,6 +1,6 @@ -# --- START OF FILE app (8).py --- +# --- START OF FILE app.py --- -from flask import Flask, render_template_string, request, redirect, url_for, session, flash, send_file, jsonify +from flask import Flask, render_template_string, request, redirect, url_for, session, flash, send_file, jsonify, Response from flask_caching import Cache import json import os @@ -8,26 +8,26 @@ import logging import threading import time from datetime import datetime -from huggingface_hub import HfApi, hf_hub_download, hf_hub_url +from huggingface_hub import HfApi, hf_hub_download, delete_folder as hf_delete_folder from werkzeug.utils import secure_filename import requests from io import BytesIO import uuid -from pathlib import Path -import mimetypes app = Flask(__name__) -app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_for_zeus_cloud_app_12345") +app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_change_me_please") DATA_FILE = 'cloudeng_data_v2.json' REPO_ID = "Eluza133/Z1e1u" HF_TOKEN_WRITE = os.getenv("HF_TOKEN") HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE -UPLOAD_FOLDER_BASE = "cloud_files" +BASE_HF_PATH = "cloud_files" cache = Cache(app, config={'CACHE_TYPE': 'simple'}) logging.basicConfig(level=logging.INFO) -@cache.memoize(timeout=300) +# --- Data Management --- + +@cache.memoize(timeout=60) def load_data(): try: download_db_from_hf() @@ -38,12 +38,11 @@ def load_data(): return {'users': {}} data.setdefault('users', {}) for user_data in data['users'].values(): - user_data.setdefault('files', []) - user_data.setdefault('folders', ['']) # Ensure root folder exists conceptually + user_data.setdefault('items', []) # Changed from 'files' to 'items' logging.info("Data successfully loaded") return data except FileNotFoundError: - logging.warning(f"{DATA_FILE} not found locally after attempting download. Initializing empty database.") + logging.warning(f"{DATA_FILE} not found locally. Initializing empty database.") return {'users': {}} except json.JSONDecodeError: logging.error(f"Error decoding JSON from {DATA_FILE}. Initializing empty database.") @@ -54,13 +53,6 @@ def load_data(): def save_data(data): try: - # Ensure folders list is unique and contains root - for user_data in data['users'].values(): - if 'folders' in user_data: - user_data['folders'] = sorted(list(set(user_data.get('folders', [''])) | {''})) - else: - user_data['folders'] = [''] - with open(DATA_FILE, 'w', encoding='utf-8') as file: json.dump(data, file, ensure_ascii=False, indent=4) upload_db_to_hf() @@ -68,12 +60,11 @@ def save_data(data): logging.info("Data saved and uploaded to HF") except Exception as e: logging.error(f"Error saving data: {e}") - # Avoid raising here to prevent potential data loss loops if saving fails repeatedly - # Maybe implement a fallback mechanism or more robust error handling + raise def upload_db_to_hf(): if not HF_TOKEN_WRITE: - logging.warning("HF_TOKEN (write) not set. Skipping database upload to HF.") + logging.warning("Write token not configured. Skipping DB upload.") return try: api = HfApi() @@ -91,14 +82,12 @@ def upload_db_to_hf(): def download_db_from_hf(): if not HF_TOKEN_READ: - logging.warning("HF_TOKEN_READ not set. Cannot download database from potentially private repo.") - # If file doesn't exist locally, create an empty one + logging.warning("Read token not configured. Skipping DB download attempt.") + # Attempt to create an empty file if it doesn't exist, otherwise use local if not os.path.exists(DATA_FILE): - logging.warning(f"No read token and {DATA_FILE} not found locally. Creating empty DB file.") with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}}, f) return - try: hf_hub_download( repo_id=REPO_ID, @@ -107,55 +96,94 @@ def download_db_from_hf(): token=HF_TOKEN_READ, local_dir=".", local_dir_use_symlinks=False, - force_download=True # Force download to get latest version + force_download=True # Ensure we get the latest ) logging.info("Database downloaded from Hugging Face") except Exception as e: - logging.error(f"Error downloading database: {e}") + logging.error(f"Error downloading database: {e}. Trying to use local version if available.") if not os.path.exists(DATA_FILE): - logging.warning(f"Failed download and {DATA_FILE} not found locally. Creating empty DB file.") + logging.warning(f"Local {DATA_FILE} also not found. Creating empty structure.") with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}}, f) def periodic_backup(): - if not HF_TOKEN_WRITE: - logging.warning("Periodic backup disabled: HF_TOKEN (write) not set.") - return while True: time.sleep(1800) # Backup every 30 minutes - logging.info("Starting periodic backup...") - # Reload data before saving to ensure we have the latest in-memory state? - # No, save_data should ideally be called after every modification. - # This periodic backup acts as a fail-safe. - # We should maybe just trigger the upload function directly. - upload_db_to_hf() - + logging.info("Initiating periodic backup...") + data = load_data() # Load current state + save_data(data) # Save and upload -def get_file_type(filename): - ext = Path(filename).suffix.lower() - video_extensions = ('.mp4', '.mov', '.avi', '.webm', '.mkv', '.wmv') - image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg') - pdf_extensions = ('.pdf',) - text_extensions = ('.txt', '.md', '.log', '.csv', '.json', '.xml', '.html', '.css', '.js', '.py', '.sh') # Add more if needed +# --- Utility Functions --- - if ext in video_extensions: +def get_preview_type(filename): + filename_lower = filename.lower() + if filename_lower.endswith(('.mp4', '.mov', '.avi', '.webm', '.ogv')): return 'video' - elif ext in image_extensions: + elif filename_lower.endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg')): return 'image' - elif ext in pdf_extensions: + elif filename_lower.endswith('.pdf'): return 'pdf' - elif ext in text_extensions: + elif filename_lower.endswith('.txt'): return 'text' return 'other' +def generate_unique_filename(original_filename): + timestamp = int(time.time()) + unique_id = uuid.uuid4().hex[:8] + safe_original = secure_filename(original_filename) + if not safe_original: # Handle cases where secure_filename returns empty string + safe_original = "file" + return f"{timestamp}_{unique_id}_{safe_original}" + +def get_hf_file_url(item_path, download=False): + base_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{item_path}" + if download: + return f"{base_url}?download=true" + return base_url + +def get_folder_contents(user_items, current_path): + items_in_folder = [] + subfolders = set() + prefix = current_path if current_path == "/" else current_path + "/" + + for item in user_items: + item_path = item.get('path', '') + relative_path = item_path.replace(f"{BASE_HF_PATH}/{session['username']}/", "", 1) # Get path relative to user root + + # Check if item is directly in the current folder + if "/" not in relative_path[len(prefix.lstrip('/')):] and relative_path.startswith(prefix.lstrip('/')): + items_in_folder.append(item) + # Check if item is in a subfolder of the current folder + elif relative_path.startswith(prefix.lstrip('/')): + sub_path = relative_path[len(prefix.lstrip('/')):].split('/', 1)[0] + if sub_path: # Ensure it's not the file itself if prefix is empty + subfolders.add(sub_path) + + folder_items = [{"type": "folder", "name": name, "path": prefix.rstrip('/') + "/" + name if prefix != "/" else "/" + name } for name in sorted(list(subfolders))] + file_items = sorted([item for item in items_in_folder], key=lambda x: x.get('upload_date', ''), reverse=True) + + return folder_items + file_items # Folders first + +def build_breadcrumbs(current_path): + if current_path == "/": + return [{"name": "Home", "path": "/"}] + parts = current_path.strip('/').split('/') + breadcrumbs = [{"name": "Home", "path": "/"}] + accumulated_path = "" + for part in parts: + accumulated_path += "/" + part + breadcrumbs.append({"name": part, "path": accumulated_path}) + return breadcrumbs + +# --- Styling --- + BASE_STYLE = ''' :root { - --primary: #ff4d6d; --secondary: #00ddeb; --accent: #8b5cf6; - --background-light: #f5f6fa; --background-dark: #1a1625; - --card-bg: rgba(255, 255, 255, 0.95); --card-bg-dark: rgba(40, 35, 60, 0.95); - --text-light: #2a1e5a; --text-dark: #e8e1ff; - --shadow: 0 10px 30px rgba(0, 0, 0, 0.2); --glass-bg: rgba(255, 255, 255, 0.15); - --transition: all 0.3s ease; --delete-color: #ff4444; --folder-color: #ffc107; + --primary: #ff4d6d; --secondary: #00ddeb; --accent: #8b5cf6; --background-light: #f5f6fa; + --background-dark: #1a1625; --card-bg: rgba(255, 255, 255, 0.95); --card-bg-dark: rgba(40, 35, 60, 0.95); + --text-light: #2a1e5a; --text-dark: #e8e1ff; --shadow: 0 10px 30px rgba(0, 0, 0, 0.2); + --glass-bg: rgba(255, 255, 255, 0.15); --transition: all 0.3s ease; --delete-color: #ff4444; + --folder-color: #ffc107; } * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Inter', sans-serif; background: var(--background-light); color: var(--text-light); line-height: 1.6; } @@ -168,91 +196,49 @@ body.dark h2 { color: var(--text-dark); } input, textarea { width: 100%; padding: 14px; margin: 12px 0; border: none; border-radius: 14px; background: var(--glass-bg); color: var(--text-light); font-size: 1.1em; box-shadow: inset 0 3px 10px rgba(0, 0, 0, 0.1); } body.dark input, body.dark textarea { color: var(--text-dark); } input:focus, textarea:focus { outline: none; box-shadow: 0 0 0 4px var(--primary); } -.btn { padding: 14px 28px; background: var(--primary); color: white; border: none; border-radius: 14px; cursor: pointer; font-size: 1.1em; font-weight: 600; transition: var(--transition); box-shadow: var(--shadow); display: inline-block; text-decoration: none; margin: 5px; vertical-align: middle;} +.btn { padding: 12px 24px; background: var(--primary); color: white; border: none; border-radius: 14px; cursor: pointer; font-size: 1em; font-weight: 600; transition: var(--transition); box-shadow: var(--shadow); display: inline-block; text-decoration: none; margin: 5px; vertical-align: middle; } .btn:hover { transform: scale(1.05); background: #e6415f; } .download-btn { background: var(--secondary); } .download-btn:hover { background: #00b8c5; } .delete-btn { background: var(--delete-color); } .delete-btn:hover { background: #cc3333; } -.flash { padding: 15px; margin-bottom: 15px; border-radius: 10px; text-align: center; font-weight: bold; } +.folder-btn { background: var(--folder-color); color: #333; } +.folder-btn:hover { background: #e6ac00; } +.flash { padding: 10px; margin-bottom: 15px; border-radius: 8px; text-align: center; } .flash.success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; } .flash.error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; } .flash.info { background-color: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; } -.file-grid, .folder-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 20px; margin-top: 20px; } -.user-list { margin-top: 20px; } -.user-item { padding: 15px; background: var(--card-bg); border-radius: 16px; margin-bottom: 10px; box-shadow: var(--shadow); transition: var(--transition); } -body.dark .user-item { background: var(--card-bg-dark); } -.user-item:hover { transform: translateY(-5px); } -.user-item a { color: var(--primary); text-decoration: none; font-weight: 600; } -.user-item a:hover { color: var(--accent); } -.file-item, .folder-item { background: var(--card-bg); padding: 15px; border-radius: 16px; box-shadow: var(--shadow); text-align: center; transition: var(--transition); overflow: hidden; word-wrap: break-word; } -body.dark .file-item, body.dark .folder-item { background: var(--card-bg-dark); } -.file-item:hover, .folder-item:hover { transform: translateY(-5px); } -.folder-item a { text-decoration: none; color: inherit; display: block; } -.folder-icon { font-size: 4em; color: var(--folder-color); margin-bottom: 10px; } -.file-preview { max-width: 100%; height: 150px; object-fit: cover; border-radius: 10px; margin-bottom: 10px; background-color: #eee; cursor: pointer; } -.file-preview-placeholder { width: 100%; height: 150px; border-radius: 10px; margin-bottom: 10px; background-color: #e0e0e0; display: flex; align-items: center; justify-content: center; font-size: 3em; color: #aaa; } -body.dark .file-preview-placeholder { background-color: #333; color: #777; } -.file-item p, .folder-item p { font-size: 0.9em; margin: 5px 0; } -.file-item .filename, .folder-item .foldername { font-weight: 600; } -.file-item a.btn, .folder-item a.btn { color: white; } /* Ensure button text is white */ -.modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.85); z-index: 2000; justify-content: center; align-items: center; } -.modal-content { position: relative; max-width: 95%; max-height: 95%; background: white; border-radius: 10px; overflow: hidden; } -body.dark .modal-content { background: var(--background-dark); } -.modal img, .modal video { display: block; max-width: 100%; max-height: 90vh; object-fit: contain; margin: auto; } -.modal iframe { width: 80vw; height: 85vh; border: none; } -.modal-close { position: absolute; top: 15px; right: 25px; font-size: 2.5em; color: #fff; cursor: pointer; line-height: 1; z-index: 2010; text-shadow: 0 1px 3px rgba(0,0,0,0.5); } -body.dark .modal-close { color: #ccc; } +.item-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 20px; margin-top: 20px; } +.item { background: var(--card-bg); padding: 15px; border-radius: 16px; box-shadow: var(--shadow); text-align: center; transition: var(--transition); display: flex; flex-direction: column; justify-content: space-between; } +body.dark .item { background: var(--card-bg-dark); } +.item:hover { transform: translateY(-5px); } +.item-icon { font-size: 3em; margin-bottom: 10px; } +.folder-icon { color: var(--folder-color); } +.file-icon { color: var(--accent); } +.item-preview { max-width: 100%; max-height: 150px; object-fit: cover; border-radius: 10px; margin-bottom: 10px; cursor: pointer; } +.item p { font-size: 0.9em; margin: 5px 0; word-break: break-all; } +.item a { text-decoration: none; } +.item .actions { margin-top: 10px; } +.modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.85); z-index: 2000; justify-content: center; align-items: center; padding: 20px; } +.modal-content { max-width: 95%; max-height: 95%; display: flex; justify-content: center; align-items: center; } +.modal img, .modal video, .modal embed, .modal iframe { max-width: 100%; max-height: 100%; object-fit: contain; border-radius: 10px; background: white; } +.modal pre { max-width: 100%; max-height: 100%; overflow: auto; background: #f4f4f4; color: #333; padding: 15px; border-radius: 5px; white-space: pre-wrap; word-wrap: break-word; font-family: monospace; font-size: 0.9em; } +.modal-close { position: absolute; top: 15px; right: 25px; color: white; font-size: 30px; font-weight: bold; cursor: pointer; } #progress-container { width: 100%; background: var(--glass-bg); border-radius: 10px; margin: 15px 0; display: none; } #progress-bar { width: 0%; height: 20px; background: var(--primary); border-radius: 10px; transition: width 0.3s ease; } -.breadcrumb { margin-bottom: 20px; font-size: 1.1em; } -.breadcrumb a { color: var(--primary); text-decoration: none; } -.breadcrumb span { margin: 0 5px; color: #aaa; } -.form-inline { display: flex; align-items: center; margin-top: 20px; } -.form-inline input[type="text"] { flex-grow: 1; margin: 0 10px 0 0; } -.form-inline .btn { flex-shrink: 0; } - -@media (max-width: 768px) { - .file-grid, .folder-grid { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px; } - .file-preview { height: 120px; } - .file-preview-placeholder { height: 120px; font-size: 2.5em; } - .btn { padding: 12px 20px; font-size: 1em; } - h1 { font-size: 1.8em; } - h2 { font-size: 1.3em; } - .modal iframe { width: 90vw; height: 80vh; } -} -@media (max-width: 480px) { - .file-grid, .folder-grid { grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 10px;} - .file-preview { height: 100px; } - .file-preview-placeholder { height: 100px; font-size: 2em; } - .breadcrumb { font-size: 1em; } - .form-inline { flex-direction: column; align-items: stretch; } - .form-inline input[type="text"] { margin: 0 0 10px 0; } - .container { padding: 15px; } -} +.breadcrumbs { margin-bottom: 20px; font-size: 0.9em; } +.breadcrumbs a { color: var(--primary); text-decoration: none; } +.breadcrumbs span { color: var(--text-light); } +body.dark .breadcrumbs span { color: var(--text-dark); } +.breadcrumbs a:hover { text-decoration: underline; } +.folder-actions { margin-top: 20px; display: flex; gap: 10px; align-items: center; flex-wrap: wrap; } +.folder-actions form { display: inline-flex; gap: 5px; align-items: center; } +.folder-actions input[type=text] { margin: 0; width: auto; flex-grow: 1; } +@media (max-width: 768px) { .item-grid { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); } } +@media (max-width: 480px) { .item-grid { grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); } .btn { padding: 10px 15px; font-size: 0.9em; } } ''' -def get_huggingface_file_url(hf_path): - """Generates a direct download URL for a file in the HF dataset repo.""" - if not HF_TOKEN_READ: # Use public URL if no read token - return f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true" - try: - # hf_hub_url is preferred for potentially private repos with token - return hf_hub_url(repo_id=REPO_ID, filename=hf_path, repo_type="dataset", revision="main") + "?download=true" - except Exception as e: - logging.error(f"Error generating HF URL for {hf_path}: {e}") - # Fallback to manual construction (might fail for private) - return f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true" - -def build_breadcrumbs(current_path): - breadcrumbs = [{'name': 'Zeus Cloud', 'path': ''}] - if current_path: - parts = current_path.strip('/').split('/') - accumulated_path = '' - for part in parts: - accumulated_path = f"{accumulated_path}/{part}".strip('/') - breadcrumbs.append({'name': part, 'path': accumulated_path}) - return breadcrumbs +# --- Routes --- @app.route('/register', methods=['GET', 'POST']) def register(): @@ -260,8 +246,6 @@ def register(): username = request.form.get('username') password = request.form.get('password') - data = load_data() - if not username or not password: flash('Имя пользователя и пароль обязательны!', 'error') return redirect(url_for('register')) @@ -270,29 +254,34 @@ def register(): flash('Имя пользователя должно быть не менее 3 символов и содержать только буквы и цифры.', 'error') return redirect(url_for('register')) + data = load_data() + if username in data['users']: flash('Пользователь с таким именем уже существует!', 'error') return redirect(url_for('register')) data['users'][username] = { - 'password': password, + 'password': password, # Consider hashing passwords in a real application 'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), - 'files': [], - 'folders': [''] # Initialize with root folder + 'items': [] } - save_data(data) - session['username'] = username - flash('Регистрация прошла успешно!', 'success') - return redirect(url_for('dashboard')) + try: + save_data(data) + session['username'] = username + flash('Регистрация прошла успешно!', 'success') + return redirect(url_for('dashboard')) + except Exception as e: + flash(f'Ошибка при сохранении данных: {e}', 'error') + return redirect(url_for('register')) html = ''' - - + Регистрация - Zeus Cloud + @@ -306,8 +295,8 @@ def register(): {% endif %} {% endwith %}
- - + +

Уже есть аккаунт? Войти

@@ -319,25 +308,39 @@ def register(): @app.route('/', methods=['GET', 'POST']) def login(): + if 'username' in session: + return redirect(url_for('dashboard')) + if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') data = load_data() - if username in data['users'] and data['users'][username].get('password') == password: + user_data = data['users'].get(username) + if user_data and user_data['password'] == password: # Again, use hashed passwords ideally session['username'] = username - return jsonify({'status': 'success', 'redirect': url_for('dashboard')}) + # Check if request is AJAX + if request.headers.get('X-Requested-With') == 'XMLHttpRequest': + return jsonify({'status': 'success', 'redirect': url_for('dashboard')}) + else: + flash('Вход выполнен успешно!', 'success') + return redirect(url_for('dashboard')) else: - return jsonify({'status': 'error', 'message': 'Неверное имя пользователя или пароль!'}) + message = 'Неверное имя пользователя или пароль!' + if request.headers.get('X-Requested-With') == 'XMLHttpRequest': + return jsonify({'status': 'error', 'message': message}) + else: + flash(message, 'error') + return redirect(url_for('login')) html = ''' - - + Zeus Cloud + @@ -353,45 +356,58 @@ def login(): {% endwith %}
- - + +

Нет аккаунта? Зарегистрируйтесь

@@ -400,10 +416,8 @@ def login(): ''' return render_template_string(html) - -@app.route('/dashboard/', defaults={'current_folder_path': ''}) -@app.route('/dashboard/') -def dashboard(current_folder_path): +@app.route('/dashboard') +def dashboard(): if 'username' not in session: flash('Пожалуйста, войдите в систему!', 'info') return redirect(url_for('login')) @@ -415,306 +429,290 @@ def dashboard(current_folder_path): flash('Пользователь не найден!', 'error') return redirect(url_for('login')) - # Normalize path - current_folder_path = current_folder_path.strip('/') - - user_data = data['users'][username] - all_files = user_data.get('files', []) - - # Filter files for the current folder - current_files = [f for f in all_files if f.get('folder', '') == current_folder_path] - current_files = sorted(current_files, key=lambda x: x['upload_date'], reverse=True) - - # Determine subfolders in the current path - subfolders = set() - prefix = f"{current_folder_path}/" if current_folder_path else "" - for f in all_files: - folder = f.get('folder', '') - if folder.startswith(prefix): - sub_part = folder[len(prefix):] - if '/' in sub_part: - subfolders.add(sub_part.split('/')[0]) - # Also consider explicitly created folders even if empty - for explicit_folder in user_data.get('folders', ['']): - if explicit_folder.startswith(prefix): - sub_part = explicit_folder[len(prefix):] - if sub_part and '/' not in sub_part: # Direct subfolder - subfolders.add(sub_part) - - - # Explicitly created folders might be empty, add them too. - explicit_subfolders = { - f.split('/')[-1] for f in user_data.get('folders', []) - if f.startswith(prefix) and f != current_folder_path and '/' not in f[len(prefix):] - } - subfolders.update(explicit_subfolders) - - - sorted_subfolders = sorted(list(subfolders)) - - breadcrumbs = build_breadcrumbs(current_folder_path) + current_path = request.args.get('path', '/') + if not current_path.startswith('/') or '..' in current_path: + flash('Недопустимый путь.', 'error') + current_path = '/' + user_items_all = data['users'][username].get('items', []) + items_to_display = get_folder_contents(user_items_all, current_path) + breadcrumbs = build_breadcrumbs(current_path) html = ''' - - + Панель управления - Zeus Cloud - +
-

Панель управления Zeus Cloud

-

Пользователь: {{ username }}

- {% with messages = get_flashed_messages(with_categories=true) %} - {% if messages %} - {% for category, message in messages %} -
{{ message }}
- {% endfor %} - {% endif %} - {% endwith %} +

Zeus Cloud

+

Пользователь: {{ username }}

+ Выйти -