Update app.py
Browse files
app.py
CHANGED
|
@@ -1,28 +1,32 @@
|
|
| 1 |
-
|
| 2 |
-
from flask import Flask, render_template_string, request, redirect, url_for, session, flash, send_file, jsonify
|
| 3 |
-
from flask_caching import Cache
|
| 4 |
import json
|
| 5 |
-
import os
|
| 6 |
import logging
|
|
|
|
| 7 |
import threading
|
| 8 |
import time
|
|
|
|
| 9 |
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
from huggingface_hub import HfApi, hf_hub_download
|
| 11 |
from werkzeug.utils import secure_filename
|
| 12 |
-
import requests
|
| 13 |
-
from io import BytesIO
|
| 14 |
|
| 15 |
app = Flask(__name__)
|
| 16 |
-
app.secret_key = os.getenv("FLASK_SECRET_KEY", "
|
| 17 |
DATA_FILE = 'cloudeng_data.json'
|
| 18 |
-
REPO_ID = "Eluza133/Z1e1u"
|
| 19 |
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
|
| 20 |
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE
|
| 21 |
|
| 22 |
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
|
| 23 |
logging.basicConfig(level=logging.INFO)
|
| 24 |
|
| 25 |
-
|
|
|
|
|
|
|
| 26 |
def load_data():
|
| 27 |
try:
|
| 28 |
download_db_from_hf()
|
|
@@ -30,17 +34,33 @@ def load_data():
|
|
| 30 |
data = json.load(file)
|
| 31 |
if not isinstance(data, dict):
|
| 32 |
logging.warning("Data is not in dict format, initializing empty database")
|
| 33 |
-
return {'users': {}, 'files': {}}
|
| 34 |
data.setdefault('users', {})
|
| 35 |
-
|
|
|
|
|
|
|
| 36 |
logging.info("Data successfully loaded")
|
| 37 |
return data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
except Exception as e:
|
| 39 |
logging.error(f"Error loading data: {e}")
|
| 40 |
-
return {'users': {}
|
| 41 |
|
| 42 |
def save_data(data):
|
| 43 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
with open(DATA_FILE, 'w', encoding='utf-8') as file:
|
| 45 |
json.dump(data, file, ensure_ascii=False, indent=4)
|
| 46 |
upload_db_to_hf()
|
|
@@ -48,9 +68,14 @@ def save_data(data):
|
|
| 48 |
logging.info("Data saved and uploaded to HF")
|
| 49 |
except Exception as e:
|
| 50 |
logging.error(f"Error saving data: {e}")
|
|
|
|
|
|
|
| 51 |
raise
|
| 52 |
|
| 53 |
def upload_db_to_hf():
|
|
|
|
|
|
|
|
|
|
| 54 |
try:
|
| 55 |
api = HfApi()
|
| 56 |
api.upload_file(
|
|
@@ -66,6 +91,13 @@ def upload_db_to_hf():
|
|
| 66 |
logging.error(f"Error uploading database: {e}")
|
| 67 |
|
| 68 |
def download_db_from_hf():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
try:
|
| 70 |
hf_hub_download(
|
| 71 |
repo_id=REPO_ID,
|
|
@@ -73,280 +105,154 @@ def download_db_from_hf():
|
|
| 73 |
repo_type="dataset",
|
| 74 |
token=HF_TOKEN_READ,
|
| 75 |
local_dir=".",
|
| 76 |
-
local_dir_use_symlinks=False
|
|
|
|
| 77 |
)
|
| 78 |
logging.info("Database downloaded from Hugging Face")
|
| 79 |
except Exception as e:
|
| 80 |
-
|
|
|
|
| 81 |
if not os.path.exists(DATA_FILE):
|
|
|
|
| 82 |
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 83 |
-
json.dump({'users': {}
|
| 84 |
|
| 85 |
def periodic_backup():
|
| 86 |
while True:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
upload_db_to_hf()
|
| 88 |
-
|
| 89 |
|
| 90 |
def get_file_type(filename):
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
if filename.lower().endswith(video_extensions):
|
| 94 |
return 'video'
|
| 95 |
-
elif
|
| 96 |
return 'image'
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
return 'other'
|
| 98 |
|
|
|
|
| 99 |
BASE_STYLE = '''
|
| 100 |
:root {
|
| 101 |
-
--primary: #ff4d6d;
|
| 102 |
-
--
|
| 103 |
-
--
|
| 104 |
-
--
|
| 105 |
-
--
|
| 106 |
-
--
|
| 107 |
-
--card-bg-dark: rgba(40, 35, 60, 0.95);
|
| 108 |
-
--text-light: #2a1e5a;
|
| 109 |
-
--text-dark: #e8e1ff;
|
| 110 |
-
--shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
|
| 111 |
-
--glass-bg: rgba(255, 255, 255, 0.15);
|
| 112 |
-
--transition: all 0.3s ease;
|
| 113 |
-
--delete-color: #ff4444;
|
| 114 |
}
|
| 115 |
* { margin: 0; padding: 0; box-sizing: border-box; }
|
| 116 |
-
body {
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
}
|
| 122 |
-
body.dark {
|
| 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 |
-
|
| 164 |
-
}
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
}
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
}
|
| 172 |
-
|
| 173 |
-
padding: 14px 28px;
|
| 174 |
-
background: var(--primary);
|
| 175 |
-
color: white;
|
| 176 |
-
border: none;
|
| 177 |
-
border-radius: 14px;
|
| 178 |
-
cursor: pointer;
|
| 179 |
-
font-size: 1.1em;
|
| 180 |
-
font-weight: 600;
|
| 181 |
-
transition: var(--transition);
|
| 182 |
-
box-shadow: var(--shadow);
|
| 183 |
-
display: inline-block;
|
| 184 |
-
text-decoration: none;
|
| 185 |
-
}
|
| 186 |
-
.btn:hover {
|
| 187 |
-
transform: scale(1.05);
|
| 188 |
-
background: #e6415f;
|
| 189 |
-
}
|
| 190 |
-
.download-btn {
|
| 191 |
-
background: var(--secondary);
|
| 192 |
-
margin-top: 10px;
|
| 193 |
-
}
|
| 194 |
-
.download-btn:hover {
|
| 195 |
-
background: #00b8c5;
|
| 196 |
-
}
|
| 197 |
-
.delete-btn {
|
| 198 |
-
background: var(--delete-color);
|
| 199 |
-
margin-top: 10px;
|
| 200 |
-
}
|
| 201 |
-
.delete-btn:hover {
|
| 202 |
-
background: #cc3333;
|
| 203 |
-
}
|
| 204 |
-
.flash {
|
| 205 |
-
color: var(--secondary);
|
| 206 |
-
text-align: center;
|
| 207 |
-
margin-bottom: 15px;
|
| 208 |
-
}
|
| 209 |
-
.file-grid {
|
| 210 |
-
display: grid;
|
| 211 |
-
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
| 212 |
-
gap: 20px;
|
| 213 |
-
margin-top: 20px;
|
| 214 |
-
}
|
| 215 |
-
.user-list {
|
| 216 |
-
margin-top: 20px;
|
| 217 |
-
}
|
| 218 |
-
.user-item {
|
| 219 |
-
padding: 15px;
|
| 220 |
-
background: var(--card-bg);
|
| 221 |
-
border-radius: 16px;
|
| 222 |
-
margin-bottom: 10px;
|
| 223 |
-
box-shadow: var(--shadow);
|
| 224 |
-
transition: var(--transition);
|
| 225 |
-
}
|
| 226 |
-
body.dark .user-item {
|
| 227 |
-
background: var(--card-bg-dark);
|
| 228 |
-
}
|
| 229 |
-
.user-item:hover {
|
| 230 |
-
transform: translateY(-5px);
|
| 231 |
-
}
|
| 232 |
-
.user-item a {
|
| 233 |
-
color: var(--primary);
|
| 234 |
-
text-decoration: none;
|
| 235 |
-
font-weight: 600;
|
| 236 |
-
}
|
| 237 |
-
.user-item a:hover {
|
| 238 |
-
color: var(--accent);
|
| 239 |
-
}
|
| 240 |
-
@media (max-width: 768px) {
|
| 241 |
-
.file-grid {
|
| 242 |
-
grid-template-columns: repeat(2, 1fr);
|
| 243 |
-
}
|
| 244 |
-
}
|
| 245 |
-
@media (max-width: 480px) {
|
| 246 |
-
.file-grid {
|
| 247 |
-
grid-template-columns: 1fr;
|
| 248 |
-
}
|
| 249 |
-
}
|
| 250 |
-
.file-item {
|
| 251 |
-
background: var(--card-bg);
|
| 252 |
-
padding: 15px;
|
| 253 |
-
border-radius: 16px;
|
| 254 |
-
box-shadow: var(--shadow);
|
| 255 |
-
text-align: center;
|
| 256 |
-
transition: var(--transition);
|
| 257 |
-
}
|
| 258 |
-
body.dark .file-item {
|
| 259 |
-
background: var(--card-bg-dark);
|
| 260 |
-
}
|
| 261 |
-
.file-item:hover {
|
| 262 |
-
transform: translateY(-5px);
|
| 263 |
-
}
|
| 264 |
-
.file-preview {
|
| 265 |
-
max-width: 100%;
|
| 266 |
-
max-height: 200px;
|
| 267 |
-
object-fit: cover;
|
| 268 |
-
border-radius: 10px;
|
| 269 |
-
margin-bottom: 10px;
|
| 270 |
-
loading: lazy;
|
| 271 |
-
}
|
| 272 |
-
.file-item p {
|
| 273 |
-
font-size: 0.9em;
|
| 274 |
-
margin: 5px 0;
|
| 275 |
-
}
|
| 276 |
-
.file-item a {
|
| 277 |
-
color: var(--primary);
|
| 278 |
-
text-decoration: none;
|
| 279 |
-
}
|
| 280 |
-
.file-item a:hover {
|
| 281 |
-
color: var(--accent);
|
| 282 |
-
}
|
| 283 |
-
.modal {
|
| 284 |
-
display: none;
|
| 285 |
-
position: fixed;
|
| 286 |
-
top: 0;
|
| 287 |
-
left: 0;
|
| 288 |
-
width: 100%;
|
| 289 |
-
height: 100%;
|
| 290 |
-
background: rgba(0, 0, 0, 0.85);
|
| 291 |
-
z-index: 2000;
|
| 292 |
-
justify-content: center;
|
| 293 |
-
align-items: center;
|
| 294 |
-
}
|
| 295 |
-
.modal img, .modal video {
|
| 296 |
-
max-width: 95%;
|
| 297 |
-
max-height: 95%;
|
| 298 |
-
object-fit: contain;
|
| 299 |
-
border-radius: 20px;
|
| 300 |
-
box-shadow: var(--shadow);
|
| 301 |
-
}
|
| 302 |
-
#progress-container {
|
| 303 |
-
width: 100%;
|
| 304 |
-
background: var(--glass-bg);
|
| 305 |
-
border-radius: 10px;
|
| 306 |
-
margin: 15px 0;
|
| 307 |
-
display: none;
|
| 308 |
-
}
|
| 309 |
-
#progress-bar {
|
| 310 |
-
width: 0%;
|
| 311 |
-
height: 20px;
|
| 312 |
-
background: var(--primary);
|
| 313 |
-
border-radius: 10px;
|
| 314 |
-
transition: width 0.3s ease;
|
| 315 |
-
}
|
| 316 |
'''
|
| 317 |
|
|
|
|
|
|
|
| 318 |
@app.route('/register', methods=['GET', 'POST'])
|
| 319 |
def register():
|
| 320 |
if request.method == 'POST':
|
| 321 |
username = request.form.get('username')
|
| 322 |
password = request.form.get('password')
|
| 323 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
data = load_data()
|
| 325 |
|
| 326 |
if username in data['users']:
|
| 327 |
-
flash('Пользователь с таким именем уже существует!')
|
| 328 |
-
return redirect(url_for('register'))
|
| 329 |
-
|
| 330 |
-
if not username or not password:
|
| 331 |
-
flash('Имя пользователя и пароль обязательны!')
|
| 332 |
return redirect(url_for('register'))
|
| 333 |
|
| 334 |
data['users'][username] = {
|
| 335 |
-
'password': password,
|
| 336 |
'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
| 337 |
'files': []
|
| 338 |
}
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
|
| 344 |
html = '''
|
| 345 |
<!DOCTYPE html>
|
| 346 |
<html lang="ru">
|
| 347 |
<head>
|
| 348 |
-
<meta charset="UTF-8">
|
| 349 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 350 |
<title>Регистрация - Zeus Cloud</title>
|
| 351 |
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 352 |
<style>''' + BASE_STYLE + '''</style>
|
|
@@ -354,23 +260,22 @@ def register():
|
|
| 354 |
<body>
|
| 355 |
<div class="container">
|
| 356 |
<h1>Регистрация в Zeus Cloud</h1>
|
| 357 |
-
{% with messages = get_flashed_messages() %}
|
| 358 |
{% if messages %}
|
| 359 |
-
{% for message in messages %}
|
| 360 |
-
<div class="flash">{{ message }}</div>
|
| 361 |
{% endfor %}
|
| 362 |
{% endif %}
|
| 363 |
{% endwith %}
|
| 364 |
-
<form method="POST"
|
| 365 |
-
<input type="text" name="username" placeholder="
|
| 366 |
-
<input type="password" name="password" placeholder="
|
| 367 |
<button type="submit" class="btn">Зарегистрироваться</button>
|
| 368 |
</form>
|
| 369 |
<p style="margin-top: 20px;">Уже есть аккаунт? <a href="{{ url_for('login') }}">Войти</a></p>
|
| 370 |
</div>
|
| 371 |
</body>
|
| 372 |
-
</html>
|
| 373 |
-
'''
|
| 374 |
return render_template_string(html)
|
| 375 |
|
| 376 |
@app.route('/', methods=['GET', 'POST'])
|
|
@@ -380,297 +285,471 @@ def login():
|
|
| 380 |
password = request.form.get('password')
|
| 381 |
data = load_data()
|
| 382 |
|
| 383 |
-
|
|
|
|
| 384 |
session['username'] = username
|
|
|
|
|
|
|
| 385 |
return jsonify({'status': 'success', 'redirect': url_for('dashboard')})
|
| 386 |
else:
|
| 387 |
return jsonify({'status': 'error', 'message': 'Неверное имя пользователя или пароль!'})
|
| 388 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
html = '''
|
| 390 |
<!DOCTYPE html>
|
| 391 |
<html lang="ru">
|
| 392 |
<head>
|
| 393 |
-
<meta charset="UTF-8">
|
| 394 |
-
<
|
| 395 |
-
<title>Zeus Cloud</title>
|
| 396 |
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 397 |
<style>''' + BASE_STYLE + '''</style>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
</head>
|
| 399 |
<body>
|
| 400 |
<div class="container">
|
| 401 |
<h1>Zeus Cloud</h1>
|
| 402 |
<div id="flash-messages">
|
| 403 |
-
|
| 404 |
{% if messages %}
|
| 405 |
-
{% for message in messages %}
|
| 406 |
-
<div class="flash">{{ message }}</div>
|
| 407 |
{% endfor %}
|
| 408 |
{% endif %}
|
| 409 |
-
|
| 410 |
</div>
|
| 411 |
<form method="POST" id="login-form">
|
| 412 |
-
<input type="text" name="username" placeholder="
|
| 413 |
-
<input type="password" name="password" placeholder="
|
| 414 |
-
|
|
|
|
|
|
|
|
|
|
| 415 |
</form>
|
| 416 |
<p style="margin-top: 20px;">Нет аккаунта? <a href="{{ url_for('register') }}">Зарегистрируйтесь</a></p>
|
| 417 |
</div>
|
| 418 |
<script>
|
| 419 |
-
const savedCredentials = JSON.parse(localStorage.getItem('zeusCredentials'));
|
| 420 |
-
if (savedCredentials) {
|
| 421 |
-
fetch('/', {
|
| 422 |
-
method: 'POST',
|
| 423 |
-
headers: {
|
| 424 |
-
'Content-Type': 'application/x-www-form-urlencoded',
|
| 425 |
-
},
|
| 426 |
-
body: `username=${encodeURIComponent(savedCredentials.username)}&password=${encodeURIComponent(savedCredentials.password)}`
|
| 427 |
-
})
|
| 428 |
-
.then(response => response.json())
|
| 429 |
-
.then(data => {
|
| 430 |
-
if (data.status === 'success') {
|
| 431 |
-
window.location.href = data.redirect;
|
| 432 |
-
}
|
| 433 |
-
})
|
| 434 |
-
.catch(error => console.error('Ошибка автовхода:', error));
|
| 435 |
-
}
|
| 436 |
-
|
| 437 |
document.getElementById('login-form').addEventListener('submit', function(e) {
|
| 438 |
e.preventDefault();
|
| 439 |
const formData = new FormData(this);
|
|
|
|
|
|
|
| 440 |
fetch('/', {
|
| 441 |
method: 'POST',
|
| 442 |
body: formData
|
| 443 |
})
|
| 444 |
.then(response => response.json())
|
| 445 |
.then(data => {
|
|
|
|
|
|
|
| 446 |
if (data.status === 'success') {
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 450 |
window.location.href = data.redirect;
|
| 451 |
} else {
|
| 452 |
-
|
| 453 |
}
|
| 454 |
})
|
| 455 |
.catch(error => {
|
| 456 |
-
|
|
|
|
| 457 |
});
|
| 458 |
});
|
| 459 |
</script>
|
| 460 |
</body>
|
| 461 |
-
</html>
|
| 462 |
-
'''
|
| 463 |
return render_template_string(html)
|
| 464 |
|
|
|
|
| 465 |
@app.route('/dashboard', methods=['GET', 'POST'])
|
| 466 |
def dashboard():
|
| 467 |
if 'username' not in session:
|
| 468 |
-
flash('Пожалуйста, войдите в систему!')
|
| 469 |
return redirect(url_for('login'))
|
| 470 |
|
| 471 |
username = session['username']
|
| 472 |
data = load_data()
|
| 473 |
-
if username not in data
|
| 474 |
session.pop('username', None)
|
| 475 |
-
flash('Пользователь не найден!')
|
| 476 |
return redirect(url_for('login'))
|
| 477 |
|
| 478 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 479 |
|
| 480 |
if request.method == 'POST':
|
|
|
|
|
|
|
|
|
|
|
|
|
| 481 |
files = request.files.getlist('files')
|
| 482 |
-
|
| 483 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 484 |
return redirect(url_for('dashboard'))
|
| 485 |
|
| 486 |
-
if files:
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
temp_files = []
|
| 490 |
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
for temp_path, filename in temp_files:
|
| 499 |
-
file_path = f"cloud_files/{username}/{filename}"
|
| 500 |
-
api.upload_file(
|
| 501 |
-
path_or_fileobj=temp_path,
|
| 502 |
-
path_in_repo=file_path,
|
| 503 |
-
repo_id=REPO_ID,
|
| 504 |
-
repo_type="dataset",
|
| 505 |
-
token=HF_TOKEN_WRITE,
|
| 506 |
-
commit_message=f"Uploaded file for {username}"
|
| 507 |
-
)
|
| 508 |
-
|
| 509 |
-
file_info = {
|
| 510 |
-
'filename': filename,
|
| 511 |
-
'path': file_path,
|
| 512 |
-
'type': get_file_type(filename),
|
| 513 |
-
'upload_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 514 |
-
}
|
| 515 |
-
data['users'][username]['files'].append(file_info)
|
| 516 |
|
| 517 |
-
|
| 518 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 519 |
|
| 520 |
-
|
| 521 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 522 |
|
| 523 |
-
return redirect(url_for('dashboard'))
|
| 524 |
|
| 525 |
html = '''
|
| 526 |
<!DOCTYPE html>
|
| 527 |
<html lang="ru">
|
| 528 |
<head>
|
| 529 |
-
<meta charset="UTF-8">
|
| 530 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 531 |
<title>Панель управления - Zeus Cloud</title>
|
| 532 |
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
|
|
|
| 533 |
<style>''' + BASE_STYLE + '''</style>
|
| 534 |
</head>
|
| 535 |
<body>
|
| 536 |
<div class="container">
|
| 537 |
-
<h1>
|
| 538 |
-
<p>Пользователь: {{ username }}</p>
|
| 539 |
-
{% with messages = get_flashed_messages() %}
|
| 540 |
{% if messages %}
|
| 541 |
-
{% for message in messages %}
|
| 542 |
-
<div class="flash">{{ message }}</div>
|
| 543 |
{% endfor %}
|
| 544 |
{% endif %}
|
| 545 |
{% endwith %}
|
|
|
|
|
|
|
| 546 |
<form id="upload-form" method="POST" enctype="multipart/form-data">
|
| 547 |
-
<input type="file" name="files" multiple
|
| 548 |
-
<
|
|
|
|
| 549 |
</form>
|
| 550 |
<div id="progress-container">
|
| 551 |
-
<div id="progress-bar"></div>
|
| 552 |
</div>
|
| 553 |
-
|
| 554 |
-
<
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
<
|
| 568 |
-
|
| 569 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
</div>
|
| 571 |
{% endfor %}
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
</
|
| 576 |
-
<
|
| 577 |
-
|
| 578 |
-
<
|
| 579 |
-
<h3>Для пользователей Android:</h3>
|
| 580 |
-
<ol>
|
| 581 |
-
<li>Откройте Zeus Cloud в браузере Chrome.</li>
|
| 582 |
-
<li>Нажмите на меню браузера (обычно три точки вверху справа).</li>
|
| 583 |
-
<li>Выберите <strong>"Добавить на главный экран"</strong>.</li>
|
| 584 |
-
<li>Подтвердите добавление, и иконка приложения появится на вашем главном экране.</li>
|
| 585 |
-
</ol>
|
| 586 |
-
</div>
|
| 587 |
-
<div style="margin-top: 10px;">
|
| 588 |
-
<h3>Для пользователей iOS (iPhone/iPad):</h3>
|
| 589 |
-
<ol>
|
| 590 |
-
<li>Откройте Zeus Cloud в браузере Safari.</li>
|
| 591 |
-
<li>Нажмите кнопку <strong>"Поделиться"</strong> (квадрат со стрелкой вверх) в нижней части экрана.</li>
|
| 592 |
-
<li>Прокрутите список опций вниз и выберите <strong>"Добавить на экран «Домой»"</strong>.</li>
|
| 593 |
-
<li>В правом верхнем углу нажмите <strong>"Добавить"</strong>. Иконка приложения появится на вашем главном экране.</li>
|
| 594 |
-
</ol>
|
| 595 |
-
</div>
|
| 596 |
-
<a href="{{ url_for('logout') }}" class="btn" style="margin-top: 20px;" id="logout-btn">Выйти</a>
|
| 597 |
</div>
|
| 598 |
-
|
| 599 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 600 |
</div>
|
|
|
|
| 601 |
<script>
|
| 602 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 603 |
const modal = document.getElementById('mediaModal');
|
| 604 |
const modalContent = document.getElementById('modalContent');
|
| 605 |
-
|
| 606 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 607 |
} else {
|
| 608 |
-
|
| 609 |
}
|
| 610 |
-
modal.style.display = 'flex';
|
| 611 |
}
|
| 612 |
-
|
|
|
|
| 613 |
const modal = document.getElementById('mediaModal');
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
}
|
| 620 |
-
modalContent.innerHTML = ''; // Очистить содержимое
|
| 621 |
-
}
|
| 622 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 623 |
|
|
|
|
|
|
|
| 624 |
const form = document.getElementById('upload-form');
|
| 625 |
const progressBar = document.getElementById('progress-bar');
|
| 626 |
const progressContainer = document.getElementById('progress-container');
|
| 627 |
const uploadBtn = document.getElementById('upload-btn');
|
|
|
|
| 628 |
|
| 629 |
form.addEventListener('submit', function(e) {
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
if (files.length > 20) {
|
| 633 |
-
alert('Максимум 20 файлов за раз!');
|
| 634 |
-
return;
|
| 635 |
-
}
|
| 636 |
-
if (files.length === 0) {
|
| 637 |
alert('Пожалуйста, выберите файлы для загрузки.');
|
| 638 |
return;
|
| 639 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 640 |
|
|
|
|
|
|
|
| 641 |
const formData = new FormData(form);
|
| 642 |
progressContainer.style.display = 'block';
|
| 643 |
progressBar.style.width = '0%';
|
|
|
|
| 644 |
uploadBtn.disabled = true;
|
|
|
|
| 645 |
|
| 646 |
const xhr = new XMLHttpRequest();
|
| 647 |
-
xhr.open('POST', '
|
| 648 |
|
| 649 |
xhr.upload.onprogress = function(event) {
|
| 650 |
if (event.lengthComputable) {
|
| 651 |
-
const percent = (event.loaded / event.total) * 100;
|
| 652 |
progressBar.style.width = percent + '%';
|
|
|
|
| 653 |
}
|
| 654 |
};
|
| 655 |
|
| 656 |
xhr.onload = function() {
|
| 657 |
uploadBtn.disabled = false;
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
//
|
| 663 |
-
|
| 664 |
} else {
|
| 665 |
-
|
| 666 |
-
|
|
|
|
|
|
|
|
|
|
| 667 |
};
|
| 668 |
|
| 669 |
xhr.onerror = function() {
|
| 670 |
-
alert('Ошибка с
|
| 671 |
progressContainer.style.display = 'none';
|
| 672 |
progressBar.style.width = '0%';
|
|
|
|
| 673 |
uploadBtn.disabled = false;
|
|
|
|
| 674 |
};
|
| 675 |
|
| 676 |
xhr.send(formData);
|
|
@@ -678,380 +757,513 @@ def dashboard():
|
|
| 678 |
|
| 679 |
document.getElementById('logout-btn').addEventListener('click', function(e) {
|
| 680 |
e.preventDefault();
|
| 681 |
-
localStorage.removeItem('zeusCredentials');
|
| 682 |
-
window.location.href = '
|
| 683 |
});
|
| 684 |
</script>
|
| 685 |
</body>
|
| 686 |
-
</html>
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 692 |
if 'username' not in session:
|
| 693 |
-
|
| 694 |
-
return redirect(url_for('login'))
|
| 695 |
|
| 696 |
username = session['username']
|
|
|
|
|
|
|
|
|
|
|
|
|
| 697 |
data = load_data()
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
flash('Пользователь не найден!')
|
| 701 |
-
return redirect(url_for('login'))
|
| 702 |
|
| 703 |
-
|
| 704 |
-
user_files = data['users'][username]['files']
|
| 705 |
-
if not any(file['path'] == file_path for file in user_files):
|
| 706 |
-
# Разрешаем скачивание админу, если он залогинен (проверка в админ панели)
|
| 707 |
-
# Но здесь обычный пользователь, ему нельзя
|
| 708 |
-
is_admin_route = request.referrer and 'admhosto' in request.referrer
|
| 709 |
-
if not is_admin_route: # Если это не админ пытается скачать со своей страницы
|
| 710 |
-
flash('У вас нет доступа к этому файлу!')
|
| 711 |
-
return redirect(url_for('dashboard'))
|
| 712 |
-
# Если это админ, доступ разрешен (неявно, т.к. проверка выше не сработает)
|
| 713 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 714 |
|
| 715 |
-
file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{file_path}?download=true"
|
| 716 |
try:
|
| 717 |
-
api = HfApi()
|
| 718 |
-
# Использование токена для скачивания, если репозиторий приватный
|
| 719 |
headers = {}
|
| 720 |
if HF_TOKEN_READ:
|
| 721 |
headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
|
| 722 |
|
| 723 |
-
response = requests.get(file_url, headers=headers, stream=True)
|
| 724 |
-
response.raise_for_status()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 725 |
|
| 726 |
-
file_content = BytesIO(response.content)
|
| 727 |
return send_file(
|
| 728 |
file_content,
|
| 729 |
as_attachment=True,
|
| 730 |
-
download_name=
|
| 731 |
-
mimetype='application/octet-stream' #
|
| 732 |
)
|
| 733 |
except requests.exceptions.RequestException as e:
|
| 734 |
-
logging.error(f"Error downloading file from HF: {e}")
|
| 735 |
-
flash('Ошибка скачивания файла
|
| 736 |
-
# Определяем, куда редиректить: на дашборд или админку
|
| 737 |
-
if request.referrer and 'admhosto' in request.referrer:
|
| 738 |
-
return redirect(url_for('admin_user_files', username=file_path.split('/')[1])) # Получаем username из пути
|
| 739 |
-
else:
|
| 740 |
-
return redirect(url_for('dashboard'))
|
| 741 |
except Exception as e:
|
| 742 |
-
logging.error(f"Unexpected error during download: {e}")
|
| 743 |
-
flash('Произошла непредвиденная ошибка при скачивании файла.')
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 748 |
|
| 749 |
|
| 750 |
-
@app.route('/delete/<path:
|
| 751 |
-
def delete_file(
|
| 752 |
if 'username' not in session:
|
| 753 |
-
flash('Пожалуйста, войдите в систему!')
|
| 754 |
return redirect(url_for('login'))
|
| 755 |
|
| 756 |
username = session['username']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 757 |
data = load_data()
|
| 758 |
-
if username not in data
|
| 759 |
session.pop('username', None)
|
| 760 |
-
flash('Пользователь не найден!')
|
| 761 |
return redirect(url_for('login'))
|
| 762 |
|
| 763 |
-
user_files = data['users'][username]
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 768 |
return redirect(url_for('dashboard'))
|
| 769 |
|
|
|
|
|
|
|
| 770 |
try:
|
| 771 |
api = HfApi()
|
| 772 |
api.delete_file(
|
| 773 |
-
path_in_repo=
|
| 774 |
repo_id=REPO_ID,
|
| 775 |
repo_type="dataset",
|
| 776 |
token=HF_TOKEN_WRITE,
|
| 777 |
-
commit_message=f"
|
| 778 |
)
|
| 779 |
-
|
|
|
|
|
|
|
|
|
|
| 780 |
save_data(data)
|
| 781 |
-
flash('Файл успешно удален!')
|
|
|
|
| 782 |
except Exception as e:
|
| 783 |
-
|
| 784 |
-
|
|
|
|
|
|
|
|
|
|
| 785 |
|
| 786 |
return redirect(url_for('dashboard'))
|
| 787 |
|
|
|
|
| 788 |
@app.route('/logout')
|
| 789 |
def logout():
|
| 790 |
session.pop('username', None)
|
| 791 |
-
|
| 792 |
-
#
|
| 793 |
return redirect(url_for('login'))
|
| 794 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 795 |
|
| 796 |
@app.route('/admhosto')
|
| 797 |
def admin_panel():
|
| 798 |
-
|
|
|
|
|
|
|
|
|
|
| 799 |
data = load_data()
|
| 800 |
-
users = data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 801 |
|
| 802 |
html = '''
|
| 803 |
-
<!DOCTYPE html>
|
| 804 |
-
<
|
| 805 |
-
<head>
|
| 806 |
-
<meta charset="UTF-8">
|
| 807 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 808 |
<title>Админ-панель - Zeus Cloud</title>
|
| 809 |
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
|
|
|
| 810 |
<style>''' + BASE_STYLE + '''</style>
|
| 811 |
-
</head>
|
| 812 |
-
<
|
| 813 |
-
<
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
{% if messages %}
|
| 834 |
-
<div style="margin-top: 20px;">
|
| 835 |
-
{% for message in messages %}
|
| 836 |
-
<div class="flash">{{ message }}</div>
|
| 837 |
-
{% endfor %}
|
| 838 |
</div>
|
| 839 |
-
|
| 840 |
-
|
|
|
|
| 841 |
</div>
|
| 842 |
-
</
|
| 843 |
-
</html>
|
| 844 |
'''
|
| 845 |
-
return render_template_string(html,
|
|
|
|
| 846 |
|
| 847 |
@app.route('/admhosto/user/<username>')
|
| 848 |
def admin_user_files(username):
|
| 849 |
-
|
|
|
|
|
|
|
|
|
|
| 850 |
data = load_data()
|
| 851 |
-
if username not in data
|
| 852 |
-
flash('Пользователь не найден!')
|
| 853 |
return redirect(url_for('admin_panel'))
|
| 854 |
|
| 855 |
user_files = sorted(data['users'][username].get('files', []), key=lambda x: x.get('upload_date', ''), reverse=True)
|
| 856 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 857 |
html = '''
|
| 858 |
-
<!DOCTYPE html>
|
| 859 |
-
<
|
| 860 |
-
<head>
|
| 861 |
-
<meta charset="UTF-8">
|
| 862 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 863 |
<title>Файлы пользователя {{ username }} - Zeus Cloud</title>
|
| 864 |
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
|
|
|
| 865 |
<style>''' + BASE_STYLE + '''</style>
|
| 866 |
-
</head>
|
| 867 |
-
<
|
| 868 |
-
<
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
{%
|
| 885 |
-
<
|
| 886 |
{% else %}
|
| 887 |
-
<
|
| 888 |
{% endif %}
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 895 |
</div>
|
| 896 |
-
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
|
| 900 |
-
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
|
| 920 |
-
|
| 921 |
-
|
| 922 |
-
|
| 923 |
-
|
| 924 |
-
}
|
| 925 |
-
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
|
| 929 |
-
|
| 930 |
-
|
| 931 |
-
|
| 932 |
-
|
| 933 |
-
|
| 934 |
-
|
| 935 |
-
}
|
| 936 |
-
|
| 937 |
-
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 941 |
'''
|
| 942 |
-
|
| 943 |
-
|
| 944 |
-
|
|
|
|
|
|
|
|
|
|
| 945 |
|
| 946 |
|
| 947 |
@app.route('/admhosto/delete_user/<username>', methods=['POST'])
|
| 948 |
def admin_delete_user(username):
|
| 949 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 950 |
data = load_data()
|
| 951 |
-
if username not in data
|
| 952 |
-
flash('Пользователь не найден!')
|
| 953 |
return redirect(url_for('admin_panel'))
|
| 954 |
|
| 955 |
-
|
| 956 |
|
| 957 |
try:
|
| 958 |
api = HfApi()
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
|
| 963 |
-
|
| 964 |
-
|
| 965 |
-
|
| 966 |
-
|
| 967 |
-
|
| 968 |
-
|
| 969 |
-
|
| 970 |
-
|
| 971 |
-
|
| 972 |
-
|
| 973 |
-
|
| 974 |
-
|
| 975 |
-
|
| 976 |
-
|
| 977 |
-
|
| 978 |
-
|
| 979 |
-
|
| 980 |
-
|
| 981 |
-
|
| 982 |
-
|
| 983 |
-
|
| 984 |
-
|
| 985 |
-
|
| 986 |
-
|
| 987 |
-
|
| 988 |
-
|
| 989 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 990 |
del data['users'][username]
|
| 991 |
save_data(data)
|
| 992 |
-
flash(f'Пользователь {username} и
|
| 993 |
-
logging.info(f"Admin
|
| 994 |
|
| 995 |
except Exception as e:
|
| 996 |
-
logging.error(f"
|
| 997 |
-
flash(f'Ошибка при удалении пользователя {username}
|
| 998 |
|
| 999 |
return redirect(url_for('admin_panel'))
|
| 1000 |
|
| 1001 |
|
| 1002 |
-
@app.route('/admhosto/delete_file/<username>/<path:
|
| 1003 |
-
def admin_delete_file(username,
|
| 1004 |
-
|
| 1005 |
-
|
| 1006 |
-
|
| 1007 |
-
|
| 1008 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1009 |
|
| 1010 |
-
|
| 1011 |
-
file_exists_in_db = any(f['path'] == file_path for f in user_files)
|
| 1012 |
|
| 1013 |
-
|
| 1014 |
-
|
| 1015 |
-
|
| 1016 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1017 |
|
| 1018 |
-
|
| 1019 |
-
|
| 1020 |
-
|
| 1021 |
-
|
| 1022 |
-
|
| 1023 |
-
|
| 1024 |
-
|
| 1025 |
-
|
| 1026 |
-
)
|
| 1027 |
|
| 1028 |
-
# Обновляем базу данных, даже если файла там не было (на всякий случай)
|
| 1029 |
-
data['users'][username]['files'] = [f for f in user_files if f['path'] != file_path]
|
| 1030 |
-
save_data(data)
|
| 1031 |
-
flash('Файл успешно удален!')
|
| 1032 |
-
logging.info(f"Admin deleted file {file_path} for user {username}")
|
| 1033 |
|
| 1034 |
-
|
| 1035 |
-
|
| 1036 |
-
|
| 1037 |
-
|
| 1038 |
|
| 1039 |
-
|
| 1040 |
|
|
|
|
|
|
|
| 1041 |
|
| 1042 |
if __name__ == '__main__':
|
| 1043 |
-
# Проверка наличия токенов при старте
|
| 1044 |
if not HF_TOKEN_WRITE:
|
| 1045 |
-
logging.warning("HF_TOKEN (write access) is
|
| 1046 |
if not HF_TOKEN_READ:
|
| 1047 |
-
logging.warning("HF_TOKEN_READ is not set. Falling back to HF_TOKEN. File downloads might fail for private repos if HF_TOKEN is not set.")
|
| 1048 |
|
| 1049 |
-
# Запуск периодического бэкапа в отдельном потоке
|
| 1050 |
-
# Убедимся, что бэкап запускается только если есть токен для записи
|
| 1051 |
if HF_TOKEN_WRITE:
|
| 1052 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1053 |
else:
|
| 1054 |
-
logging.warning("Periodic backup disabled because
|
|
|
|
|
|
|
|
|
|
| 1055 |
|
| 1056 |
-
#
|
| 1057 |
-
app.run(debug=False, host='0.0.0.0', port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import json
|
|
|
|
| 2 |
import logging
|
| 3 |
+
import os
|
| 4 |
import threading
|
| 5 |
import time
|
| 6 |
+
import uuid
|
| 7 |
from datetime import datetime
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
from flask import (Flask, flash, jsonify, redirect, render_template_string,
|
| 12 |
+
request, send_file, session, url_for)
|
| 13 |
+
from flask_caching import Cache
|
| 14 |
from huggingface_hub import HfApi, hf_hub_download
|
| 15 |
from werkzeug.utils import secure_filename
|
|
|
|
|
|
|
| 16 |
|
| 17 |
app = Flask(__name__)
|
| 18 |
+
app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_dev_12345") # Use a strong secret in production
|
| 19 |
DATA_FILE = 'cloudeng_data.json'
|
| 20 |
+
REPO_ID = "Eluza133/Z1e1u" # Replace with your actual repo ID
|
| 21 |
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
|
| 22 |
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE
|
| 23 |
|
| 24 |
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
|
| 25 |
logging.basicConfig(level=logging.INFO)
|
| 26 |
|
| 27 |
+
# --- Data Handling ---
|
| 28 |
+
|
| 29 |
+
@cache.memoize(timeout=60) # Shorter cache, frequent updates might be needed
|
| 30 |
def load_data():
|
| 31 |
try:
|
| 32 |
download_db_from_hf()
|
|
|
|
| 34 |
data = json.load(file)
|
| 35 |
if not isinstance(data, dict):
|
| 36 |
logging.warning("Data is not in dict format, initializing empty database")
|
| 37 |
+
return {'users': {}, 'files': {}} # files key is legacy, keep for potential old data? No, structure is users -> files
|
| 38 |
data.setdefault('users', {})
|
| 39 |
+
# Ensure each user has a 'files' list
|
| 40 |
+
for user_data in data['users'].values():
|
| 41 |
+
user_data.setdefault('files', [])
|
| 42 |
logging.info("Data successfully loaded")
|
| 43 |
return data
|
| 44 |
+
except FileNotFoundError:
|
| 45 |
+
logging.warning(f"{DATA_FILE} not found locally. Initializing empty database.")
|
| 46 |
+
return {'users': {}}
|
| 47 |
+
except json.JSONDecodeError:
|
| 48 |
+
logging.error(f"Error decoding JSON from {DATA_FILE}. Initializing empty database.")
|
| 49 |
+
return {'users': {}}
|
| 50 |
except Exception as e:
|
| 51 |
logging.error(f"Error loading data: {e}")
|
| 52 |
+
return {'users': {}} # Return empty structure on error
|
| 53 |
|
| 54 |
def save_data(data):
|
| 55 |
try:
|
| 56 |
+
# Ensure data integrity before saving
|
| 57 |
+
if not isinstance(data, dict) or 'users' not in data:
|
| 58 |
+
raise ValueError("Invalid data structure for saving.")
|
| 59 |
+
for username, user_data in data.get('users', {}).items():
|
| 60 |
+
if 'files' not in user_data or not isinstance(user_data['files'], list):
|
| 61 |
+
logging.warning(f"Correcting missing or invalid 'files' list for user {username}")
|
| 62 |
+
user_data['files'] = []
|
| 63 |
+
|
| 64 |
with open(DATA_FILE, 'w', encoding='utf-8') as file:
|
| 65 |
json.dump(data, file, ensure_ascii=False, indent=4)
|
| 66 |
upload_db_to_hf()
|
|
|
|
| 68 |
logging.info("Data saved and uploaded to HF")
|
| 69 |
except Exception as e:
|
| 70 |
logging.error(f"Error saving data: {e}")
|
| 71 |
+
# Don't raise here, maybe log and continue? Or flash a message?
|
| 72 |
+
# For now, let's re-raise to be aware of save failures
|
| 73 |
raise
|
| 74 |
|
| 75 |
def upload_db_to_hf():
|
| 76 |
+
if not HF_TOKEN_WRITE:
|
| 77 |
+
logging.warning("HF Write Token not set. Skipping database upload.")
|
| 78 |
+
return
|
| 79 |
try:
|
| 80 |
api = HfApi()
|
| 81 |
api.upload_file(
|
|
|
|
| 91 |
logging.error(f"Error uploading database: {e}")
|
| 92 |
|
| 93 |
def download_db_from_hf():
|
| 94 |
+
if not HF_TOKEN_READ:
|
| 95 |
+
logging.warning("HF Read Token not set. Skipping database download.")
|
| 96 |
+
# Ensure a default file exists if download fails/is skipped
|
| 97 |
+
if not os.path.exists(DATA_FILE):
|
| 98 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 99 |
+
json.dump({'users': {}}, f)
|
| 100 |
+
return
|
| 101 |
try:
|
| 102 |
hf_hub_download(
|
| 103 |
repo_id=REPO_ID,
|
|
|
|
| 105 |
repo_type="dataset",
|
| 106 |
token=HF_TOKEN_READ,
|
| 107 |
local_dir=".",
|
| 108 |
+
local_dir_use_symlinks=False,
|
| 109 |
+
force_download=True # Ensure we get the latest version
|
| 110 |
)
|
| 111 |
logging.info("Database downloaded from Hugging Face")
|
| 112 |
except Exception as e:
|
| 113 |
+
# More specific error handling (e.g., 404 Not Found)
|
| 114 |
+
logging.error(f"Error downloading database: {e}. This might happen if the file doesn't exist on the Hub yet.")
|
| 115 |
if not os.path.exists(DATA_FILE):
|
| 116 |
+
logging.info("Creating empty database file locally as download failed and file doesn't exist.")
|
| 117 |
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 118 |
+
json.dump({'users': {}}, f)
|
| 119 |
|
| 120 |
def periodic_backup():
|
| 121 |
while True:
|
| 122 |
+
time.sleep(1800) # Backup every 30 minutes
|
| 123 |
+
logging.info("Initiating periodic backup...")
|
| 124 |
+
# Reload data before backing up? No, save_data handles upload.
|
| 125 |
+
# Just call the upload function directly.
|
| 126 |
upload_db_to_hf()
|
| 127 |
+
|
| 128 |
|
| 129 |
def get_file_type(filename):
|
| 130 |
+
filename_lower = filename.lower()
|
| 131 |
+
if filename_lower.endswith(('.mp4', '.mov', '.avi', '.webm', '.mkv', '.wmv')):
|
|
|
|
| 132 |
return 'video'
|
| 133 |
+
elif filename_lower.endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg')):
|
| 134 |
return 'image'
|
| 135 |
+
elif filename_lower.endswith('.pdf'):
|
| 136 |
+
return 'pdf'
|
| 137 |
+
elif filename_lower.endswith(('.txt', '.md', '.log', '.csv', '.json', '.yaml', '.xml', '.html', '.css', '.js', '.py', '.sh')):
|
| 138 |
+
return 'text'
|
| 139 |
return 'other'
|
| 140 |
|
| 141 |
+
# --- Styles ---
|
| 142 |
BASE_STYLE = '''
|
| 143 |
:root {
|
| 144 |
+
--primary: #ff4d6d; --secondary: #00ddeb; --accent: #8b5cf6;
|
| 145 |
+
--background-light: #f5f6fa; --background-dark: #1a1625;
|
| 146 |
+
--card-bg: rgba(255, 255, 255, 0.95); --card-bg-dark: rgba(40, 35, 60, 0.95);
|
| 147 |
+
--text-light: #2a1e5a; --text-dark: #e8e1ff;
|
| 148 |
+
--shadow: 0 10px 30px rgba(0, 0, 0, 0.2); --glass-bg: rgba(255, 255, 255, 0.15);
|
| 149 |
+
--transition: all 0.3s ease; --delete-color: #ff4444;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
}
|
| 151 |
* { margin: 0; padding: 0; box-sizing: border-box; }
|
| 152 |
+
body { font-family: 'Inter', sans-serif; background: var(--background-light); color: var(--text-light); line-height: 1.6; }
|
| 153 |
+
body.dark { background: var(--background-dark); color: var(--text-dark); }
|
| 154 |
+
.container { margin: 20px auto; max-width: 1200px; padding: 25px; background: var(--card-bg); border-radius: 20px; box-shadow: var(--shadow); }
|
| 155 |
+
body.dark .container { background: var(--card-bg-dark); }
|
| 156 |
+
h1 { font-size: 2em; font-weight: 800; text-align: center; margin-bottom: 25px; background: linear-gradient(135deg, var(--primary), var(--accent)); -webkit-background-clip: text; color: transparent; }
|
| 157 |
+
h2 { font-size: 1.5em; margin-top: 30px; margin-bottom: 15px; color: var(--text-light); border-bottom: 2px solid var(--accent); padding-bottom: 5px;}
|
| 158 |
+
body.dark h2 { color: var(--text-dark); border-bottom-color: var(--secondary); }
|
| 159 |
+
input, textarea, select { 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); }
|
| 160 |
+
body.dark input, body.dark textarea, body.dark select { color: var(--text-dark); background: rgba(0, 0, 0, 0.2); }
|
| 161 |
+
input:focus, textarea:focus, select:focus { outline: none; box-shadow: 0 0 0 4px var(--primary); }
|
| 162 |
+
.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; text-align: center; }
|
| 163 |
+
.btn:hover { transform: scale(1.05); background: #e6415f; }
|
| 164 |
+
.download-btn { background: var(--secondary); margin-top: 10px; }
|
| 165 |
+
.download-btn:hover { background: #00b8c5; }
|
| 166 |
+
.delete-btn { background: var(--delete-color); margin-top: 10px; }
|
| 167 |
+
.delete-btn:hover { background: #cc3333; }
|
| 168 |
+
.flash { padding: 10px; margin-bottom: 15px; border-radius: 10px; text-align: center; }
|
| 169 |
+
.flash.success { background-color: rgba(0, 221, 235, 0.2); color: var(--secondary); }
|
| 170 |
+
.flash.error { background-color: rgba(255, 77, 109, 0.2); color: var(--primary); }
|
| 171 |
+
.file-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 20px; margin-top: 20px; }
|
| 172 |
+
.folder-section { margin-bottom: 30px; }
|
| 173 |
+
.folder-title { font-size: 1.3em; font-weight: 700; margin-bottom: 15px; padding-left: 10px; border-left: 4px solid var(--accent); }
|
| 174 |
+
body.dark .folder-title { border-left-color: var(--secondary); }
|
| 175 |
+
.user-list { margin-top: 20px; }
|
| 176 |
+
.user-item { padding: 15px; background: var(--card-bg); border-radius: 16px; margin-bottom: 10px; box-shadow: var(--shadow); transition: var(--transition); display: flex; justify-content: space-between; align-items: center; }
|
| 177 |
+
body.dark .user-item { background: var(--card-bg-dark); }
|
| 178 |
+
.user-item:hover { transform: translateY(-5px); }
|
| 179 |
+
.user-item a { color: var(--primary); text-decoration: none; font-weight: 600; }
|
| 180 |
+
.user-item a:hover { color: var(--accent); }
|
| 181 |
+
.user-item span { font-size: 0.9em; opacity: 0.8; }
|
| 182 |
+
@media (max-width: 768px) { .file-grid { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); } }
|
| 183 |
+
@media (max-width: 480px) { .file-grid { grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); } }
|
| 184 |
+
.file-item { background: var(--card-bg); padding: 10px; border-radius: 16px; box-shadow: var(--shadow); text-align: center; transition: var(--transition); display: flex; flex-direction: column; justify-content: space-between; height: 100%; }
|
| 185 |
+
body.dark .file-item { background: var(--card-bg-dark); }
|
| 186 |
+
.file-item:hover { transform: translateY(-5px); }
|
| 187 |
+
.file-preview-container { height: 120px; display: flex; align-items: center; justify-content: center; margin-bottom: 10px; cursor: pointer; background-color: rgba(0,0,0,0.05); border-radius: 10px; overflow: hidden;}
|
| 188 |
+
body.dark .file-preview-container { background-color: rgba(255,255,255,0.05); }
|
| 189 |
+
.file-preview { max-width: 100%; max-height: 100%; object-fit: cover; border-radius: 10px; display: block; }
|
| 190 |
+
.file-icon { font-size: 40px; color: var(--accent); } /* For non-previewable files */
|
| 191 |
+
.file-info { margin-top: auto; } /* Pushes info and buttons down */
|
| 192 |
+
.file-item p { font-size: 0.85em; margin: 4px 0; word-break: break-all; }
|
| 193 |
+
.file-item .filename { font-weight: 600; }
|
| 194 |
+
.file-item .date { font-size: 0.75em; opacity: 0.7; }
|
| 195 |
+
.file-item .actions { margin-top: 8px; display: flex; justify-content: space-around; gap: 5px;}
|
| 196 |
+
.file-item .actions .btn { padding: 6px 10px; font-size: 0.8em; }
|
| 197 |
+
.modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.9); z-index: 2000; justify-content: center; align-items: center; padding: 20px; }
|
| 198 |
+
.modal-content { max-width: 95%; max-height: 95%; background: var(--card-bg-dark); padding: 5px; border-radius: 10px; position: relative; }
|
| 199 |
+
body.dark .modal-content { background: var(--card-bg-dark); } /* Keep dark for contrast */
|
| 200 |
+
.modal img, .modal video, .modal iframe, .modal pre { display: block; max-width: 100%; max-height: calc(95vh - 50px); /* Adjust for padding/close button */ margin: auto; border: none; }
|
| 201 |
+
.modal pre { background: #fff; color: #333; padding: 15px; border-radius: 5px; white-space: pre-wrap; word-wrap: break-word; overflow-y: auto; font-size: 0.9em; height: calc(95vh - 50px); }
|
| 202 |
+
.modal-close { position: absolute; top: -10px; right: -10px; background: var(--primary); color: white; border: none; border-radius: 50%; width: 30px; height: 30px; font-size: 1.2em; cursor: pointer; line-height: 30px; text-align: center; box-shadow: var(--shadow); }
|
| 203 |
+
#progress-container { width: 100%; background: var(--glass-bg); border-radius: 10px; margin: 15px 0; display: none; overflow: hidden; }
|
| 204 |
+
#progress-bar { width: 0%; height: 20px; background: linear-gradient(90deg, var(--primary), var(--accent)); border-radius: 10px 0 0 10px; transition: width 0.3s ease; text-align: center; color: white; line-height: 20px; font-size: 0.8em; }
|
| 205 |
+
#upload-form { display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-end; margin-bottom: 15px;}
|
| 206 |
+
#upload-form input[type="file"] { flex-grow: 1; }
|
| 207 |
+
#upload-form input[type="text"] { width: auto; flex-grow: 1; margin: 0; } /* Adjust folder input */
|
| 208 |
+
#upload-form button { margin: 0; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
'''
|
| 210 |
|
| 211 |
+
# --- Routes ---
|
| 212 |
+
|
| 213 |
@app.route('/register', methods=['GET', 'POST'])
|
| 214 |
def register():
|
| 215 |
if request.method == 'POST':
|
| 216 |
username = request.form.get('username')
|
| 217 |
password = request.form.get('password')
|
| 218 |
|
| 219 |
+
if not username or not password:
|
| 220 |
+
flash('Имя пользователя и пароль обязательны!', 'error')
|
| 221 |
+
return redirect(url_for('register'))
|
| 222 |
+
|
| 223 |
+
# Basic validation (add more as needed)
|
| 224 |
+
if len(username) < 3 or len(password) < 6:
|
| 225 |
+
flash('Имя пользователя должно быть не менее 3 символов, пароль не менее 6.', 'error')
|
| 226 |
+
return redirect(url_for('register'))
|
| 227 |
+
|
| 228 |
+
# Use locking for concurrent requests if necessary (complex setup)
|
| 229 |
data = load_data()
|
| 230 |
|
| 231 |
if username in data['users']:
|
| 232 |
+
flash('Пользователь с таким именем уже существует!', 'error')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
return redirect(url_for('register'))
|
| 234 |
|
| 235 |
data['users'][username] = {
|
| 236 |
+
'password': password, # In a real app, HASH the password!
|
| 237 |
'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
| 238 |
'files': []
|
| 239 |
}
|
| 240 |
+
try:
|
| 241 |
+
save_data(data)
|
| 242 |
+
session['username'] = username
|
| 243 |
+
flash('Регистрация прошла успешно!', 'success')
|
| 244 |
+
return redirect(url_for('dashboard'))
|
| 245 |
+
except Exception as e:
|
| 246 |
+
flash('Ошибка при сохранении данных пользователя.', 'error')
|
| 247 |
+
logging.error(f"Error saving during registration for {username}: {e}")
|
| 248 |
+
return redirect(url_for('register'))
|
| 249 |
+
|
| 250 |
|
| 251 |
html = '''
|
| 252 |
<!DOCTYPE html>
|
| 253 |
<html lang="ru">
|
| 254 |
<head>
|
| 255 |
+
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
|
|
| 256 |
<title>Регистрация - Zeus Cloud</title>
|
| 257 |
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 258 |
<style>''' + BASE_STYLE + '''</style>
|
|
|
|
| 260 |
<body>
|
| 261 |
<div class="container">
|
| 262 |
<h1>Регистрация в Zeus Cloud</h1>
|
| 263 |
+
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 264 |
{% if messages %}
|
| 265 |
+
{% for category, message in messages %}
|
| 266 |
+
<div class="flash {{ category }}">{{ message }}</div>
|
| 267 |
{% endfor %}
|
| 268 |
{% endif %}
|
| 269 |
{% endwith %}
|
| 270 |
+
<form method="POST">
|
| 271 |
+
<input type="text" name="username" placeholder="Имя пользователя (мин. 3)" required minlength="3">
|
| 272 |
+
<input type="password" name="password" placeholder="Пароль (мин. 6)" required minlength="6">
|
| 273 |
<button type="submit" class="btn">Зарегистрироваться</button>
|
| 274 |
</form>
|
| 275 |
<p style="margin-top: 20px;">Уже есть аккаунт? <a href="{{ url_for('login') }}">Войти</a></p>
|
| 276 |
</div>
|
| 277 |
</body>
|
| 278 |
+
</html>'''
|
|
|
|
| 279 |
return render_template_string(html)
|
| 280 |
|
| 281 |
@app.route('/', methods=['GET', 'POST'])
|
|
|
|
| 285 |
password = request.form.get('password')
|
| 286 |
data = load_data()
|
| 287 |
|
| 288 |
+
# IMPORTANT: NEVER store plain passwords. Use hashing (e.g., werkzeug.security.generate_password_hash/check_password_hash)
|
| 289 |
+
if username in data['users'] and data['users'][username].get('password') == password:
|
| 290 |
session['username'] = username
|
| 291 |
+
session.permanent = True # Make session last longer
|
| 292 |
+
app.permanent_session_lifetime = timedelta(days=30) # Example: 30 days
|
| 293 |
return jsonify({'status': 'success', 'redirect': url_for('dashboard')})
|
| 294 |
else:
|
| 295 |
return jsonify({'status': 'error', 'message': 'Неверное имя пользователя или пароль!'})
|
| 296 |
|
| 297 |
+
if 'username' in session:
|
| 298 |
+
return redirect(url_for('dashboard'))
|
| 299 |
+
|
| 300 |
+
|
| 301 |
html = '''
|
| 302 |
<!DOCTYPE html>
|
| 303 |
<html lang="ru">
|
| 304 |
<head>
|
| 305 |
+
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 306 |
+
<title>Вход - Zeus Cloud</title>
|
|
|
|
| 307 |
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 308 |
<style>''' + BASE_STYLE + '''</style>
|
| 309 |
+
<script>
|
| 310 |
+
// Basic client-side check for saved credentials (consider security implications)
|
| 311 |
+
document.addEventListener('DOMContentLoaded', () => {
|
| 312 |
+
const savedCredentials = JSON.parse(localStorage.getItem('zeusCredentials'));
|
| 313 |
+
if (savedCredentials && savedCredentials.username && savedCredentials.password) {
|
| 314 |
+
// Attempt auto-login only if needed (prevents loop if already logged in server-side)
|
| 315 |
+
if (!document.cookie.includes('session=')) { // Simple check, might not be foolproof
|
| 316 |
+
attemptAutoLogin(savedCredentials.username, savedCredentials.password);
|
| 317 |
+
}
|
| 318 |
+
}
|
| 319 |
+
});
|
| 320 |
+
|
| 321 |
+
function attemptAutoLogin(username, password) {
|
| 322 |
+
fetch('/', {
|
| 323 |
+
method: 'POST',
|
| 324 |
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', },
|
| 325 |
+
body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`
|
| 326 |
+
})
|
| 327 |
+
.then(response => response.json())
|
| 328 |
+
.then(data => {
|
| 329 |
+
if (data.status === 'success') {
|
| 330 |
+
window.location.href = data.redirect;
|
| 331 |
+
} else {
|
| 332 |
+
// Clear invalid stored credentials
|
| 333 |
+
localStorage.removeItem('zeusCredentials');
|
| 334 |
+
}
|
| 335 |
+
})
|
| 336 |
+
.catch(error => console.error('Ошибка автовхода:', error));
|
| 337 |
+
}
|
| 338 |
+
</script>
|
| 339 |
</head>
|
| 340 |
<body>
|
| 341 |
<div class="container">
|
| 342 |
<h1>Zeus Cloud</h1>
|
| 343 |
<div id="flash-messages">
|
| 344 |
+
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 345 |
{% if messages %}
|
| 346 |
+
{% for category, message in messages %}
|
| 347 |
+
<div class="flash {{ category }}">{{ message }}</div>
|
| 348 |
{% endfor %}
|
| 349 |
{% endif %}
|
| 350 |
+
{% endwith %}
|
| 351 |
</div>
|
| 352 |
<form method="POST" id="login-form">
|
| 353 |
+
<input type="text" name="username" placeholder="Имя пользователя" required>
|
| 354 |
+
<input type="password" name="password" placeholder="Пароль" required>
|
| 355 |
+
<label style="display: block; margin-top: 10px; font-size: 0.9em;">
|
| 356 |
+
<input type="checkbox" id="remember-me" style="width: auto; margin-right: 5px;"> Запомнить меня
|
| 357 |
+
</label>
|
| 358 |
+
<button type="submit" class="btn" style="margin-top: 15px;">Войти</button>
|
| 359 |
</form>
|
| 360 |
<p style="margin-top: 20px;">Нет аккаунта? <a href="{{ url_for('register') }}">Зарегистрируйтесь</a></p>
|
| 361 |
</div>
|
| 362 |
<script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
document.getElementById('login-form').addEventListener('submit', function(e) {
|
| 364 |
e.preventDefault();
|
| 365 |
const formData = new FormData(this);
|
| 366 |
+
const rememberMe = document.getElementById('remember-me').checked;
|
| 367 |
+
|
| 368 |
fetch('/', {
|
| 369 |
method: 'POST',
|
| 370 |
body: formData
|
| 371 |
})
|
| 372 |
.then(response => response.json())
|
| 373 |
.then(data => {
|
| 374 |
+
const flashDiv = document.getElementById('flash-messages');
|
| 375 |
+
flashDiv.innerHTML = ''; // Clear previous messages
|
| 376 |
if (data.status === 'success') {
|
| 377 |
+
if (rememberMe) {
|
| 378 |
+
const username = formData.get('username');
|
| 379 |
+
const password = formData.get('password'); // Storing password in localStorage is insecure! Avoid if possible.
|
| 380 |
+
localStorage.setItem('zeusCredentials', JSON.stringify({ username, password }));
|
| 381 |
+
} else {
|
| 382 |
+
localStorage.removeItem('zeusCredentials');
|
| 383 |
+
}
|
| 384 |
window.location.href = data.redirect;
|
| 385 |
} else {
|
| 386 |
+
flashDiv.innerHTML = `<div class="flash error">${data.message}</div>`;
|
| 387 |
}
|
| 388 |
})
|
| 389 |
.catch(error => {
|
| 390 |
+
console.error('Ошибка входа:', error);
|
| 391 |
+
document.getElementById('flash-messages').innerHTML = `<div class="flash error">Ошибка соединения! Попробуйте позже.</div>`;
|
| 392 |
});
|
| 393 |
});
|
| 394 |
</script>
|
| 395 |
</body>
|
| 396 |
+
</html>'''
|
|
|
|
| 397 |
return render_template_string(html)
|
| 398 |
|
| 399 |
+
|
| 400 |
@app.route('/dashboard', methods=['GET', 'POST'])
|
| 401 |
def dashboard():
|
| 402 |
if 'username' not in session:
|
| 403 |
+
flash('Пожалуйста, войдите в систему!', 'error')
|
| 404 |
return redirect(url_for('login'))
|
| 405 |
|
| 406 |
username = session['username']
|
| 407 |
data = load_data()
|
| 408 |
+
if username not in data.get('users', {}):
|
| 409 |
session.pop('username', None)
|
| 410 |
+
flash('Пользователь не найден! Пожалуйста, войдите снова.', 'error')
|
| 411 |
return redirect(url_for('login'))
|
| 412 |
|
| 413 |
+
# Ensure user data structure is correct
|
| 414 |
+
user_data = data['users'][username]
|
| 415 |
+
if 'files' not in user_data or not isinstance(user_data['files'], list):
|
| 416 |
+
user_data['files'] = []
|
| 417 |
+
|
| 418 |
|
| 419 |
if request.method == 'POST':
|
| 420 |
+
if not HF_TOKEN_WRITE:
|
| 421 |
+
flash('Ошибка: Загрузка невозможна, отсутствует токен записи Hugging Face.', 'error')
|
| 422 |
+
return redirect(url_for('dashboard'))
|
| 423 |
+
|
| 424 |
files = request.files.getlist('files')
|
| 425 |
+
folder_name = request.form.get('folder_name', '').strip()
|
| 426 |
+
# Basic folder name validation/sanitization
|
| 427 |
+
safe_folder_name = secure_filename(folder_name) if folder_name else ""
|
| 428 |
+
|
| 429 |
+
if not files or all(not f.filename for f in files):
|
| 430 |
+
flash('Пожалуйста, выберите файлы для загрузки.', 'error')
|
| 431 |
return redirect(url_for('dashboard'))
|
| 432 |
|
| 433 |
+
if len(files) > 20: # Limit number of files per upload
|
| 434 |
+
flash('Максимум 20 файлов за раз!', 'error')
|
| 435 |
+
return redirect(url_for('dashboard'))
|
|
|
|
| 436 |
|
| 437 |
+
# Consider checking total upload size limit here
|
| 438 |
+
|
| 439 |
+
os.makedirs('uploads', exist_ok=True)
|
| 440 |
+
api = HfApi()
|
| 441 |
+
uploaded_count = 0
|
| 442 |
+
error_count = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 443 |
|
| 444 |
+
for file in files:
|
| 445 |
+
if file and file.filename:
|
| 446 |
+
original_filename = secure_filename(file.filename)
|
| 447 |
+
if not original_filename: # Skip if filename becomes empty after securing
|
| 448 |
+
error_count += 1
|
| 449 |
+
continue
|
| 450 |
|
| 451 |
+
unique_id = uuid.uuid4().hex
|
| 452 |
+
_, ext = os.path.splitext(original_filename)
|
| 453 |
+
storage_filename = f"{unique_id}{ext}"
|
| 454 |
+
|
| 455 |
+
folder_prefix_hf = f"cloud_files/{username}"
|
| 456 |
+
display_prefix = ""
|
| 457 |
+
if safe_folder_name:
|
| 458 |
+
folder_prefix_hf += f"/{safe_folder_name}"
|
| 459 |
+
display_prefix = f"{safe_folder_name}/"
|
| 460 |
+
|
| 461 |
+
storage_path = f"{folder_prefix_hf}/{storage_filename}"
|
| 462 |
+
# display_path stores relative path including original name
|
| 463 |
+
display_path = f"{display_prefix}{original_filename}"
|
| 464 |
+
|
| 465 |
+
temp_path = os.path.join('uploads', f"{unique_id}_{original_filename}") # Use unique temp name
|
| 466 |
+
|
| 467 |
+
try:
|
| 468 |
+
file.save(temp_path)
|
| 469 |
+
|
| 470 |
+
api.upload_file(
|
| 471 |
+
path_or_fileobj=temp_path,
|
| 472 |
+
path_in_repo=storage_path,
|
| 473 |
+
repo_id=REPO_ID,
|
| 474 |
+
repo_type="dataset",
|
| 475 |
+
token=HF_TOKEN_WRITE,
|
| 476 |
+
commit_message=f"User {username} uploaded {display_path}"
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
file_info = {
|
| 480 |
+
'original_filename': original_filename,
|
| 481 |
+
'storage_path': storage_path, # Full path on HF
|
| 482 |
+
'display_path': display_path, # Relative path for user display
|
| 483 |
+
'type': get_file_type(original_filename),
|
| 484 |
+
'upload_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 485 |
+
}
|
| 486 |
+
# Ensure the files list exists before appending
|
| 487 |
+
if 'files' not in data['users'][username]:
|
| 488 |
+
data['users'][username]['files'] = []
|
| 489 |
+
data['users'][username]['files'].append(file_info)
|
| 490 |
+
uploaded_count += 1
|
| 491 |
+
|
| 492 |
+
except Exception as e:
|
| 493 |
+
logging.error(f"Error uploading file {original_filename} for {username}: {e}")
|
| 494 |
+
error_count += 1
|
| 495 |
+
finally:
|
| 496 |
+
if os.path.exists(temp_path):
|
| 497 |
+
os.remove(temp_path) # Clean up temp file
|
| 498 |
+
|
| 499 |
+
try:
|
| 500 |
+
save_data(data) # Save data after processing all files in the batch
|
| 501 |
+
if uploaded_count > 0:
|
| 502 |
+
flash(f'{uploaded_count} файл(ов) успешно загружено!', 'success')
|
| 503 |
+
if error_count > 0:
|
| 504 |
+
flash(f'{error_count} файл(ов) не удалось загрузить.', 'error')
|
| 505 |
+
except Exception as e:
|
| 506 |
+
flash('Критическая ошибка: Не удалось сохранить информацию о загруженных файлах.', 'error')
|
| 507 |
+
logging.error(f"Error saving data after uploads for {username}: {e}")
|
| 508 |
+
|
| 509 |
+
return redirect(url_for('dashboard')) # Redirect after POST
|
| 510 |
+
|
| 511 |
+
# --- GET Request Logic ---
|
| 512 |
+
user_files = sorted(user_data.get('files', []), key=lambda x: x.get('upload_date', ''), reverse=True)
|
| 513 |
+
|
| 514 |
+
# Group files by folder
|
| 515 |
+
files_by_folder = {'': []} # '' key for root files
|
| 516 |
+
for file in user_files:
|
| 517 |
+
display_path = file.get('display_path', file.get('original_filename', 'unknown')) # Fallback needed?
|
| 518 |
+
folder = ''
|
| 519 |
+
if '/' in display_path:
|
| 520 |
+
folder = display_path.rsplit('/', 1)[0]
|
| 521 |
+
if folder not in files_by_folder:
|
| 522 |
+
files_by_folder[folder] = []
|
| 523 |
+
files_by_folder[folder].append(file)
|
| 524 |
+
|
| 525 |
+
# Sort folders (root first, then alphabetically)
|
| 526 |
+
sorted_folders = sorted(files_by_folder.keys(), key=lambda x: (x != '', x))
|
| 527 |
|
|
|
|
| 528 |
|
| 529 |
html = '''
|
| 530 |
<!DOCTYPE html>
|
| 531 |
<html lang="ru">
|
| 532 |
<head>
|
| 533 |
+
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
|
|
| 534 |
<title>Панель управления - Zeus Cloud</title>
|
| 535 |
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 536 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"> <!-- Font Awesome for icons -->
|
| 537 |
<style>''' + BASE_STYLE + '''</style>
|
| 538 |
</head>
|
| 539 |
<body>
|
| 540 |
<div class="container">
|
| 541 |
+
<h1>Zeus Cloud</h1>
|
| 542 |
+
<p style="text-align: center; margin-bottom: 20px;">Пользователь: <strong>{{ username }}</strong></p>
|
| 543 |
+
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 544 |
{% if messages %}
|
| 545 |
+
{% for category, message in messages %}
|
| 546 |
+
<div class="flash {{ category }}">{{ message }}</div>
|
| 547 |
{% endfor %}
|
| 548 |
{% endif %}
|
| 549 |
{% endwith %}
|
| 550 |
+
|
| 551 |
+
<h2>Загрузить файлы</h2>
|
| 552 |
<form id="upload-form" method="POST" enctype="multipart/form-data">
|
| 553 |
+
<input type="file" name="files" multiple>
|
| 554 |
+
<input type="text" name="folder_name" placeholder="Имя папки (необязательно)">
|
| 555 |
+
<button type="submit" class="btn" id="upload-btn">Загрузить</button>
|
| 556 |
</form>
|
| 557 |
<div id="progress-container">
|
| 558 |
+
<div id="progress-bar">0%</div>
|
| 559 |
</div>
|
| 560 |
+
|
| 561 |
+
<h2>Ваши файлы</h2>
|
| 562 |
+
{% if not files_by_folder or (len(files_by_folder) == 1 and not files_by_folder['']) %}
|
| 563 |
+
<p>Вы еще не загрузили ни одного файла.</p>
|
| 564 |
+
{% else %}
|
| 565 |
+
{% for folder_name in sorted_folders %}
|
| 566 |
+
<div class="folder-section">
|
| 567 |
+
<h3 class="folder-title">
|
| 568 |
+
{% if folder_name == '' %}
|
| 569 |
+
<i class="fas fa-folder"></i> Корень
|
| 570 |
+
{% else %}
|
| 571 |
+
<i class="fas fa-folder"></i> {{ folder_name }}
|
| 572 |
+
{% endif %}
|
| 573 |
+
</h3>
|
| 574 |
+
<div class="file-grid">
|
| 575 |
+
{% for file in files_by_folder[folder_name] %}
|
| 576 |
+
<div class="file-item">
|
| 577 |
+
<div class="file-preview-container" onclick="openModal('{{ file.storage_path | urlencode }}', '{{ file.type }}')">
|
| 578 |
+
{% set preview_url = "https://huggingface.co/datasets/" + repo_id + "/resolve/main/" + file.storage_path %}
|
| 579 |
+
{% if file.type == 'video' %}
|
| 580 |
+
<video class="file-preview" preload="metadata" muted><source src="{{ preview_url }}" type="video/mp4"></video>
|
| 581 |
+
{% elif file.type == 'image' %}
|
| 582 |
+
<img class="file-preview" src="{{ preview_url }}" alt="{{ file.original_filename }}" loading="lazy">
|
| 583 |
+
{% elif file.type == 'pdf' %}
|
| 584 |
+
<i class="fas fa-file-pdf file-icon" style="color: #e74c3c;"></i>
|
| 585 |
+
{% elif file.type == 'text' %}
|
| 586 |
+
<i class="fas fa-file-alt file-icon" style="color: #3498db;"></i>
|
| 587 |
+
{% else %}
|
| 588 |
+
<i class="fas fa-file file-icon" style="color: #95a5a6;"></i>
|
| 589 |
+
{% endif %}
|
| 590 |
+
</div>
|
| 591 |
+
<div class="file-info">
|
| 592 |
+
<p class="filename" title="{{ file.original_filename }}">{{ file.original_filename[:25] }}{{ '...' if file.original_filename|length > 25 else '' }}</p>
|
| 593 |
+
<p class="date">{{ file.upload_date }}</p>
|
| 594 |
+
<div class="actions">
|
| 595 |
+
<a href="{{ url_for('download_file', storage_path=file.storage_path | urlencode, original_filename=file.original_filename) }}" class="btn download-btn" title="Скачать"><i class="fas fa-download"></i></a>
|
| 596 |
+
<a href="{{ url_for('delete_file', storage_path=file.storage_path | urlencode ) }}" class="btn delete-btn" title="Удалить" onclick="return confirm('Удалить {{ file.original_filename }}?');"><i class="fas fa-trash"></i></a>
|
| 597 |
+
</div>
|
| 598 |
+
</div>
|
| 599 |
+
</div>
|
| 600 |
+
{% endfor %}
|
| 601 |
+
</div>
|
| 602 |
</div>
|
| 603 |
{% endfor %}
|
| 604 |
+
{% endif %}
|
| 605 |
+
|
| 606 |
+
<h2 style="margin-top: 40px;">Добавить на главный экран</h2>
|
| 607 |
+
<p>Инструкции по добавлению PWA (Progressive Web App) на ваш телефон для быстрого доступа.</p>
|
| 608 |
+
<!-- PWA Instructions -->
|
| 609 |
+
|
| 610 |
+
<a href="{{ url_for('logout') }}" class="btn" style="margin-top: 30px; background-color: var(--accent);" id="logout-btn">Выйти</a>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 611 |
</div>
|
| 612 |
+
|
| 613 |
+
<div class="modal" id="mediaModal">
|
| 614 |
+
<button class="modal-close" onclick="closeModal()">×</button>
|
| 615 |
+
<div class="modal-content" id="modalContentWrapper">
|
| 616 |
+
<div id="modalContent"></div>
|
| 617 |
+
</div>
|
| 618 |
</div>
|
| 619 |
+
|
| 620 |
<script>
|
| 621 |
+
const repoId = "{{ repo_id }}";
|
| 622 |
+
const hfTokenRead = "{{ HF_TOKEN_READ or '' }}"; // Pass token if needed for private previews
|
| 623 |
+
|
| 624 |
+
function escapeHtml(unsafe) {
|
| 625 |
+
return unsafe
|
| 626 |
+
.replace(/&/g, "&")
|
| 627 |
+
.replace(/</g, "<")
|
| 628 |
+
.replace(/>/g, ">")
|
| 629 |
+
.replace(/"/g, """)
|
| 630 |
+
.replace(/'/g, "'");
|
| 631 |
+
}
|
| 632 |
+
|
| 633 |
+
function openModal(encodedStoragePath, fileType) {
|
| 634 |
+
const storagePath = decodeURIComponent(encodedStoragePath);
|
| 635 |
const modal = document.getElementById('mediaModal');
|
| 636 |
const modalContent = document.getElementById('modalContent');
|
| 637 |
+
modalContent.innerHTML = '<p style="text-align:center; color:white; padding: 20px;">Загрузка...</p>'; // Loading indicator
|
| 638 |
+
modal.style.display = 'flex';
|
| 639 |
+
|
| 640 |
+
const fileUrl = `https://huggingface.co/datasets/${repoId}/resolve/main/${storagePath}`;
|
| 641 |
+
const downloadUrl = `${fileUrl}?download=true`; // Use download=true for raw content
|
| 642 |
+
|
| 643 |
+
const headers = {};
|
| 644 |
+
if (hfTokenRead) {
|
| 645 |
+
headers['Authorization'] = `Bearer ${hfTokenRead}`;
|
| 646 |
+
}
|
| 647 |
+
|
| 648 |
+
if (fileType === 'image') {
|
| 649 |
+
modalContent.innerHTML = `<img src="${fileUrl}" alt="Предпросмотр">`; // Browser handles image loading/auth usually
|
| 650 |
+
} else if (fileType === 'video') {
|
| 651 |
+
modalContent.innerHTML = `<video controls autoplay><source src="${fileUrl}" type="video/mp4"></video>`; // Browser handles video loading/auth
|
| 652 |
+
} else if (fileType === 'pdf') {
|
| 653 |
+
// Embedding PDF, might have issues with private repos depending on browser/HF setup
|
| 654 |
+
modalContent.innerHTML = `<iframe src="${fileUrl}" width="100%" height="calc(95vh - 50px)"></iframe>`;
|
| 655 |
+
} else if (fileType === 'text') {
|
| 656 |
+
fetch(downloadUrl, { headers: headers })
|
| 657 |
+
.then(response => {
|
| 658 |
+
if (!response.ok) {
|
| 659 |
+
throw new Error(`HTTP error! status: ${response.status}`);
|
| 660 |
+
}
|
| 661 |
+
return response.text();
|
| 662 |
+
})
|
| 663 |
+
.then(text => {
|
| 664 |
+
modalContent.innerHTML = `<pre>${escapeHtml(text)}</pre>`;
|
| 665 |
+
})
|
| 666 |
+
.catch(err => {
|
| 667 |
+
console.error("Error fetching text content:", err);
|
| 668 |
+
modalContent.innerHTML = '<p style="color:red; text-align:center;">Не удалось загрузить текстовое содержимое.</p>';
|
| 669 |
+
});
|
| 670 |
} else {
|
| 671 |
+
modalContent.innerHTML = '<p style="color:white; text-align:center;">Предпросмотр для этого типа файла недоступен.</p>';
|
| 672 |
}
|
|
|
|
| 673 |
}
|
| 674 |
+
|
| 675 |
+
function closeModal() {
|
| 676 |
const modal = document.getElementById('mediaModal');
|
| 677 |
+
const modalContent = document.getElementById('modalContent');
|
| 678 |
+
modal.style.display = 'none';
|
| 679 |
+
const video = modalContent.querySelector('video');
|
| 680 |
+
if (video) { video.pause(); }
|
| 681 |
+
modalContent.innerHTML = ''; // Clear content
|
|
|
|
|
|
|
|
|
|
| 682 |
}
|
| 683 |
+
// Close modal on clicking background (outside content)
|
| 684 |
+
document.getElementById('mediaModal').addEventListener('click', function(event) {
|
| 685 |
+
if (event.target === this) {
|
| 686 |
+
closeModal();
|
| 687 |
+
}
|
| 688 |
+
});
|
| 689 |
|
| 690 |
+
|
| 691 |
+
// Upload Progress
|
| 692 |
const form = document.getElementById('upload-form');
|
| 693 |
const progressBar = document.getElementById('progress-bar');
|
| 694 |
const progressContainer = document.getElementById('progress-container');
|
| 695 |
const uploadBtn = document.getElementById('upload-btn');
|
| 696 |
+
const fileInput = form.querySelector('input[type="file"]');
|
| 697 |
|
| 698 |
form.addEventListener('submit', function(e) {
|
| 699 |
+
if (!fileInput.files || fileInput.files.length === 0) {
|
| 700 |
+
e.preventDefault(); // Prevent submission
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 701 |
alert('Пожалуйста, выберите файлы для загрузки.');
|
| 702 |
return;
|
| 703 |
}
|
| 704 |
+
if (fileInput.files.length > 20) {
|
| 705 |
+
e.preventDefault();
|
| 706 |
+
alert('Максимум 20 файлов за раз!');
|
| 707 |
+
return;
|
| 708 |
+
}
|
| 709 |
|
| 710 |
+
// Use XHR for progress tracking
|
| 711 |
+
e.preventDefault();
|
| 712 |
const formData = new FormData(form);
|
| 713 |
progressContainer.style.display = 'block';
|
| 714 |
progressBar.style.width = '0%';
|
| 715 |
+
progressBar.textContent = '0%';
|
| 716 |
uploadBtn.disabled = true;
|
| 717 |
+
uploadBtn.textContent = 'Загрузка...';
|
| 718 |
|
| 719 |
const xhr = new XMLHttpRequest();
|
| 720 |
+
xhr.open('POST', '{{ url_for("dashboard") }}', true);
|
| 721 |
|
| 722 |
xhr.upload.onprogress = function(event) {
|
| 723 |
if (event.lengthComputable) {
|
| 724 |
+
const percent = Math.round((event.loaded / event.total) * 100);
|
| 725 |
progressBar.style.width = percent + '%';
|
| 726 |
+
progressBar.textContent = percent + '%';
|
| 727 |
}
|
| 728 |
};
|
| 729 |
|
| 730 |
xhr.onload = function() {
|
| 731 |
uploadBtn.disabled = false;
|
| 732 |
+
uploadBtn.textContent = 'Загрузить';
|
| 733 |
+
// Instead of reload, we should ideally get the updated file list via JSON
|
| 734 |
+
// and update the DOM, but for simplicity, we reload.
|
| 735 |
+
if (xhr.status >= 200 && xhr.status < 300) {
|
| 736 |
+
// Success - Reload to see changes and flash messages
|
| 737 |
+
window.location.reload();
|
| 738 |
} else {
|
| 739 |
+
// Handle server-side errors shown via flash messages after reload,
|
| 740 |
+
// or parse response if it were JSON
|
| 741 |
+
alert('Произошла ошибка на сервере во время загрузки.');
|
| 742 |
+
progressContainer.style.display = 'none'; // Hide progress on error
|
| 743 |
+
}
|
| 744 |
};
|
| 745 |
|
| 746 |
xhr.onerror = function() {
|
| 747 |
+
alert('Ошибка сети при загрузке файлов!');
|
| 748 |
progressContainer.style.display = 'none';
|
| 749 |
progressBar.style.width = '0%';
|
| 750 |
+
progressBar.textContent = '0%';
|
| 751 |
uploadBtn.disabled = false;
|
| 752 |
+
uploadBtn.textContent = 'Загрузить';
|
| 753 |
};
|
| 754 |
|
| 755 |
xhr.send(formData);
|
|
|
|
| 757 |
|
| 758 |
document.getElementById('logout-btn').addEventListener('click', function(e) {
|
| 759 |
e.preventDefault();
|
| 760 |
+
localStorage.removeItem('zeusCredentials'); // Clear saved creds on logout
|
| 761 |
+
window.location.href = '{{ url_for("logout") }}';
|
| 762 |
});
|
| 763 |
</script>
|
| 764 |
</body>
|
| 765 |
+
</html>'''
|
| 766 |
+
return render_template_string(html,
|
| 767 |
+
username=username,
|
| 768 |
+
files_by_folder=files_by_folder,
|
| 769 |
+
sorted_folders=sorted_folders,
|
| 770 |
+
repo_id=REPO_ID,
|
| 771 |
+
HF_TOKEN_READ=HF_TOKEN_READ) # Pass token for JS
|
| 772 |
+
|
| 773 |
+
@app.route('/download/<path:storage_path>/<original_filename>')
|
| 774 |
+
def download_file(storage_path, original_filename):
|
| 775 |
if 'username' not in session:
|
| 776 |
+
return redirect(url_for('login')) # No flash needed, redirect immediately
|
|
|
|
| 777 |
|
| 778 |
username = session['username']
|
| 779 |
+
# Decode the path received from the URL
|
| 780 |
+
storage_path = requests.utils.unquote(storage_path)
|
| 781 |
+
|
| 782 |
+
# Verify user owns the file or is admin (admin check is implicit via referrer check below)
|
| 783 |
data = load_data()
|
| 784 |
+
user_files = data.get('users', {}).get(username, {}).get('files', [])
|
| 785 |
+
is_owner = any(f.get('storage_path') == storage_path for f in user_files)
|
|
|
|
|
|
|
| 786 |
|
| 787 |
+
is_admin_route = request.referrer and 'admhosto' in request.referrer # Basic admin check
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 788 |
|
| 789 |
+
if not is_owner and not is_admin_route: # Must be owner or admin accessing via admin page
|
| 790 |
+
flash('У вас нет доступа к этому файлу!', 'error')
|
| 791 |
+
return redirect(url_for('dashboard'))
|
| 792 |
+
|
| 793 |
+
file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{storage_path}?download=true"
|
| 794 |
+
logging.info(f"Attempting download for {username if is_owner else 'admin'} from: {file_url}")
|
| 795 |
|
|
|
|
| 796 |
try:
|
|
|
|
|
|
|
| 797 |
headers = {}
|
| 798 |
if HF_TOKEN_READ:
|
| 799 |
headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
|
| 800 |
|
| 801 |
+
response = requests.get(file_url, headers=headers, stream=True, timeout=60) # Add timeout
|
| 802 |
+
response.raise_for_status()
|
| 803 |
+
|
| 804 |
+
# Stream download for potentially large files
|
| 805 |
+
file_content = BytesIO(response.content) # Read into memory - consider streaming response directly for very large files
|
| 806 |
+
file_content.seek(0)
|
| 807 |
|
|
|
|
| 808 |
return send_file(
|
| 809 |
file_content,
|
| 810 |
as_attachment=True,
|
| 811 |
+
download_name=original_filename, # Use the original filename
|
| 812 |
+
mimetype='application/octet-stream' # Generic mimetype
|
| 813 |
)
|
| 814 |
except requests.exceptions.RequestException as e:
|
| 815 |
+
logging.error(f"Error downloading file {storage_path} from HF: {e}")
|
| 816 |
+
flash(f'Ошибка скачивания файла "{original_filename}". Файл не найден или ошибка сети.', 'error')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 817 |
except Exception as e:
|
| 818 |
+
logging.error(f"Unexpected error during download of {storage_path}: {e}")
|
| 819 |
+
flash('Произошла непредвиденная ошибка при скачивании файла.', 'error')
|
| 820 |
+
|
| 821 |
+
# Redirect back based on where the request came from
|
| 822 |
+
if is_admin_route:
|
| 823 |
+
# Extract target username from storage path for admin redirect
|
| 824 |
+
parts = storage_path.split('/')
|
| 825 |
+
target_username = parts[1] if len(parts) > 1 else None
|
| 826 |
+
if target_username:
|
| 827 |
+
return redirect(url_for('admin_user_files', username=target_username))
|
| 828 |
+
else:
|
| 829 |
+
return redirect(url_for('admin_panel')) # Fallback
|
| 830 |
+
else:
|
| 831 |
+
return redirect(url_for('dashboard'))
|
| 832 |
|
| 833 |
|
| 834 |
+
@app.route('/delete/<path:storage_path>')
|
| 835 |
+
def delete_file(storage_path):
|
| 836 |
if 'username' not in session:
|
|
|
|
| 837 |
return redirect(url_for('login'))
|
| 838 |
|
| 839 |
username = session['username']
|
| 840 |
+
storage_path = requests.utils.unquote(storage_path) # Decode path
|
| 841 |
+
|
| 842 |
+
if not HF_TOKEN_WRITE:
|
| 843 |
+
flash('Ошибка: Удаление не возможно, отсутствует токен записи Hugging Face.', 'error')
|
| 844 |
+
return redirect(url_for('dashboard'))
|
| 845 |
+
|
| 846 |
data = load_data()
|
| 847 |
+
if username not in data.get('users', {}): # Robust check
|
| 848 |
session.pop('username', None)
|
|
|
|
| 849 |
return redirect(url_for('login'))
|
| 850 |
|
| 851 |
+
user_files = data['users'][username].get('files', [])
|
| 852 |
+
original_filename = "unknown file" # Default
|
| 853 |
+
file_found = False
|
| 854 |
+
for f in user_files:
|
| 855 |
+
if f.get('storage_path') == storage_path:
|
| 856 |
+
original_filename = f.get('original_filename', storage_path)
|
| 857 |
+
file_found = True
|
| 858 |
+
break
|
| 859 |
+
|
| 860 |
+
if not file_found:
|
| 861 |
+
flash('Файл не найден в вашем списке!', 'error')
|
| 862 |
return redirect(url_for('dashboard'))
|
| 863 |
|
| 864 |
+
logging.info(f"User {username} attempting to delete {storage_path} ({original_filename})")
|
| 865 |
+
|
| 866 |
try:
|
| 867 |
api = HfApi()
|
| 868 |
api.delete_file(
|
| 869 |
+
path_in_repo=storage_path,
|
| 870 |
repo_id=REPO_ID,
|
| 871 |
repo_type="dataset",
|
| 872 |
token=HF_TOKEN_WRITE,
|
| 873 |
+
commit_message=f"User {username} deleted {storage_path}"
|
| 874 |
)
|
| 875 |
+
logging.info(f"Successfully deleted file {storage_path} from HF Hub.")
|
| 876 |
+
|
| 877 |
+
# Update local data
|
| 878 |
+
data['users'][username]['files'] = [f for f in user_files if f.get('storage_path') != storage_path]
|
| 879 |
save_data(data)
|
| 880 |
+
flash(f'Файл "{original_filename}" успешно удален!', 'success')
|
| 881 |
+
|
| 882 |
except Exception as e:
|
| 883 |
+
# Check if the error is because the file is already deleted (e.g., 404 on delete)
|
| 884 |
+
# This requires inspecting the specific exception type from huggingface_hub
|
| 885 |
+
logging.error(f"Error deleting file {storage_path} for user {username}: {e}")
|
| 886 |
+
flash(f'Ошибка при удалении файла "{original_filename}" на сервере.', 'error')
|
| 887 |
+
# Should we remove from local DB if deletion fails? Maybe not, allows retry.
|
| 888 |
|
| 889 |
return redirect(url_for('dashboard'))
|
| 890 |
|
| 891 |
+
|
| 892 |
@app.route('/logout')
|
| 893 |
def logout():
|
| 894 |
session.pop('username', None)
|
| 895 |
+
flash('Вы вышли из системы.', 'success')
|
| 896 |
+
# Client-side script on login page handles localStorage clearing
|
| 897 |
return redirect(url_for('login'))
|
| 898 |
|
| 899 |
+
# --- Admin Routes ---
|
| 900 |
+
|
| 901 |
+
# TODO: Add proper admin authentication (e.g., check if session['username'] is in an admin list)
|
| 902 |
+
def is_admin():
|
| 903 |
+
# Placeholder: In a real app, check against a list of admin usernames or roles
|
| 904 |
+
# return session.get('username') == 'admin_user'
|
| 905 |
+
return True # WARNING: Allows anyone to access admin panel for now!
|
| 906 |
+
|
| 907 |
|
| 908 |
@app.route('/admhosto')
|
| 909 |
def admin_panel():
|
| 910 |
+
if not is_admin():
|
| 911 |
+
flash('Доступ запрещен.', 'error')
|
| 912 |
+
return redirect(url_for('login'))
|
| 913 |
+
|
| 914 |
data = load_data()
|
| 915 |
+
users = data.get('users', {})
|
| 916 |
+
|
| 917 |
+
# Calculate total files and maybe size if needed (size requires querying HF)
|
| 918 |
+
user_stats = {}
|
| 919 |
+
for uname, udata in users.items():
|
| 920 |
+
user_stats[uname] = {
|
| 921 |
+
'file_count': len(udata.get('files', [])),
|
| 922 |
+
'created_at': udata.get('created_at', 'N/A')
|
| 923 |
+
}
|
| 924 |
+
|
| 925 |
|
| 926 |
html = '''
|
| 927 |
+
<!DOCTYPE html><html lang="ru"><head>
|
| 928 |
+
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
|
|
|
|
|
|
|
|
| 929 |
<title>Админ-панель - Zeus Cloud</title>
|
| 930 |
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 931 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
|
| 932 |
<style>''' + BASE_STYLE + '''</style>
|
| 933 |
+
</head><body>
|
| 934 |
+
<div class="container">
|
| 935 |
+
<h1>Админ-панель Zeus Cloud</h1>
|
| 936 |
+
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 937 |
+
{% if messages %}
|
| 938 |
+
{% for category, message in messages %}
|
| 939 |
+
<div class="flash {{ category }}">{{ message }}</div>
|
| 940 |
+
{% endfor %}
|
| 941 |
+
{% endif %}
|
| 942 |
+
{% endwith %}
|
| 943 |
+
<h2>Список пользователей</h2>
|
| 944 |
+
<div class="user-list">
|
| 945 |
+
{% for username, stats in user_stats.items() %}
|
| 946 |
+
<div class="user-item">
|
| 947 |
+
<div>
|
| 948 |
+
<a href="{{ url_for('admin_user_files', username=username) }}"><i class="fas fa-user"></i> {{ username }}</a>
|
| 949 |
+
<span style="margin-left: 15px;">Файлов: {{ stats.file_count }}</span>
|
| 950 |
+
<span style="margin-left: 15px;">Создан: {{ stats.created_at }}</span>
|
| 951 |
+
</div>
|
| 952 |
+
<form method="POST" action="{{ url_for('admin_delete_user', username=username) }}" style="display: inline;" onsubmit="return confirm('ВНИМАНИЕ! Удалить пользователя {{ username }} и ВСЕ его файлы? Это действие НЕОБРАТИМО!');">
|
| 953 |
+
<button type="submit" class="btn delete-btn" style="padding: 5px 10px; font-size: 0.9em;"><i class="fas fa-user-slash"></i> Удалить</button>
|
| 954 |
+
</form>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 955 |
</div>
|
| 956 |
+
{% else %}
|
| 957 |
+
<p>Пользователей пока нет.</p>
|
| 958 |
+
{% endfor %}
|
| 959 |
</div>
|
| 960 |
+
</div>
|
| 961 |
+
</body></html>
|
| 962 |
'''
|
| 963 |
+
return render_template_string(html, user_stats=user_stats)
|
| 964 |
+
|
| 965 |
|
| 966 |
@app.route('/admhosto/user/<username>')
|
| 967 |
def admin_user_files(username):
|
| 968 |
+
if not is_admin():
|
| 969 |
+
flash('Доступ запрещен.', 'error')
|
| 970 |
+
return redirect(url_for('login'))
|
| 971 |
+
|
| 972 |
data = load_data()
|
| 973 |
+
if username not in data.get('users', {}):
|
| 974 |
+
flash(f'Пользователь "{username}" не найден!', 'error')
|
| 975 |
return redirect(url_for('admin_panel'))
|
| 976 |
|
| 977 |
user_files = sorted(data['users'][username].get('files', []), key=lambda x: x.get('upload_date', ''), reverse=True)
|
| 978 |
|
| 979 |
+
# Group files by folder for admin view as well
|
| 980 |
+
files_by_folder_admin = {'': []}
|
| 981 |
+
for file in user_files:
|
| 982 |
+
display_path = file.get('display_path', file.get('original_filename', 'unknown'))
|
| 983 |
+
folder = ''
|
| 984 |
+
if '/' in display_path:
|
| 985 |
+
folder = display_path.rsplit('/', 1)[0]
|
| 986 |
+
if folder not in files_by_folder_admin:
|
| 987 |
+
files_by_folder_admin[folder] = []
|
| 988 |
+
files_by_folder_admin[folder].append(file)
|
| 989 |
+
|
| 990 |
+
sorted_folders_admin = sorted(files_by_folder_admin.keys(), key=lambda x: (x != '', x))
|
| 991 |
+
|
| 992 |
+
|
| 993 |
html = '''
|
| 994 |
+
<!DOCTYPE html><html lang="ru"><head>
|
| 995 |
+
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
|
|
|
|
|
|
|
|
| 996 |
<title>Файлы пользователя {{ username }} - Zeus Cloud</title>
|
| 997 |
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 998 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
|
| 999 |
<style>''' + BASE_STYLE + '''</style>
|
| 1000 |
+
</head><body>
|
| 1001 |
+
<div class="container">
|
| 1002 |
+
<h1>Файлы пользователя: {{ username }}</h1>
|
| 1003 |
+
<a href="{{ url_for('admin_panel') }}" class="btn" style="margin-bottom: 20px; background-color: var(--accent);"><i class="fas fa-arrow-left"></i> Назад к пользователям</a>
|
| 1004 |
+
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 1005 |
+
{% if messages %}
|
| 1006 |
+
{% for category, message in messages %}
|
| 1007 |
+
<div class="flash {{ category }}">{{ message }}</div>
|
| 1008 |
+
{% endfor %}
|
| 1009 |
+
{% endif %}
|
| 1010 |
+
{% endwith %}
|
| 1011 |
+
|
| 1012 |
+
{% if not files_by_folder_admin or (len(files_by_folder_admin) == 1 and not files_by_folder_admin['']) %}
|
| 1013 |
+
<p>У этого пользователя нет файлов.</p>
|
| 1014 |
+
{% else %}
|
| 1015 |
+
{% for folder_name in sorted_folders_admin %}
|
| 1016 |
+
<div class="folder-section">
|
| 1017 |
+
<h3 class="folder-title">
|
| 1018 |
+
{% if folder_name == '' %}
|
| 1019 |
+
<i class="fas fa-folder"></i> Корень
|
| 1020 |
{% else %}
|
| 1021 |
+
<i class="fas fa-folder"></i> {{ folder_name }}
|
| 1022 |
{% endif %}
|
| 1023 |
+
</h3>
|
| 1024 |
+
<div class="file-grid">
|
| 1025 |
+
{% for file in files_by_folder_admin[folder_name] %}
|
| 1026 |
+
<div class="file-item">
|
| 1027 |
+
<div class="file-preview-container" onclick="openModalAdmin('{{ file.storage_path | urlencode }}', '{{ file.type }}')">
|
| 1028 |
+
{% set preview_url_admin = "https://huggingface.co/datasets/" + repo_id + "/resolve/main/" + file.storage_path %}
|
| 1029 |
+
{% if file.type == 'video' %}
|
| 1030 |
+
<video class="file-preview" preload="metadata" muted><source src="{{ preview_url_admin }}" type="video/mp4"></video>
|
| 1031 |
+
{% elif file.type == 'image' %}
|
| 1032 |
+
<img class="file-preview" src="{{ preview_url_admin }}" alt="{{ file.original_filename }}" loading="lazy">
|
| 1033 |
+
{% elif file.type == 'pdf' %}
|
| 1034 |
+
<i class="fas fa-file-pdf file-icon" style="color: #e74c3c;"></i>
|
| 1035 |
+
{% elif file.type == 'text' %}
|
| 1036 |
+
<i class="fas fa-file-alt file-icon" style="color: #3498db;"></i>
|
| 1037 |
+
{% else %}
|
| 1038 |
+
<i class="fas fa-file file-icon" style="color: #95a5a6;"></i>
|
| 1039 |
+
{% endif %}
|
| 1040 |
+
</div>
|
| 1041 |
+
<div class="file-info">
|
| 1042 |
+
<p class="filename" title="{{ file.original_filename }}">{{ file.original_filename[:25] }}{{ '...' if file.original_filename|length > 25 else '' }}</p>
|
| 1043 |
+
<p class="date">{{ file.upload_date }}</p>
|
| 1044 |
+
<div class="actions">
|
| 1045 |
+
<a href="{{ url_for('download_file', storage_path=file.storage_path | urlencode, original_filename=file.original_filename) }}" class="btn download-btn" title="Скачать"><i class="fas fa-download"></i></a>
|
| 1046 |
+
<form method="POST" action="{{ url_for('admin_delete_file', username=username, storage_path=file.storage_path | urlencode) }}" style="display: inline;" onsubmit="return confirm('Удалить этот файл?');">
|
| 1047 |
+
<button type="submit" class="btn delete-btn" title="Удалить"><i class="fas fa-trash"></i></button>
|
| 1048 |
+
</form>
|
| 1049 |
+
</div>
|
| 1050 |
+
</div>
|
| 1051 |
+
</div>
|
| 1052 |
+
{% endfor %}
|
| 1053 |
</div>
|
| 1054 |
+
</div>
|
| 1055 |
+
{% endfor %}
|
| 1056 |
+
{% endif %}
|
| 1057 |
+
</div>
|
| 1058 |
+
|
| 1059 |
+
<div class="modal" id="mediaModalAdmin">
|
| 1060 |
+
<button class="modal-close" onclick="closeModalAdmin()">×</button>
|
| 1061 |
+
<div class="modal-content" id="modalContentWrapperAdmin">
|
| 1062 |
+
<div id="modalContentAdmin"></div>
|
| 1063 |
+
</div>
|
| 1064 |
+
</div>
|
| 1065 |
+
|
| 1066 |
+
<script>
|
| 1067 |
+
// Replicate modal logic specifically for admin page to avoid conflicts if needed, or reuse if safe
|
| 1068 |
+
const repoIdAdmin = "{{ repo_id }}";
|
| 1069 |
+
const hfTokenReadAdmin = "{{ HF_TOKEN_READ or '' }}";
|
| 1070 |
+
|
| 1071 |
+
function escapeHtmlAdmin(unsafe) { return unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'"); }
|
| 1072 |
+
|
| 1073 |
+
function openModalAdmin(encodedStoragePath, fileType) {
|
| 1074 |
+
const storagePath = decodeURIComponent(encodedStoragePath);
|
| 1075 |
+
const modal = document.getElementById('mediaModalAdmin');
|
| 1076 |
+
const modalContent = document.getElementById('modalContentAdmin');
|
| 1077 |
+
modalContent.innerHTML = '<p style="text-align:center; color:white; padding:20px;">Загрузка...</p>';
|
| 1078 |
+
modal.style.display = 'flex';
|
| 1079 |
+
|
| 1080 |
+
const fileUrl = `https://huggingface.co/datasets/${repoIdAdmin}/resolve/main/${storagePath}`;
|
| 1081 |
+
const downloadUrl = `${fileUrl}?download=true`;
|
| 1082 |
+
const headers = {};
|
| 1083 |
+
if (hfTokenReadAdmin) { headers['Authorization'] = `Bearer ${hfTokenReadAdmin}`; }
|
| 1084 |
+
|
| 1085 |
+
if (fileType === 'image') { modalContent.innerHTML = `<img src="${fileUrl}" alt="Предпросмотр">`; }
|
| 1086 |
+
else if (fileType === 'video') { modalContent.innerHTML = `<video controls autoplay><source src="${fileUrl}" type="video/mp4"></video>`; }
|
| 1087 |
+
else if (fileType === 'pdf') { modalContent.innerHTML = `<iframe src="${fileUrl}" width="100%" height="calc(95vh - 50px)"></iframe>`; }
|
| 1088 |
+
else if (fileType === 'text') {
|
| 1089 |
+
fetch(downloadUrl, { headers: headers })
|
| 1090 |
+
.then(response => { if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); return response.text(); })
|
| 1091 |
+
.then(text => { modalContent.innerHTML = `<pre>${escapeHtmlAdmin(text)}</pre>`; })
|
| 1092 |
+
.catch(err => { console.error("Error fetching text:", err); modalContent.innerHTML = '<p style="color:red;text-align:center;">Ошибка загрузки текста.</p>'; });
|
| 1093 |
+
} else { modalContent.innerHTML = '<p style="color:white;text-align:center;">Предпросмотр недоступен.</p>'; }
|
| 1094 |
+
}
|
| 1095 |
+
function closeModalAdmin() {
|
| 1096 |
+
const modal = document.getElementById('mediaModalAdmin');
|
| 1097 |
+
const modalContent = document.getElementById('modalContentAdmin');
|
| 1098 |
+
modal.style.display = 'none';
|
| 1099 |
+
const video = modalContent.querySelector('video');
|
| 1100 |
+
if (video) { video.pause(); }
|
| 1101 |
+
modalContent.innerHTML = '';
|
| 1102 |
+
}
|
| 1103 |
+
document.getElementById('mediaModalAdmin').addEventListener('click', function(event) { if (event.target === this) { closeModalAdmin(); } });
|
| 1104 |
+
</script>
|
| 1105 |
+
|
| 1106 |
+
</body></html>
|
| 1107 |
'''
|
| 1108 |
+
return render_template_string(html,
|
| 1109 |
+
username=username,
|
| 1110 |
+
files_by_folder_admin=files_by_folder_admin,
|
| 1111 |
+
sorted_folders_admin=sorted_folders_admin,
|
| 1112 |
+
repo_id=REPO_ID,
|
| 1113 |
+
HF_TOKEN_READ=HF_TOKEN_READ)
|
| 1114 |
|
| 1115 |
|
| 1116 |
@app.route('/admhosto/delete_user/<username>', methods=['POST'])
|
| 1117 |
def admin_delete_user(username):
|
| 1118 |
+
if not is_admin():
|
| 1119 |
+
flash('Доступ запрещен.', 'error')
|
| 1120 |
+
return redirect(url_for('login'))
|
| 1121 |
+
|
| 1122 |
+
if not HF_TOKEN_WRITE:
|
| 1123 |
+
flash('Ошибка: Удаление не возможно, отсутствует токен записи Hugging Face.', 'error')
|
| 1124 |
+
return redirect(url_for('admin_panel'))
|
| 1125 |
+
|
| 1126 |
data = load_data()
|
| 1127 |
+
if username not in data.get('users', {}):
|
| 1128 |
+
flash(f'Пользователь "{username}" не найден!', 'error')
|
| 1129 |
return redirect(url_for('admin_panel'))
|
| 1130 |
|
| 1131 |
+
logging.warning(f"Admin attempting to delete user {username} and all their files.")
|
| 1132 |
|
| 1133 |
try:
|
| 1134 |
api = HfApi()
|
| 1135 |
+
user_folder_path = f"cloud_files/{username}"
|
| 1136 |
+
|
| 1137 |
+
# Attempt to delete the entire user folder on Hugging Face Hub
|
| 1138 |
+
try:
|
| 1139 |
+
# List files first to see if folder exists/has content (delete_folder might fail on empty)
|
| 1140 |
+
# Or just try deleting - may need more robust error handling based on hf_hub exceptions
|
| 1141 |
+
logging.info(f"Attempting to delete folder: {user_folder_path} in repo {REPO_ID}")
|
| 1142 |
+
api.delete_folder(
|
| 1143 |
+
folder_path=user_folder_path,
|
| 1144 |
+
repo_id=REPO_ID,
|
| 1145 |
+
repo_type="dataset",
|
| 1146 |
+
token=HF_TOKEN_WRITE,
|
| 1147 |
+
commit_message=f"Admin deleted folder for user {username}"
|
| 1148 |
+
)
|
| 1149 |
+
logging.info(f"Successfully deleted HF folder {user_folder_path}")
|
| 1150 |
+
except Exception as folder_delete_error:
|
| 1151 |
+
# Catch specific 'not found' or handle generic error
|
| 1152 |
+
logging.warning(f"Could not delete folder {user_folder_path} directly (maybe empty or already gone?): {folder_delete_error}")
|
| 1153 |
+
# If folder deletion fails, we might still want to remove the user from DB
|
| 1154 |
+
# Optionally, try deleting individual files listed in DB as a fallback (more complex)
|
| 1155 |
+
user_files_in_db = data['users'][username].get('files', [])
|
| 1156 |
+
if user_files_in_db:
|
| 1157 |
+
logging.info(f"Attempting individual file deletion for {username} as folder deletion failed.")
|
| 1158 |
+
deleted_count = 0
|
| 1159 |
+
failed_count = 0
|
| 1160 |
+
for file_info in user_files_in_db:
|
| 1161 |
+
storage_path = file_info.get('storage_path')
|
| 1162 |
+
if storage_path:
|
| 1163 |
+
try:
|
| 1164 |
+
api.delete_file(
|
| 1165 |
+
path_in_repo=storage_path,
|
| 1166 |
+
repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE
|
| 1167 |
+
)
|
| 1168 |
+
deleted_count += 1
|
| 1169 |
+
except Exception as file_del_err:
|
| 1170 |
+
failed_count += 1
|
| 1171 |
+
logging.error(f"Error deleting file {storage_path} during user cleanup: {file_del_err}")
|
| 1172 |
+
logging.info(f"Individual file deletion for {username}: {deleted_count} deleted, {failed_count} failed.")
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
# Regardless of HF deletion success/failure, remove user from local database
|
| 1176 |
del data['users'][username]
|
| 1177 |
save_data(data)
|
| 1178 |
+
flash(f'Пользователь {username} удален из базы данных. Файлы на сервере удалены (или попытка удаления произведена).', 'success')
|
| 1179 |
+
logging.info(f"Admin removed user {username} from database.")
|
| 1180 |
|
| 1181 |
except Exception as e:
|
| 1182 |
+
logging.error(f"Critical error during admin deletion of user {username}: {e}")
|
| 1183 |
+
flash(f'Ошибка при удалении пользователя {username}. Проверьте логи.', 'error')
|
| 1184 |
|
| 1185 |
return redirect(url_for('admin_panel'))
|
| 1186 |
|
| 1187 |
|
| 1188 |
+
@app.route('/admhosto/delete_file/<username>/<path:storage_path>', methods=['POST'])
|
| 1189 |
+
def admin_delete_file(username, storage_path):
|
| 1190 |
+
if not is_admin():
|
| 1191 |
+
flash('Доступ запрещен.', 'error')
|
| 1192 |
+
return redirect(url_for('login'))
|
| 1193 |
+
|
| 1194 |
+
storage_path = requests.utils.unquote(storage_path) # Decode path
|
| 1195 |
+
|
| 1196 |
+
if not HF_TOKEN_WRITE:
|
| 1197 |
+
flash('Ошибка: Удаление не возможно, отсутствует токен записи Hugging Face.', 'error')
|
| 1198 |
+
return redirect(url_for('admin_user_files', username=username))
|
| 1199 |
+
|
| 1200 |
+
data = load_data()
|
| 1201 |
+
if username not in data.get('users', {}):
|
| 1202 |
+
flash(f'Пользователь "{username}" не найден!', 'error')
|
| 1203 |
+
return redirect(url_for('admin_panel')) # Redirect to main admin panel if user not found
|
| 1204 |
+
|
| 1205 |
+
user_files = data['users'][username].get('files', [])
|
| 1206 |
+
original_filename = "unknown file"
|
| 1207 |
+
file_exists_in_db = False
|
| 1208 |
+
for f in user_files:
|
| 1209 |
+
if f.get('storage_path') == storage_path:
|
| 1210 |
+
original_filename = f.get('original_filename', storage_path)
|
| 1211 |
+
file_exists_in_db = True
|
| 1212 |
+
break
|
| 1213 |
|
| 1214 |
+
logging.info(f"Admin attempting to delete file {storage_path} ({original_filename}) for user {username}")
|
|
|
|
| 1215 |
|
| 1216 |
+
try:
|
| 1217 |
+
api = HfApi()
|
| 1218 |
+
api.delete_file(
|
| 1219 |
+
path_in_repo=storage_path,
|
| 1220 |
+
repo_id=REPO_ID,
|
| 1221 |
+
repo_type="dataset",
|
| 1222 |
+
token=HF_TOKEN_WRITE,
|
| 1223 |
+
commit_message=f"Admin deleted file {storage_path} for user {username}"
|
| 1224 |
+
)
|
| 1225 |
+
logging.info(f"Admin successfully deleted file {storage_path} from HF Hub.")
|
| 1226 |
+
flash(f'Файл "{original_filename}" успешно удален с сервера.', 'success')
|
| 1227 |
|
| 1228 |
+
# Remove from DB only if it exists there
|
| 1229 |
+
if file_exists_in_db:
|
| 1230 |
+
data['users'][username]['files'] = [f for f in user_files if f.get('storage_path') != storage_path]
|
| 1231 |
+
save_data(data)
|
| 1232 |
+
logging.info(f"Removed file {storage_path} from DB for user {username}")
|
| 1233 |
+
else:
|
| 1234 |
+
logging.warning(f"File {storage_path} was deleted from HF by admin, but was not found in the local DB for user {username}.")
|
| 1235 |
+
flash('Файл удален с сервера, но отсутствовал в локальной базе данных (возможна рассинхронизация).', 'warning')
|
|
|
|
| 1236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1237 |
|
| 1238 |
+
except Exception as e:
|
| 1239 |
+
# Handle specific exceptions, e.g., file not found on HF (already deleted?)
|
| 1240 |
+
logging.error(f"Error deleting file {storage_path} by admin for user {username}: {e}")
|
| 1241 |
+
flash(f'Ошибка при удалении файла "{original_filename}" на сервере.', 'error')
|
| 1242 |
|
| 1243 |
+
return redirect(url_for('admin_user_files', username=username))
|
| 1244 |
|
| 1245 |
+
# --- Main Execution ---
|
| 1246 |
+
from datetime import timedelta
|
| 1247 |
|
| 1248 |
if __name__ == '__main__':
|
|
|
|
| 1249 |
if not HF_TOKEN_WRITE:
|
| 1250 |
+
logging.warning("!!! HF_TOKEN (write access) is NOT set. File uploads, deletions, and DB backups will FAIL. !!!")
|
| 1251 |
if not HF_TOKEN_READ:
|
| 1252 |
+
logging.warning("HF_TOKEN_READ is not set. Falling back to HF_TOKEN. File downloads/previews might fail for private repos if HF_TOKEN is also not set.")
|
| 1253 |
|
|
|
|
|
|
|
| 1254 |
if HF_TOKEN_WRITE:
|
| 1255 |
+
# Initial backup on startup? Maybe wait a bit.
|
| 1256 |
+
# Download first to ensure we have the latest state before potentially backing up stale data
|
| 1257 |
+
load_data() # Trigger initial download/load
|
| 1258 |
+
# Start backup thread
|
| 1259 |
+
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
|
| 1260 |
+
backup_thread.start()
|
| 1261 |
+
logging.info("Periodic backup thread started.")
|
| 1262 |
else:
|
| 1263 |
+
logging.warning("Periodic backup disabled because HF Write Token is not set.")
|
| 1264 |
+
|
| 1265 |
+
# Set session lifetime
|
| 1266 |
+
app.permanent_session_lifetime = timedelta(days=30)
|
| 1267 |
|
| 1268 |
+
# Consider using Waitress or Gunicorn instead of Flask dev server for production
|
| 1269 |
+
app.run(debug=False, host='0.0.0.0', port=7860)
|