Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 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
|
|
@@ -13,7 +14,7 @@ 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")
|
|
@@ -29,14 +30,14 @@ def load_data():
|
|
| 29 |
with open(DATA_FILE, 'r', encoding='utf-8') as file:
|
| 30 |
data = json.load(file)
|
| 31 |
if not isinstance(data, dict):
|
| 32 |
-
logging.warning("
|
| 33 |
return {'users': {}, 'files': {}}
|
| 34 |
data.setdefault('users', {})
|
| 35 |
data.setdefault('files', {})
|
| 36 |
-
logging.info("
|
| 37 |
return data
|
| 38 |
except Exception as e:
|
| 39 |
-
logging.error(f"
|
| 40 |
return {'users': {}, 'files': {}}
|
| 41 |
|
| 42 |
def save_data(data):
|
|
@@ -45,15 +46,12 @@ def save_data(data):
|
|
| 45 |
json.dump(data, file, ensure_ascii=False, indent=4)
|
| 46 |
upload_db_to_hf()
|
| 47 |
cache.clear()
|
| 48 |
-
logging.info("
|
| 49 |
except Exception as e:
|
| 50 |
-
logging.error(f"
|
| 51 |
raise
|
| 52 |
|
| 53 |
def upload_db_to_hf():
|
| 54 |
-
if not HF_TOKEN_WRITE:
|
| 55 |
-
logging.warning("HF_TOKEN (write) не установлен. Пропуск загрузки на Hugging Face.")
|
| 56 |
-
return
|
| 57 |
try:
|
| 58 |
api = HfApi()
|
| 59 |
api.upload_file(
|
|
@@ -62,19 +60,13 @@ def upload_db_to_hf():
|
|
| 62 |
repo_id=REPO_ID,
|
| 63 |
repo_type="dataset",
|
| 64 |
token=HF_TOKEN_WRITE,
|
| 65 |
-
commit_message=f"
|
| 66 |
)
|
| 67 |
-
logging.info("
|
| 68 |
except Exception as e:
|
| 69 |
-
logging.error(f"
|
| 70 |
|
| 71 |
def download_db_from_hf():
|
| 72 |
-
if not HF_TOKEN_READ:
|
| 73 |
-
logging.warning("HF_TOKEN_READ не установлен. Пропуск загрузки с Hugging Face.")
|
| 74 |
-
if not os.path.exists(DATA_FILE):
|
| 75 |
-
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 76 |
-
json.dump({'users': {}, 'files': {}}, f)
|
| 77 |
-
return
|
| 78 |
try:
|
| 79 |
hf_hub_download(
|
| 80 |
repo_id=REPO_ID,
|
|
@@ -84,396 +76,211 @@ def download_db_from_hf():
|
|
| 84 |
local_dir=".",
|
| 85 |
local_dir_use_symlinks=False
|
| 86 |
)
|
| 87 |
-
logging.info("
|
| 88 |
except Exception as e:
|
| 89 |
-
logging.error(f"
|
| 90 |
if not os.path.exists(DATA_FILE):
|
| 91 |
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 92 |
json.dump({'users': {}, 'files': {}}, f)
|
| 93 |
-
logging.info("Создан пустой файл базы данных.")
|
| 94 |
-
|
| 95 |
|
| 96 |
def periodic_backup():
|
| 97 |
while True:
|
|
|
|
| 98 |
time.sleep(1800)
|
| 99 |
-
logging.info("Запуск периодического резервного копирования...")
|
| 100 |
-
try:
|
| 101 |
-
data = load_data()
|
| 102 |
-
save_data(data)
|
| 103 |
-
except Exception as e:
|
| 104 |
-
logging.error(f"Ошибка во время периодического резервного копирования: {e}")
|
| 105 |
-
|
| 106 |
|
| 107 |
def get_file_type(filename):
|
| 108 |
-
video_extensions = ('.mp4', '.mov', '.avi'
|
| 109 |
-
image_extensions = ('.jpg', '.jpeg', '.png', '.gif'
|
| 110 |
-
|
| 111 |
-
if filename_lower.endswith(video_extensions):
|
| 112 |
return 'video'
|
| 113 |
-
elif
|
| 114 |
return 'image'
|
| 115 |
return 'other'
|
| 116 |
|
| 117 |
BASE_STYLE = '''
|
| 118 |
-
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600;700&display=swap');
|
| 119 |
-
|
| 120 |
:root {
|
| 121 |
-
--primary: #
|
| 122 |
-
--secondary: #
|
| 123 |
-
--accent: #
|
| 124 |
-
--background-light: #
|
| 125 |
-
--background-dark: #
|
| 126 |
-
--card-bg:
|
| 127 |
-
--card-bg-dark:
|
| 128 |
-
--text-light: #
|
| 129 |
-
--text-dark: #
|
| 130 |
-
--shadow: 0
|
| 131 |
-
--
|
| 132 |
-
--
|
| 133 |
-
--
|
| 134 |
-
--transition: all 0.35s cubic-bezier(0.25, 0.8, 0.25, 1);
|
| 135 |
-
--delete-color: #ff4d4f; /* Ant Design Red */
|
| 136 |
-
--border-radius-main: 16px;
|
| 137 |
-
--border-radius-small: 12px;
|
| 138 |
}
|
| 139 |
-
|
| 140 |
* { margin: 0; padding: 0; box-sizing: border-box; }
|
| 141 |
-
|
| 142 |
body {
|
| 143 |
-
font-family: '
|
| 144 |
-
background:
|
| 145 |
color: var(--text-light);
|
| 146 |
-
line-height: 1.
|
| 147 |
-
transition: background 0.3s, color 0.3s;
|
| 148 |
}
|
| 149 |
-
|
| 150 |
body.dark {
|
| 151 |
-
background:
|
| 152 |
color: var(--text-dark);
|
| 153 |
}
|
| 154 |
-
|
| 155 |
.container {
|
| 156 |
-
margin:
|
| 157 |
-
max-width:
|
| 158 |
-
padding:
|
| 159 |
background: var(--card-bg);
|
| 160 |
-
border-radius:
|
| 161 |
box-shadow: var(--shadow);
|
| 162 |
-
transition: var(--transition);
|
| 163 |
-
border: 1px solid rgba(0, 0, 0, 0.05);
|
| 164 |
}
|
| 165 |
-
|
| 166 |
body.dark .container {
|
| 167 |
background: var(--card-bg-dark);
|
| 168 |
-
box-shadow: var(--shadow-dark);
|
| 169 |
-
border: 1px solid rgba(255, 255, 255, 0.1);
|
| 170 |
}
|
| 171 |
-
|
| 172 |
h1 {
|
| 173 |
-
font-size:
|
| 174 |
-
font-weight:
|
| 175 |
text-align: center;
|
| 176 |
-
margin-bottom:
|
| 177 |
-
background: linear-gradient(135deg, var(--primary), var(--
|
| 178 |
-webkit-background-clip: text;
|
| 179 |
color: transparent;
|
| 180 |
-
padding-bottom: 10px; /* Space for slogan */
|
| 181 |
}
|
| 182 |
-
|
| 183 |
h2 {
|
| 184 |
-
font-size: 1.
|
| 185 |
-
margin-top:
|
| 186 |
-
margin-bottom: 15px;
|
| 187 |
color: var(--text-light);
|
| 188 |
-
font-weight: 600;
|
| 189 |
-
border-bottom: 2px solid var(--primary);
|
| 190 |
-
padding-bottom: 8px;
|
| 191 |
-
display: inline-block;
|
| 192 |
}
|
| 193 |
-
|
| 194 |
body.dark h2 {
|
| 195 |
color: var(--text-dark);
|
| 196 |
-
border-bottom-color: var(--secondary);
|
| 197 |
-
}
|
| 198 |
-
|
| 199 |
-
.slogan {
|
| 200 |
-
text-align: center;
|
| 201 |
-
margin-top: -15px; /* Position under h1 */
|
| 202 |
-
margin-bottom: 30px;
|
| 203 |
-
font-style: italic;
|
| 204 |
-
opacity: 0.7;
|
| 205 |
-
font-weight: 400;
|
| 206 |
-
font-size: 1.1em;
|
| 207 |
-
color: var(--primary);
|
| 208 |
}
|
| 209 |
-
body.dark .slogan {
|
| 210 |
-
color: var(--secondary);
|
| 211 |
-
opacity: 0.8;
|
| 212 |
-
}
|
| 213 |
-
|
| 214 |
-
|
| 215 |
input, textarea {
|
| 216 |
width: 100%;
|
| 217 |
-
padding:
|
| 218 |
-
margin:
|
| 219 |
-
border:
|
| 220 |
-
border-radius:
|
| 221 |
background: var(--glass-bg);
|
| 222 |
color: var(--text-light);
|
| 223 |
font-size: 1.1em;
|
| 224 |
-
|
| 225 |
-
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.06);
|
| 226 |
}
|
| 227 |
-
|
| 228 |
body.dark input, body.dark textarea {
|
| 229 |
color: var(--text-dark);
|
| 230 |
-
background: var(--glass-bg-dark);
|
| 231 |
-
border-color: #444;
|
| 232 |
-
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15);
|
| 233 |
}
|
| 234 |
-
|
| 235 |
input:focus, textarea:focus {
|
| 236 |
outline: none;
|
| 237 |
-
|
| 238 |
-
box-shadow: 0 0 0 3px rgba(106, 17, 203, 0.2); /* Focus ring */
|
| 239 |
}
|
| 240 |
-
|
| 241 |
-
body.dark input:focus, body.dark textarea:focus {
|
| 242 |
-
border-color: var(--secondary);
|
| 243 |
-
box-shadow: 0 0 0 3px rgba(37, 117, 252, 0.25);
|
| 244 |
-
}
|
| 245 |
-
|
| 246 |
.btn {
|
| 247 |
-
padding:
|
| 248 |
-
background:
|
| 249 |
color: white;
|
| 250 |
border: none;
|
| 251 |
-
border-radius:
|
| 252 |
cursor: pointer;
|
| 253 |
-
font-size: 1.
|
| 254 |
font-weight: 600;
|
| 255 |
transition: var(--transition);
|
| 256 |
-
box-shadow:
|
| 257 |
display: inline-block;
|
| 258 |
text-decoration: none;
|
| 259 |
-
text-align: center;
|
| 260 |
-
margin-right: 10px; /* Spacing between buttons */
|
| 261 |
-
margin-bottom: 10px;
|
| 262 |
}
|
| 263 |
-
|
| 264 |
.btn:hover {
|
| 265 |
-
transform:
|
| 266 |
-
|
| 267 |
-
filter: brightness(1.1);
|
| 268 |
}
|
| 269 |
-
|
| 270 |
.download-btn {
|
| 271 |
-
background:
|
|
|
|
| 272 |
}
|
| 273 |
.download-btn:hover {
|
| 274 |
-
|
| 275 |
}
|
| 276 |
-
|
| 277 |
.delete-btn {
|
| 278 |
-
background:
|
|
|
|
| 279 |
}
|
| 280 |
.delete-btn:hover {
|
| 281 |
-
|
| 282 |
}
|
| 283 |
-
|
| 284 |
.flash {
|
| 285 |
-
padding: 15px 20px;
|
| 286 |
-
margin-bottom: 20px;
|
| 287 |
-
border-radius: var(--border-radius-small);
|
| 288 |
-
text-align: center;
|
| 289 |
-
font-weight: 600;
|
| 290 |
-
background-color: rgba(37, 117, 252, 0.1); /* Light blue bg */
|
| 291 |
color: var(--secondary);
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
body.dark .flash {
|
| 295 |
-
background-color: rgba(37, 117, 252, 0.2);
|
| 296 |
-
border-color: rgba(37, 117, 252, 0.5);
|
| 297 |
-
}
|
| 298 |
-
.flash.error {
|
| 299 |
-
background-color: rgba(255, 77, 79, 0.1);
|
| 300 |
-
color: var(--delete-color);
|
| 301 |
-
border-color: rgba(255, 77, 79, 0.3);
|
| 302 |
-
}
|
| 303 |
-
body.dark .flash.error {
|
| 304 |
-
background-color: rgba(255, 77, 79, 0.2);
|
| 305 |
-
border-color: rgba(255, 77, 79, 0.5);
|
| 306 |
}
|
| 307 |
-
|
| 308 |
-
|
| 309 |
.file-grid {
|
| 310 |
display: grid;
|
| 311 |
-
grid-template-columns: repeat(auto-fill, minmax(
|
| 312 |
-
gap:
|
| 313 |
-
margin-top:
|
| 314 |
}
|
| 315 |
-
|
| 316 |
.user-list {
|
| 317 |
-
margin-top:
|
| 318 |
-
display: grid;
|
| 319 |
-
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
| 320 |
-
gap: 20px;
|
| 321 |
}
|
| 322 |
-
|
| 323 |
.user-item {
|
| 324 |
-
padding:
|
| 325 |
background: var(--card-bg);
|
| 326 |
-
border-radius:
|
| 327 |
margin-bottom: 10px;
|
| 328 |
box-shadow: var(--shadow);
|
| 329 |
transition: var(--transition);
|
| 330 |
-
border-left: 5px solid var(--primary);
|
| 331 |
}
|
| 332 |
-
|
| 333 |
body.dark .user-item {
|
| 334 |
background: var(--card-bg-dark);
|
| 335 |
-
box-shadow: var(--shadow-dark);
|
| 336 |
-
border-left-color: var(--secondary);
|
| 337 |
}
|
| 338 |
-
|
| 339 |
.user-item:hover {
|
| 340 |
-
transform: translateY(-5px)
|
| 341 |
-
box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
|
| 342 |
-
}
|
| 343 |
-
body.dark .user-item:hover {
|
| 344 |
-
box-shadow: 0 15px 30px rgba(0, 0, 0, 0.35);
|
| 345 |
}
|
| 346 |
-
|
| 347 |
-
|
| 348 |
.user-item a {
|
| 349 |
color: var(--primary);
|
| 350 |
text-decoration: none;
|
| 351 |
-
font-weight:
|
| 352 |
-
font-size: 1.2em;
|
| 353 |
-
display: block;
|
| 354 |
-
margin-bottom: 8px;
|
| 355 |
-
}
|
| 356 |
-
body.dark .user-item a {
|
| 357 |
-
color: var(--secondary);
|
| 358 |
}
|
| 359 |
-
|
| 360 |
.user-item a:hover {
|
| 361 |
-
|
| 362 |
}
|
| 363 |
-
.user-item p {
|
| 364 |
-
font-size: 0.95em;
|
| 365 |
-
opacity: 0.8;
|
| 366 |
-
margin-bottom: 4px;
|
| 367 |
-
}
|
| 368 |
-
|
| 369 |
-
|
| 370 |
@media (max-width: 768px) {
|
| 371 |
.file-grid {
|
| 372 |
-
grid-template-columns: repeat(
|
| 373 |
}
|
| 374 |
-
.container { padding: 25px; }
|
| 375 |
-
h1 { font-size: 2.2em; }
|
| 376 |
-
h2 { font-size: 1.5em; }
|
| 377 |
}
|
| 378 |
-
|
| 379 |
@media (max-width: 480px) {
|
| 380 |
.file-grid {
|
| 381 |
grid-template-columns: 1fr;
|
| 382 |
}
|
| 383 |
-
.container { padding: 20px 15px; }
|
| 384 |
-
h1 { font-size: 1.8em; }
|
| 385 |
-
.slogan { font-size: 1em; }
|
| 386 |
-
.btn { width: 100%; margin-right: 0; } /* Stack buttons */
|
| 387 |
}
|
| 388 |
-
|
| 389 |
.file-item {
|
| 390 |
background: var(--card-bg);
|
| 391 |
padding: 15px;
|
| 392 |
-
border-radius:
|
| 393 |
box-shadow: var(--shadow);
|
| 394 |
text-align: center;
|
| 395 |
transition: var(--transition);
|
| 396 |
-
overflow: hidden; /* Ensure preview fits */
|
| 397 |
-
display: flex;
|
| 398 |
-
flex-direction: column;
|
| 399 |
-
justify-content: space-between; /* Push buttons down */
|
| 400 |
}
|
| 401 |
-
|
| 402 |
body.dark .file-item {
|
| 403 |
background: var(--card-bg-dark);
|
| 404 |
-
box-shadow: var(--shadow-dark);
|
| 405 |
-
border: 1px solid rgba(255, 255, 255, 0.08);
|
| 406 |
}
|
| 407 |
-
|
| 408 |
.file-item:hover {
|
| 409 |
-
transform: translateY(-
|
| 410 |
-
box-shadow: 0 18px 35px rgba(0, 0, 0, 0.15);
|
| 411 |
-
}
|
| 412 |
-
body.dark .file-item:hover {
|
| 413 |
-
box-shadow: 0 18px 35px rgba(0, 0, 0, 0.4);
|
| 414 |
}
|
| 415 |
-
|
| 416 |
-
.file-preview-container {
|
| 417 |
-
width: 100%;
|
| 418 |
-
height: 200px; /* Fixed height for consistency */
|
| 419 |
-
margin-bottom: 15px;
|
| 420 |
-
background-color: #eee; /* Placeholder bg */
|
| 421 |
-
border-radius: var(--border-radius-small);
|
| 422 |
-
overflow: hidden;
|
| 423 |
-
display: flex;
|
| 424 |
-
align-items: center;
|
| 425 |
-
justify-content: center;
|
| 426 |
-
cursor: pointer;
|
| 427 |
-
}
|
| 428 |
-
body.dark .file-preview-container {
|
| 429 |
-
background-color: #333;
|
| 430 |
-
}
|
| 431 |
-
|
| 432 |
.file-preview {
|
| 433 |
-
width: 100%;
|
| 434 |
-
height:
|
| 435 |
-
object-fit: cover;
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
.file-item .file-info {
|
| 441 |
-
margin-bottom: 15px; /* Space before buttons */
|
| 442 |
-
word-break: break-all; /* Prevent long names overflowing */
|
| 443 |
}
|
| 444 |
-
|
| 445 |
-
|
| 446 |
.file-item p {
|
| 447 |
font-size: 0.9em;
|
| 448 |
margin: 5px 0;
|
| 449 |
-
opacity: 0.8;
|
| 450 |
}
|
| 451 |
-
.file-item
|
| 452 |
-
font-weight: 600;
|
| 453 |
-
opacity: 1;
|
| 454 |
-
font-size: 1em;
|
| 455 |
color: var(--primary);
|
| 456 |
-
|
| 457 |
-
}
|
| 458 |
-
body.dark .file-item .filename {
|
| 459 |
-
color: var(--secondary);
|
| 460 |
-
}
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
.file-item .actions {
|
| 464 |
-
margin-top: auto; /* Pushes actions to the bottom */
|
| 465 |
-
display: flex;
|
| 466 |
-
justify-content: space-around; /* Evenly space buttons */
|
| 467 |
-
flex-wrap: wrap; /* Wrap if needed */
|
| 468 |
}
|
| 469 |
-
.file-item
|
| 470 |
-
|
| 471 |
-
font-size: 0.9em;
|
| 472 |
-
flex-grow: 1; /* Make buttons share space */
|
| 473 |
-
margin: 5px; /* Spacing around buttons */
|
| 474 |
}
|
| 475 |
-
|
| 476 |
-
|
| 477 |
.modal {
|
| 478 |
display: none;
|
| 479 |
position: fixed;
|
|
@@ -481,77 +288,31 @@ body.dark .file-item .filename {
|
|
| 481 |
left: 0;
|
| 482 |
width: 100%;
|
| 483 |
height: 100%;
|
| 484 |
-
background: rgba(0, 0, 0, 0.
|
| 485 |
z-index: 2000;
|
| 486 |
justify-content: center;
|
| 487 |
align-items: center;
|
| 488 |
-
padding: 20px;
|
| 489 |
-
cursor: pointer;
|
| 490 |
}
|
| 491 |
-
|
| 492 |
-
.modal-content {
|
| 493 |
max-width: 95%;
|
| 494 |
max-height: 95%;
|
| 495 |
-
display: flex; /* Center content */
|
| 496 |
-
justify-content: center;
|
| 497 |
-
align-items: center;
|
| 498 |
-
position: relative;
|
| 499 |
-
}
|
| 500 |
-
|
| 501 |
-
.modal img, .modal video {
|
| 502 |
-
max-width: 100%;
|
| 503 |
-
max-height: 100%;
|
| 504 |
object-fit: contain;
|
| 505 |
-
border-radius:
|
| 506 |
-
box-shadow:
|
| 507 |
-
cursor: default; /* Default cursor over media */
|
| 508 |
-
}
|
| 509 |
-
.modal video {
|
| 510 |
-
outline: none;
|
| 511 |
-
}
|
| 512 |
-
|
| 513 |
-
.modal-close {
|
| 514 |
-
position: absolute;
|
| 515 |
-
top: -30px;
|
| 516 |
-
right: -10px;
|
| 517 |
-
color: #fff;
|
| 518 |
-
font-size: 3em;
|
| 519 |
-
font-weight: bold;
|
| 520 |
-
cursor: pointer;
|
| 521 |
-
opacity: 0.8;
|
| 522 |
-
transition: opacity 0.2s;
|
| 523 |
-
}
|
| 524 |
-
.modal-close:hover {
|
| 525 |
-
opacity: 1;
|
| 526 |
}
|
| 527 |
-
|
| 528 |
-
|
| 529 |
#progress-container {
|
| 530 |
width: 100%;
|
| 531 |
-
height: 25px;
|
| 532 |
background: var(--glass-bg);
|
| 533 |
-
border-radius:
|
| 534 |
-
margin:
|
| 535 |
-
|
| 536 |
-
display: none; /* Hidden by default */
|
| 537 |
-
border: 1px solid rgba(0,0,0,0.1);
|
| 538 |
-
}
|
| 539 |
-
body.dark #progress-container {
|
| 540 |
-
background: var(--glass-bg-dark);
|
| 541 |
-
border: 1px solid rgba(255,255,255,0.15);
|
| 542 |
}
|
| 543 |
-
|
| 544 |
#progress-bar {
|
| 545 |
width: 0%;
|
| 546 |
-
height:
|
| 547 |
-
background:
|
| 548 |
-
border-radius:
|
| 549 |
-
transition: width 0.
|
| 550 |
-
text-align: center;
|
| 551 |
-
line-height: 25px;
|
| 552 |
-
color: white;
|
| 553 |
-
font-weight: 600;
|
| 554 |
-
font-size: 0.9em;
|
| 555 |
}
|
| 556 |
'''
|
| 557 |
|
|
@@ -564,11 +325,11 @@ def register():
|
|
| 564 |
data = load_data()
|
| 565 |
|
| 566 |
if username in data['users']:
|
| 567 |
-
flash('Пользователь с таким именем уже существует!'
|
| 568 |
return redirect(url_for('register'))
|
| 569 |
|
| 570 |
if not username or not password:
|
| 571 |
-
flash('
|
| 572 |
return redirect(url_for('register'))
|
| 573 |
|
| 574 |
data['users'][username] = {
|
|
@@ -576,14 +337,10 @@ def register():
|
|
| 576 |
'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
| 577 |
'files': []
|
| 578 |
}
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
return redirect(url_for('dashboard'))
|
| 584 |
-
except Exception as e:
|
| 585 |
-
flash(f'Ошибка сохранения данных: {e}', 'error')
|
| 586 |
-
return redirect(url_for('register'))
|
| 587 |
|
| 588 |
html = '''
|
| 589 |
<!DOCTYPE html>
|
|
@@ -592,16 +349,16 @@ def register():
|
|
| 592 |
<meta charset="UTF-8">
|
| 593 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 594 |
<title>Регистрация - Zeus Cloud</title>
|
|
|
|
| 595 |
<style>''' + BASE_STYLE + '''</style>
|
| 596 |
</head>
|
| 597 |
<body>
|
| 598 |
<div class="container">
|
| 599 |
<h1>Регистрация в Zeus Cloud</h1>
|
| 600 |
-
|
| 601 |
-
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 602 |
{% if messages %}
|
| 603 |
-
{% for
|
| 604 |
-
<div class="flash
|
| 605 |
{% endfor %}
|
| 606 |
{% endif %}
|
| 607 |
{% endwith %}
|
|
@@ -610,9 +367,8 @@ def register():
|
|
| 610 |
<input type="password" name="password" placeholder="Введите пароль" required>
|
| 611 |
<button type="submit" class="btn">Зарегистрироваться</button>
|
| 612 |
</form>
|
| 613 |
-
<p style="margin-top: 20px;
|
| 614 |
</div>
|
| 615 |
-
<script> document.body.classList.toggle('dark', localStorage.getItem('theme') === 'dark'); </script>
|
| 616 |
</body>
|
| 617 |
</html>
|
| 618 |
'''
|
|
@@ -625,7 +381,7 @@ def login():
|
|
| 625 |
password = request.form.get('password')
|
| 626 |
data = load_data()
|
| 627 |
|
| 628 |
-
if username in data
|
| 629 |
session['username'] = username
|
| 630 |
return jsonify({'status': 'success', 'redirect': url_for('dashboard')})
|
| 631 |
else:
|
|
@@ -637,18 +393,18 @@ def login():
|
|
| 637 |
<head>
|
| 638 |
<meta charset="UTF-8">
|
| 639 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 640 |
-
<title>
|
|
|
|
| 641 |
<style>''' + BASE_STYLE + '''</style>
|
| 642 |
</head>
|
| 643 |
<body>
|
| 644 |
<div class="container">
|
| 645 |
<h1>Zeus Cloud</h1>
|
| 646 |
-
<p class="slogan">Ваши файлы под надежной защитой квантовой криптографии</p>
|
| 647 |
<div id="flash-messages">
|
| 648 |
-
{% with messages = get_flashed_messages(
|
| 649 |
{% if messages %}
|
| 650 |
-
{% for
|
| 651 |
-
<div class="flash
|
| 652 |
{% endfor %}
|
| 653 |
{% endif %}
|
| 654 |
{% endwith %}
|
|
@@ -658,11 +414,9 @@ def login():
|
|
| 658 |
<input type="password" name="password" placeholder="Введите пароль" required>
|
| 659 |
<button type="submit" class="btn">Войти</button>
|
| 660 |
</form>
|
| 661 |
-
<p style="margin-top: 20px;
|
| 662 |
</div>
|
| 663 |
<script>
|
| 664 |
-
document.body.classList.toggle('dark', localStorage.getItem('theme') === 'dark');
|
| 665 |
-
|
| 666 |
const savedCredentials = JSON.parse(localStorage.getItem('zeusCredentials'));
|
| 667 |
if (savedCredentials) {
|
| 668 |
fetch('/', {
|
|
@@ -678,15 +432,12 @@ def login():
|
|
| 678 |
window.location.href = data.redirect;
|
| 679 |
}
|
| 680 |
})
|
| 681 |
-
.catch(error => console.error('Ошибка авто
|
| 682 |
}
|
| 683 |
|
| 684 |
document.getElementById('login-form').addEventListener('submit', function(e) {
|
| 685 |
e.preventDefault();
|
| 686 |
const formData = new FormData(this);
|
| 687 |
-
const flashContainer = document.getElementById('flash-messages');
|
| 688 |
-
flashContainer.innerHTML = '';
|
| 689 |
-
|
| 690 |
fetch('/', {
|
| 691 |
method: 'POST',
|
| 692 |
body: formData
|
|
@@ -699,11 +450,11 @@ def login():
|
|
| 699 |
localStorage.setItem('zeusCredentials', JSON.stringify({ username, password }));
|
| 700 |
window.location.href = data.redirect;
|
| 701 |
} else {
|
| 702 |
-
|
| 703 |
}
|
| 704 |
})
|
| 705 |
.catch(error => {
|
| 706 |
-
|
| 707 |
});
|
| 708 |
});
|
| 709 |
</script>
|
|
@@ -712,124 +463,66 @@ def login():
|
|
| 712 |
'''
|
| 713 |
return render_template_string(html)
|
| 714 |
|
| 715 |
-
|
| 716 |
@app.route('/dashboard', methods=['GET', 'POST'])
|
| 717 |
def dashboard():
|
| 718 |
if 'username' not in session:
|
| 719 |
-
flash('Пожалуйста, войдите!'
|
| 720 |
return redirect(url_for('login'))
|
| 721 |
|
| 722 |
username = session['username']
|
| 723 |
data = load_data()
|
| 724 |
-
if username not in data
|
| 725 |
session.pop('username', None)
|
| 726 |
-
|
| 727 |
-
flash('Пользователь не найден! Пожалуйста, войдите снова.', 'error')
|
| 728 |
return redirect(url_for('login'))
|
| 729 |
|
|
|
|
|
|
|
| 730 |
if request.method == 'POST':
|
| 731 |
files = request.files.getlist('files')
|
| 732 |
-
if
|
| 733 |
-
|
| 734 |
-
return redirect(url_for('dashboard'))
|
| 735 |
-
|
| 736 |
-
if len(files) > 20:
|
| 737 |
-
flash('Максимум 20 файлов за раз!', 'error')
|
| 738 |
return redirect(url_for('dashboard'))
|
| 739 |
|
| 740 |
-
if
|
| 741 |
-
|
| 742 |
-
|
|
|
|
| 743 |
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
# First save files locally
|
| 750 |
-
for file in files:
|
| 751 |
-
if file and file.filename:
|
| 752 |
-
filename = secure_filename(file.filename)
|
| 753 |
-
temp_path = os.path.join('uploads', f"{username}_{int(time.time())}_{filename}")
|
| 754 |
-
try:
|
| 755 |
file.save(temp_path)
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
upload_successful = False
|
| 761 |
-
# Clean up already saved temp files for this request
|
| 762 |
-
for info in temp_files_info:
|
| 763 |
-
if os.path.exists(info['temp_path']):
|
| 764 |
-
os.remove(info['temp_path'])
|
| 765 |
-
return redirect(url_for('dashboard'))
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
# Then upload to HF and update DB
|
| 769 |
-
current_files = data['users'][username].setdefault('files', [])
|
| 770 |
-
newly_added_files = []
|
| 771 |
-
|
| 772 |
-
for info in temp_files_info:
|
| 773 |
-
temp_path = info['temp_path']
|
| 774 |
-
filename = info['filename']
|
| 775 |
-
file_path_in_repo = f"cloud_files/{username}/{filename}"
|
| 776 |
-
|
| 777 |
-
try:
|
| 778 |
api.upload_file(
|
| 779 |
path_or_fileobj=temp_path,
|
| 780 |
-
path_in_repo=
|
| 781 |
repo_id=REPO_ID,
|
| 782 |
repo_type="dataset",
|
| 783 |
token=HF_TOKEN_WRITE,
|
| 784 |
-
commit_message=f"
|
| 785 |
)
|
| 786 |
|
| 787 |
file_info = {
|
| 788 |
'filename': filename,
|
| 789 |
-
'path':
|
| 790 |
'type': get_file_type(filename),
|
| 791 |
'upload_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 792 |
}
|
| 793 |
-
|
| 794 |
-
logging.info(f"Файл {filename} успешно загружен на HF.")
|
| 795 |
|
| 796 |
-
except Exception as e:
|
| 797 |
-
logging.error(f"Ошибка загрузки файла {filename} на HF: {e}")
|
| 798 |
-
flash(f'Ошибка загрузки файла {filename} на облако.', 'error')
|
| 799 |
-
upload_successful = False
|
| 800 |
-
# Potential: Implement retry or specific error handling here
|
| 801 |
-
|
| 802 |
-
finally:
|
| 803 |
-
# Clean up the local temp file regardless of upload success
|
| 804 |
if os.path.exists(temp_path):
|
| 805 |
-
|
| 806 |
-
os.remove(temp_path)
|
| 807 |
-
except Exception as e_rem:
|
| 808 |
-
logging.error(f"Ошибка удаления временного файла {temp_path}: {e_rem}")
|
| 809 |
|
|
|
|
|
|
|
| 810 |
|
| 811 |
-
if newly_added_files:
|
| 812 |
-
data['users'][username]['files'].extend(newly_added_files)
|
| 813 |
-
try:
|
| 814 |
-
save_data(data)
|
| 815 |
-
if upload_successful:
|
| 816 |
-
flash('Файлы успешно загружены!')
|
| 817 |
-
else:
|
| 818 |
-
flash('Некоторые файлы не удалось загрузить. Проверьте ошибки выше.', 'error')
|
| 819 |
-
except Exception as e_save:
|
| 820 |
-
logging.error(f"Критическая ошибка сохранения данных после загрузки: {e_save}")
|
| 821 |
-
flash('Критическая ошибка: не удалось обновить базу данных после загрузки файлов!', 'error')
|
| 822 |
-
|
| 823 |
-
elif not upload_successful:
|
| 824 |
-
flash('Ни один файл не был успешно загружен.', 'error')
|
| 825 |
-
|
| 826 |
-
# No need for manual cleanup here anymore, done in the loop
|
| 827 |
return redirect(url_for('dashboard'))
|
| 828 |
|
| 829 |
-
|
| 830 |
-
user_files_data = data['users'][username].get('files', [])
|
| 831 |
-
user_files = sorted(user_files_data, key=lambda x: x.get('upload_date', '1970-01-01 00:00:00'), reverse=True)
|
| 832 |
-
|
| 833 |
html = '''
|
| 834 |
<!DOCTYPE html>
|
| 835 |
<html lang="ru">
|
|
@@ -837,151 +530,77 @@ def dashboard():
|
|
| 837 |
<meta charset="UTF-8">
|
| 838 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 839 |
<title>Панель управления - Zeus Cloud</title>
|
|
|
|
| 840 |
<style>''' + BASE_STYLE + '''</style>
|
| 841 |
</head>
|
| 842 |
<body>
|
| 843 |
<div class="container">
|
| 844 |
<h1>Панель управления Zeus Cloud</h1>
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
<button id="theme-toggle" class="btn" style="padding: 5px 10px; font-size: 0.8em; margin-left: 10px;">🌙</button>
|
| 848 |
-
</p>
|
| 849 |
-
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 850 |
{% if messages %}
|
| 851 |
-
{% for
|
| 852 |
-
<div class="flash
|
| 853 |
{% endfor %}
|
| 854 |
{% endif %}
|
| 855 |
{% endwith %}
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
<input type="file" id="file-input" name="files" multiple required accept="image/*,video/*,audio/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.zip,.rar,.txt" style="display: none;">
|
| 860 |
-
<span id="file-names" style="margin-left: 15px; font-style: italic; opacity: 0.8;">Файлы не выбраны</span>
|
| 861 |
-
<button type="submit" class="btn" id="upload-btn">Загрузить</button>
|
| 862 |
</form>
|
| 863 |
-
|
| 864 |
<div id="progress-container">
|
| 865 |
-
<div id="progress-bar">
|
| 866 |
</div>
|
| 867 |
-
|
| 868 |
-
<
|
| 869 |
<div class="file-grid">
|
| 870 |
{% for file in user_files %}
|
| 871 |
<div class="file-item">
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
<
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
|
| 882 |
-
|
| 883 |
-
</
|
| 884 |
-
<div class="file-info">
|
| 885 |
-
<p class="filename">{{ file['filename'] }}</p>
|
| 886 |
-
<p>Тип: {{ file['type'] }}</p>
|
| 887 |
-
<p>Загружено: {{ file['upload_date'] }}</p>
|
| 888 |
-
</div>
|
| 889 |
-
<div class="actions">
|
| 890 |
-
<a href="{{ url_for('download_file', file_path=file['path']|urlencode, filename=file['filename']) }}" class="btn download-btn">Скачать</a>
|
| 891 |
-
<a href="{{ url_for('delete_file', file_path=file['path']|urlencode) }}" class="btn delete-btn" onclick="return confirm('Вы уверены, что хотите удалить этот файл: {{ file['filename'] }}?');">Удалить</a>
|
| 892 |
-
</div>
|
| 893 |
</div>
|
| 894 |
{% endfor %}
|
| 895 |
{% if not user_files %}
|
| 896 |
-
<p
|
| 897 |
{% endif %}
|
| 898 |
</div>
|
| 899 |
-
<a href="{{ url_for('logout') }}" class="btn" style="margin-top:
|
| 900 |
</div>
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
<span class="modal-close" onclick="closeModal()">×</span>
|
| 904 |
-
<div class="modal-content" onclick="event.stopPropagation()"> <!-- Предотвратить закрытие при клике на контент -->
|
| 905 |
-
<div id="modalBody"></div>
|
| 906 |
-
</div>
|
| 907 |
</div>
|
| 908 |
-
|
| 909 |
<script>
|
| 910 |
-
|
| 911 |
-
const themeToggle = document.getElementById('theme-toggle');
|
| 912 |
-
const currentTheme = localStorage.getItem('theme');
|
| 913 |
-
if (currentTheme === 'dark') {
|
| 914 |
-
document.body.classList.add('dark');
|
| 915 |
-
themeToggle.textContent = '☀️';
|
| 916 |
-
}
|
| 917 |
-
themeToggle.addEventListener('click', () => {
|
| 918 |
-
document.body.classList.toggle('dark');
|
| 919 |
-
let theme = 'light';
|
| 920 |
-
if (document.body.classList.contains('dark')) {
|
| 921 |
-
theme = 'dark';
|
| 922 |
-
themeToggle.textContent = '☀️';
|
| 923 |
-
} else {
|
| 924 |
-
themeToggle.textContent = '🌙';
|
| 925 |
-
}
|
| 926 |
-
localStorage.setItem('theme', theme);
|
| 927 |
-
});
|
| 928 |
-
|
| 929 |
-
// File input name display
|
| 930 |
-
const fileInput = document.getElementById('file-input');
|
| 931 |
-
const fileNamesSpan = document.getElementById('file-names');
|
| 932 |
-
fileInput.addEventListener('change', () => {
|
| 933 |
-
if (fileInput.files.length > 0) {
|
| 934 |
-
let names = Array.from(fileInput.files).map(f => f.name).join(', ');
|
| 935 |
-
if (names.length > 50) names = names.substring(0, 47) + '...';
|
| 936 |
-
fileNamesSpan.textContent = names;
|
| 937 |
-
fileNamesSpan.style.fontStyle = 'normal';
|
| 938 |
-
fileNamesSpan.style.opacity = '1';
|
| 939 |
-
} else {
|
| 940 |
-
fileNamesSpan.textContent = 'Файлы не выбраны';
|
| 941 |
-
fileNamesSpan.style.fontStyle = 'italic';
|
| 942 |
-
fileNamesSpan.style.opacity = '0.8';
|
| 943 |
-
}
|
| 944 |
-
});
|
| 945 |
-
|
| 946 |
-
|
| 947 |
-
function openModal(src, type) {
|
| 948 |
const modal = document.getElementById('mediaModal');
|
| 949 |
-
const
|
| 950 |
-
|
| 951 |
-
|
| 952 |
-
if (type === 'video') {
|
| 953 |
-
modalBody.innerHTML = `<video controls autoplay style="max-width: 100%; max-height: 100%; outline: none;"><source src="${src}" type="video/mp4">Ваш браузер не поддерживает встроенное видео.</video>`;
|
| 954 |
-
} else if (type === 'image') {
|
| 955 |
-
modalBody.innerHTML = `<img src="${src}" alt="Просмотр изображения" style="max-width: 100%; max-height: 100%;">`;
|
| 956 |
} else {
|
| 957 |
-
|
| 958 |
-
// For now, we allow opening but show a generic message/icon
|
| 959 |
-
modalBody.innerHTML = `<div style="color: #fff; font-size: 1.2em; text-align: center;">Предпросмотр для этого типа файла недоступен.<br><a href='${src}' download style='color: #aaf; margin-top:10px; display: inline-block;'>Скачать файл</a></div>`;
|
| 960 |
}
|
| 961 |
modal.style.display = 'flex';
|
| 962 |
-
document.body.style.overflow = 'hidden'; // Prevent background scrolling
|
| 963 |
}
|
| 964 |
-
|
| 965 |
-
function closeModal() {
|
| 966 |
const modal = document.getElementById('mediaModal');
|
| 967 |
-
|
| 968 |
-
|
| 969 |
-
|
| 970 |
-
|
| 971 |
-
|
| 972 |
-
|
| 973 |
-
|
| 974 |
-
if (event.target.id === 'mediaModal') {
|
| 975 |
-
closeModal();
|
| 976 |
-
}
|
| 977 |
-
}
|
| 978 |
-
// Optional: Close modal with Escape key
|
| 979 |
-
document.addEventListener('keydown', function(event) {
|
| 980 |
-
if (event.key === "Escape") {
|
| 981 |
-
closeModal();
|
| 982 |
}
|
| 983 |
-
|
| 984 |
-
|
| 985 |
|
| 986 |
const form = document.getElementById('upload-form');
|
| 987 |
const progressBar = document.getElementById('progress-bar');
|
|
@@ -990,51 +609,49 @@ def dashboard():
|
|
| 990 |
|
| 991 |
form.addEventListener('submit', function(e) {
|
| 992 |
e.preventDefault();
|
| 993 |
-
const files =
|
| 994 |
-
if (files.length === 0) {
|
| 995 |
-
alert('Пожалуйста, выберите файлы для загрузки.');
|
| 996 |
-
return;
|
| 997 |
-
}
|
| 998 |
if (files.length > 20) {
|
| 999 |
-
alert('
|
| 1000 |
return;
|
| 1001 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1002 |
|
| 1003 |
const formData = new FormData(form);
|
| 1004 |
progressContainer.style.display = 'block';
|
| 1005 |
progressBar.style.width = '0%';
|
| 1006 |
-
progressBar.textContent = '0%';
|
| 1007 |
uploadBtn.disabled = true;
|
| 1008 |
-
uploadBtn.textContent = 'Загрузка...';
|
| 1009 |
-
|
| 1010 |
|
| 1011 |
const xhr = new XMLHttpRequest();
|
| 1012 |
xhr.open('POST', '/dashboard', true);
|
| 1013 |
|
| 1014 |
xhr.upload.onprogress = function(event) {
|
| 1015 |
if (event.lengthComputable) {
|
| 1016 |
-
const percent =
|
| 1017 |
progressBar.style.width = percent + '%';
|
| 1018 |
-
progressBar.textContent = percent + '%';
|
| 1019 |
}
|
| 1020 |
};
|
| 1021 |
|
| 1022 |
xhr.onload = function() {
|
| 1023 |
-
|
| 1024 |
-
|
| 1025 |
-
|
| 1026 |
-
|
| 1027 |
-
|
| 1028 |
-
|
| 1029 |
-
|
| 1030 |
-
|
|
|
|
|
|
|
| 1031 |
};
|
| 1032 |
|
| 1033 |
xhr.onerror = function() {
|
| 1034 |
-
alert('Ошибка с
|
| 1035 |
progressContainer.style.display = 'none';
|
|
|
|
| 1036 |
uploadBtn.disabled = false;
|
| 1037 |
-
uploadBtn.textContent = 'Загрузить';
|
| 1038 |
};
|
| 1039 |
|
| 1040 |
xhr.send(formData);
|
|
@@ -1042,8 +659,8 @@ def dashboard():
|
|
| 1042 |
|
| 1043 |
document.getElementById('logout-btn').addEventListener('click', function(e) {
|
| 1044 |
e.preventDefault();
|
| 1045 |
-
localStorage.removeItem('zeusCredentials');
|
| 1046 |
-
window.location.href =
|
| 1047 |
});
|
| 1048 |
</script>
|
| 1049 |
</body>
|
|
@@ -1051,178 +668,117 @@ def dashboard():
|
|
| 1051 |
'''
|
| 1052 |
return render_template_string(html, username=username, user_files=user_files, repo_id=REPO_ID)
|
| 1053 |
|
| 1054 |
-
|
| 1055 |
@app.route('/download/<path:file_path>/<filename>')
|
| 1056 |
def download_file(file_path, filename):
|
| 1057 |
if 'username' not in session:
|
| 1058 |
-
flash('Пожалуйста, войдите!'
|
| 1059 |
return redirect(url_for('login'))
|
| 1060 |
|
| 1061 |
username = session['username']
|
| 1062 |
data = load_data()
|
| 1063 |
-
if username not in data
|
| 1064 |
session.pop('username', None)
|
| 1065 |
-
|
| 1066 |
-
flash('Пользователь не найден!', 'error')
|
| 1067 |
return redirect(url_for('login'))
|
| 1068 |
|
| 1069 |
-
|
| 1070 |
-
|
| 1071 |
-
|
| 1072 |
-
|
| 1073 |
-
|
| 1074 |
-
|
| 1075 |
-
|
| 1076 |
-
|
| 1077 |
-
|
| 1078 |
-
|
| 1079 |
-
referer = request.headers.get("Referer")
|
| 1080 |
-
if referer and '/admhosto/user/' in referer:
|
| 1081 |
-
return redirect(referer)
|
| 1082 |
-
return redirect(url_for('dashboard'))
|
| 1083 |
-
|
| 1084 |
-
|
| 1085 |
-
if not HF_TOKEN_READ:
|
| 1086 |
-
flash('Ошибка конфигурации сервера: Токен для чтения отсутствует.', 'error')
|
| 1087 |
-
return redirect(url_for('dashboard')) # Or referer?
|
| 1088 |
|
| 1089 |
-
file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{file_path}"
|
| 1090 |
-
logging.info(f"Попытка скачивания файла: {file_url}")
|
| 1091 |
|
|
|
|
| 1092 |
try:
|
| 1093 |
-
|
| 1094 |
-
|
| 1095 |
-
|
| 1096 |
-
|
| 1097 |
-
|
| 1098 |
-
|
| 1099 |
-
|
| 1100 |
-
|
| 1101 |
-
|
| 1102 |
-
|
| 1103 |
-
|
| 1104 |
-
|
| 1105 |
-
|
| 1106 |
-
|
| 1107 |
-
|
| 1108 |
-
|
| 1109 |
-
mimetype = common_mimetypes.get(ext, 'application/octet-stream')
|
| 1110 |
-
|
| 1111 |
-
# Stream the download
|
| 1112 |
-
return send_file(
|
| 1113 |
-
BytesIO(response.content), # Read content for send_file from BytesIO
|
| 1114 |
-
as_attachment=True,
|
| 1115 |
-
download_name=filename,
|
| 1116 |
-
mimetype=mimetype
|
| 1117 |
-
)
|
| 1118 |
-
# For true streaming with Response:
|
| 1119 |
-
# headers = { 'Content-Disposition': f'attachment; filename="{filename}"', 'Content-Type': mimetype }
|
| 1120 |
-
# return Response(response.iter_content(chunk_size=8192), headers=headers, status=response.status_code)
|
| 1121 |
-
|
| 1122 |
-
elif response.status_code == 404:
|
| 1123 |
-
flash('Ошибка: Файл не найден на сервере хранилища.', 'error')
|
| 1124 |
-
logging.error(f"Файл не найден на HF: {file_url} (status 404)")
|
| 1125 |
-
return redirect(request.referrer or url_for('dashboard'))
|
| 1126 |
-
else:
|
| 1127 |
-
flash(f'Ошибка скачивания файла ({response.status_code})!', 'error')
|
| 1128 |
-
logging.error(f"Ошибка скачивания файла с HF: {file_url} (status {response.status_code})")
|
| 1129 |
-
return redirect(request.referrer or url_for('dashboard'))
|
| 1130 |
-
|
| 1131 |
except requests.exceptions.RequestException as e:
|
| 1132 |
-
logging.error(f"
|
| 1133 |
-
flash('Ошибка с
|
| 1134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1135 |
except Exception as e:
|
| 1136 |
-
logging.error(f"
|
| 1137 |
-
flash('Произошла непредвиденная ошибка при скачивании.'
|
| 1138 |
-
|
|
|
|
|
|
|
|
|
|
| 1139 |
|
| 1140 |
|
| 1141 |
@app.route('/delete/<path:file_path>')
|
| 1142 |
def delete_file(file_path):
|
| 1143 |
if 'username' not in session:
|
| 1144 |
-
flash('Пожалуйста, войдите!'
|
| 1145 |
return redirect(url_for('login'))
|
| 1146 |
|
| 1147 |
username = session['username']
|
| 1148 |
data = load_data()
|
| 1149 |
-
if username not in data
|
| 1150 |
session.pop('username', None)
|
| 1151 |
-
|
| 1152 |
-
flash('Пользователь не найден!', 'error')
|
| 1153 |
return redirect(url_for('login'))
|
| 1154 |
|
| 1155 |
-
user_files = data['users'][username]
|
| 1156 |
-
|
| 1157 |
-
for i, file in enumerate(user_files):
|
| 1158 |
-
if file.get('path') == file_path:
|
| 1159 |
-
file_to_delete_index = i
|
| 1160 |
-
break
|
| 1161 |
-
|
| 1162 |
-
if file_to_delete_index == -1:
|
| 1163 |
-
flash('Файл не найден в вашем списке!', 'error')
|
| 1164 |
-
return redirect(url_for('dashboard'))
|
| 1165 |
-
|
| 1166 |
-
file_info = user_files[file_to_delete_index]
|
| 1167 |
-
filename = file_info.get('filename', 'неизвестный файл')
|
| 1168 |
|
| 1169 |
-
if not
|
| 1170 |
-
flash('
|
| 1171 |
return redirect(url_for('dashboard'))
|
| 1172 |
|
| 1173 |
try:
|
| 1174 |
api = HfApi()
|
| 1175 |
-
logging.info(f"Попытка удаления файла с HF: {file_path}")
|
| 1176 |
api.delete_file(
|
| 1177 |
path_in_repo=file_path,
|
| 1178 |
repo_id=REPO_ID,
|
| 1179 |
repo_type="dataset",
|
| 1180 |
token=HF_TOKEN_WRITE,
|
| 1181 |
-
commit_message=f"
|
| 1182 |
)
|
| 1183 |
-
|
| 1184 |
-
|
| 1185 |
-
# Remove from local data only after successful deletion from HF
|
| 1186 |
-
del data['users'][username]['files'][file_to_delete_index]
|
| 1187 |
save_data(data)
|
| 1188 |
-
flash(
|
| 1189 |
-
|
| 1190 |
except Exception as e:
|
| 1191 |
-
|
| 1192 |
-
|
| 1193 |
-
# Check if the error indicates the file was already gone from HF
|
| 1194 |
-
if "404" in str(e) or "not found" in str(e).lower():
|
| 1195 |
-
logging.warning(f"Файл {file_path} не найден на HF при попытке удаления, возможно, уже удален. Удаляем из базы данных.")
|
| 1196 |
-
try:
|
| 1197 |
-
del data['users'][username]['files'][file_to_delete_index]
|
| 1198 |
-
save_data(data)
|
| 1199 |
-
flash(f'Файл "{filename}" уже был удален из хранилища, запись удалена из базы данных.', 'warning')
|
| 1200 |
-
except Exception as e_save:
|
| 1201 |
-
logging.error(f"Ошибка сохранения данных после подтверждения удаления отсутствующего файла: {e_save}")
|
| 1202 |
-
flash('Ошибка: Не удалось обновить базу данных после удаления файла.', 'error')
|
| 1203 |
-
else:
|
| 1204 |
-
flash(f'Ошибка при удалении файла "{filename}" из облака!', 'error')
|
| 1205 |
|
| 1206 |
return redirect(url_for('dashboard'))
|
| 1207 |
|
| 1208 |
@app.route('/logout')
|
| 1209 |
def logout():
|
| 1210 |
session.pop('username', None)
|
| 1211 |
-
#
|
| 1212 |
-
|
| 1213 |
return redirect(url_for('login'))
|
| 1214 |
|
| 1215 |
|
| 1216 |
@app.route('/admhosto')
|
| 1217 |
def admin_panel():
|
| 1218 |
-
#
|
| 1219 |
-
# This is highly insecure and should be protected in a real application
|
| 1220 |
-
# (e.g., check session for a specific admin user, IP check, separate login)
|
| 1221 |
data = load_data()
|
| 1222 |
-
|
| 1223 |
-
# Sort users alphabetically by username for consistency
|
| 1224 |
-
users = dict(sorted(users_data.items()))
|
| 1225 |
-
|
| 1226 |
|
| 1227 |
html = '''
|
| 1228 |
<!DOCTYPE html>
|
|
@@ -1230,51 +786,40 @@ def admin_panel():
|
|
| 1230 |
<head>
|
| 1231 |
<meta charset="UTF-8">
|
| 1232 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 1233 |
-
<title>
|
|
|
|
| 1234 |
<style>''' + BASE_STYLE + '''</style>
|
| 1235 |
</head>
|
| 1236 |
<body>
|
| 1237 |
<div class="container">
|
| 1238 |
-
<h1>
|
| 1239 |
-
<button id="theme-toggle" class="btn" style="padding: 5px 10px; font-size: 0.8em; position: absolute; top: 20px; right: 20px;">🌙</button>
|
| 1240 |
<h2>Список пользователей</h2>
|
| 1241 |
<div class="user-list">
|
| 1242 |
{% for username, user_data in users.items() %}
|
| 1243 |
<div class="user-item">
|
| 1244 |
<a href="{{ url_for('admin_user_files', username=username) }}">{{ username }}</a>
|
| 1245 |
-
<p>Дата регистрации: {{ user_data.get('created_at', '
|
| 1246 |
<p>Количество файлов: {{ user_data.get('files', []) | length }}</p>
|
| 1247 |
-
|
|
|
|
|
|
|
|
|
|
| 1248 |
</div>
|
| 1249 |
{% endfor %}
|
| 1250 |
{% if not users %}
|
| 1251 |
<p>Пользователей пока нет.</p>
|
| 1252 |
{% endif %}
|
| 1253 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1254 |
</div>
|
| 1255 |
-
<script>
|
| 1256 |
-
const themeToggle = document.getElementById('theme-toggle');
|
| 1257 |
-
const currentTheme = localStorage.getItem('theme');
|
| 1258 |
-
if (currentTheme === 'dark') {
|
| 1259 |
-
document.body.classList.add('dark');
|
| 1260 |
-
themeToggle.textContent = '☀️';
|
| 1261 |
-
} else {
|
| 1262 |
-
document.body.classList.remove('dark');
|
| 1263 |
-
themeToggle.textContent = '🌙';
|
| 1264 |
-
}
|
| 1265 |
-
themeToggle.addEventListener('click', () => {
|
| 1266 |
-
document.body.classList.toggle('dark');
|
| 1267 |
-
let theme = 'light';
|
| 1268 |
-
if (document.body.classList.contains('dark')) {
|
| 1269 |
-
theme = 'dark';
|
| 1270 |
-
themeToggle.textContent = '☀️';
|
| 1271 |
-
} else {
|
| 1272 |
-
themeToggle.textContent = '🌙';
|
| 1273 |
-
}
|
| 1274 |
-
localStorage.setItem('theme', theme);
|
| 1275 |
-
});
|
| 1276 |
-
document.body.classList.toggle('dark', localStorage.getItem('theme') === 'dark');
|
| 1277 |
-
</script>
|
| 1278 |
</body>
|
| 1279 |
</html>
|
| 1280 |
'''
|
|
@@ -1282,14 +827,13 @@ def admin_panel():
|
|
| 1282 |
|
| 1283 |
@app.route('/admhosto/user/<username>')
|
| 1284 |
def admin_user_files(username):
|
| 1285 |
-
#
|
| 1286 |
data = load_data()
|
| 1287 |
-
if username not in data
|
| 1288 |
-
flash('Пользователь не найден!'
|
| 1289 |
return redirect(url_for('admin_panel'))
|
| 1290 |
|
| 1291 |
-
|
| 1292 |
-
user_files = sorted(user_files_data, key=lambda x: x.get('upload_date', '1970-01-01 00:00:00'), reverse=True)
|
| 1293 |
|
| 1294 |
html = '''
|
| 1295 |
<!DOCTYPE html>
|
|
@@ -1298,141 +842,198 @@ def admin_user_files(username):
|
|
| 1298 |
<meta charset="UTF-8">
|
| 1299 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 1300 |
<title>Файлы пользователя {{ username }} - Zeus Cloud</title>
|
| 1301 |
-
|
|
|
|
| 1302 |
</head>
|
| 1303 |
<body>
|
| 1304 |
<div class="container">
|
| 1305 |
-
|
| 1306 |
-
|
| 1307 |
-
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 1308 |
{% if messages %}
|
| 1309 |
-
{% for
|
| 1310 |
-
<div class="flash
|
| 1311 |
{% endfor %}
|
| 1312 |
{% endif %}
|
| 1313 |
{% endwith %}
|
| 1314 |
-
|
| 1315 |
<div class="file-grid">
|
| 1316 |
{% for file in user_files %}
|
| 1317 |
-
|
| 1318 |
-
|
| 1319 |
-
|
| 1320 |
-
|
| 1321 |
-
|
| 1322 |
-
|
| 1323 |
-
|
| 1324 |
-
|
| 1325 |
-
|
| 1326 |
-
|
| 1327 |
-
|
| 1328 |
-
|
| 1329 |
-
|
| 1330 |
-
<
|
| 1331 |
-
|
| 1332 |
-
|
| 1333 |
-
<p>Загружено: {{ file['upload_date'] }}</p>
|
| 1334 |
-
</div>
|
| 1335 |
-
<div class="actions">
|
| 1336 |
-
<a href="{{ url_for('download_file', file_path=file['path']|urlencode, filename=file['filename']) }}" class="btn download-btn">Скачать</a>
|
| 1337 |
-
<!-- Add Admin Delete Here - Needs separate endpoint or logic -->
|
| 1338 |
-
<!-- <a href="{{ url_for('admin_delete_file', username=username, file_path=file['path']|urlencode) }}" class="btn delete-btn" onclick="return confirm('Удалить этот файл пользователя {{ username }}?');">Удалить (Админ)</a> -->
|
| 1339 |
-
</div>
|
| 1340 |
</div>
|
| 1341 |
{% endfor %}
|
| 1342 |
{% if not user_files %}
|
| 1343 |
-
|
| 1344 |
{% endif %}
|
| 1345 |
</div>
|
| 1346 |
-
<a href="{{ url_for('admin_panel') }}" class="btn" style="margin-top:
|
| 1347 |
</div>
|
| 1348 |
-
|
| 1349 |
-
|
| 1350 |
-
<span class="modal-close" onclick="closeModal()">×</span>
|
| 1351 |
-
<div class="modal-content" onclick="event.stopPropagation()">
|
| 1352 |
-
<div id="modalBody"></div>
|
| 1353 |
-
</div>
|
| 1354 |
</div>
|
| 1355 |
-
|
| 1356 |
-
|
| 1357 |
-
// Theme toggle (duplicate from dashboard, could be DRYed up)
|
| 1358 |
-
const themeToggle = document.getElementById('theme-toggle');
|
| 1359 |
-
const currentTheme = localStorage.getItem('theme');
|
| 1360 |
-
if (currentTheme === 'dark') {
|
| 1361 |
-
document.body.classList.add('dark');
|
| 1362 |
-
themeToggle.textContent = '☀️';
|
| 1363 |
-
} else {
|
| 1364 |
-
document.body.classList.remove('dark');
|
| 1365 |
-
themeToggle.textContent = '🌙';
|
| 1366 |
-
}
|
| 1367 |
-
themeToggle.addEventListener('click', () => {
|
| 1368 |
-
document.body.classList.toggle('dark');
|
| 1369 |
-
let theme = 'light';
|
| 1370 |
-
if (document.body.classList.contains('dark')) {
|
| 1371 |
-
theme = 'dark';
|
| 1372 |
-
themeToggle.textContent = '☀️';
|
| 1373 |
-
} else {
|
| 1374 |
-
themeToggle.textContent = '🌙';
|
| 1375 |
-
}
|
| 1376 |
-
localStorage.setItem('theme', theme);
|
| 1377 |
-
});
|
| 1378 |
-
document.body.classList.toggle('dark', localStorage.getItem('theme') === 'dark');
|
| 1379 |
-
|
| 1380 |
-
// Modal functions (duplicate from dashboard)
|
| 1381 |
-
function openModal(src, type) {
|
| 1382 |
const modal = document.getElementById('mediaModal');
|
| 1383 |
-
const
|
| 1384 |
-
|
| 1385 |
-
|
| 1386 |
-
|
| 1387 |
-
|
| 1388 |
-
|
| 1389 |
-
|
| 1390 |
-
|
| 1391 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1392 |
}
|
| 1393 |
modal.style.display = 'flex';
|
| 1394 |
-
document.body.style.overflow = 'hidden';
|
| 1395 |
}
|
| 1396 |
-
|
| 1397 |
-
function closeModal() {
|
| 1398 |
const modal = document.getElementById('mediaModal');
|
| 1399 |
-
|
| 1400 |
-
|
| 1401 |
-
|
| 1402 |
-
|
| 1403 |
-
|
| 1404 |
-
|
| 1405 |
-
|
| 1406 |
-
closeModal();
|
| 1407 |
-
}
|
| 1408 |
-
}
|
| 1409 |
-
document.addEventListener('keydown', function(event) {
|
| 1410 |
-
if (event.key === "Escape") {
|
| 1411 |
-
closeModal();
|
| 1412 |
}
|
| 1413 |
-
|
|
|
|
|
|
|
| 1414 |
</script>
|
| 1415 |
</body>
|
| 1416 |
</html>
|
| 1417 |
'''
|
| 1418 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1419 |
|
| 1420 |
|
| 1421 |
if __name__ == '__main__':
|
| 1422 |
-
#
|
| 1423 |
-
|
| 1424 |
-
|
|
|
|
|
|
|
| 1425 |
|
| 1426 |
-
#
|
| 1427 |
-
#
|
| 1428 |
if HF_TOKEN_WRITE:
|
| 1429 |
-
|
| 1430 |
-
backup_thread.start()
|
| 1431 |
-
print("Поток периодического резервного копирования запущен.")
|
| 1432 |
else:
|
| 1433 |
-
|
|
|
|
|
|
|
|
|
|
| 1434 |
|
| 1435 |
-
# Run Flask app
|
| 1436 |
-
print("Запуск Flask приложения...")
|
| 1437 |
-
port = int(os.environ.get("PORT", 7860))
|
| 1438 |
-
app.run(debug=False, host='0.0.0.0', port=port)
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
from flask import Flask, render_template_string, request, redirect, url_for, session, flash, send_file, jsonify
|
| 4 |
from flask_caching import Cache
|
| 5 |
import json
|
|
|
|
| 14 |
from io import BytesIO
|
| 15 |
|
| 16 |
app = Flask(__name__)
|
| 17 |
+
app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey")
|
| 18 |
DATA_FILE = 'cloudeng_data.json'
|
| 19 |
REPO_ID = "Eluza133/Z1e1u"
|
| 20 |
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
|
|
|
|
| 30 |
with open(DATA_FILE, 'r', encoding='utf-8') as file:
|
| 31 |
data = json.load(file)
|
| 32 |
if not isinstance(data, dict):
|
| 33 |
+
logging.warning("Data is not in dict format, initializing empty database")
|
| 34 |
return {'users': {}, 'files': {}}
|
| 35 |
data.setdefault('users', {})
|
| 36 |
data.setdefault('files', {})
|
| 37 |
+
logging.info("Data successfully loaded")
|
| 38 |
return data
|
| 39 |
except Exception as e:
|
| 40 |
+
logging.error(f"Error loading data: {e}")
|
| 41 |
return {'users': {}, 'files': {}}
|
| 42 |
|
| 43 |
def save_data(data):
|
|
|
|
| 46 |
json.dump(data, file, ensure_ascii=False, indent=4)
|
| 47 |
upload_db_to_hf()
|
| 48 |
cache.clear()
|
| 49 |
+
logging.info("Data saved and uploaded to HF")
|
| 50 |
except Exception as e:
|
| 51 |
+
logging.error(f"Error saving data: {e}")
|
| 52 |
raise
|
| 53 |
|
| 54 |
def upload_db_to_hf():
|
|
|
|
|
|
|
|
|
|
| 55 |
try:
|
| 56 |
api = HfApi()
|
| 57 |
api.upload_file(
|
|
|
|
| 60 |
repo_id=REPO_ID,
|
| 61 |
repo_type="dataset",
|
| 62 |
token=HF_TOKEN_WRITE,
|
| 63 |
+
commit_message=f"Backup {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
|
| 64 |
)
|
| 65 |
+
logging.info("Database uploaded to Hugging Face")
|
| 66 |
except Exception as e:
|
| 67 |
+
logging.error(f"Error uploading database: {e}")
|
| 68 |
|
| 69 |
def download_db_from_hf():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
try:
|
| 71 |
hf_hub_download(
|
| 72 |
repo_id=REPO_ID,
|
|
|
|
| 76 |
local_dir=".",
|
| 77 |
local_dir_use_symlinks=False
|
| 78 |
)
|
| 79 |
+
logging.info("Database downloaded from Hugging Face")
|
| 80 |
except Exception as e:
|
| 81 |
+
logging.error(f"Error downloading database: {e}")
|
| 82 |
if not os.path.exists(DATA_FILE):
|
| 83 |
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 84 |
json.dump({'users': {}, 'files': {}}, f)
|
|
|
|
|
|
|
| 85 |
|
| 86 |
def periodic_backup():
|
| 87 |
while True:
|
| 88 |
+
upload_db_to_hf()
|
| 89 |
time.sleep(1800)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
def get_file_type(filename):
|
| 92 |
+
video_extensions = ('.mp4', '.mov', '.avi')
|
| 93 |
+
image_extensions = ('.jpg', '.jpeg', '.png', '.gif')
|
| 94 |
+
if filename.lower().endswith(video_extensions):
|
|
|
|
| 95 |
return 'video'
|
| 96 |
+
elif filename.lower().endswith(image_extensions):
|
| 97 |
return 'image'
|
| 98 |
return 'other'
|
| 99 |
|
| 100 |
BASE_STYLE = '''
|
|
|
|
|
|
|
| 101 |
:root {
|
| 102 |
+
--primary: #ff4d6d;
|
| 103 |
+
--secondary: #00ddeb;
|
| 104 |
+
--accent: #8b5cf6;
|
| 105 |
+
--background-light: #f5f6fa;
|
| 106 |
+
--background-dark: #1a1625;
|
| 107 |
+
--card-bg: rgba(255, 255, 255, 0.95);
|
| 108 |
+
--card-bg-dark: rgba(40, 35, 60, 0.95);
|
| 109 |
+
--text-light: #2a1e5a;
|
| 110 |
+
--text-dark: #e8e1ff;
|
| 111 |
+
--shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
|
| 112 |
+
--glass-bg: rgba(255, 255, 255, 0.15);
|
| 113 |
+
--transition: all 0.3s ease;
|
| 114 |
+
--delete-color: #ff4444;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
}
|
|
|
|
| 116 |
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
|
|
| 117 |
body {
|
| 118 |
+
font-family: 'Inter', sans-serif;
|
| 119 |
+
background: var(--background-light);
|
| 120 |
color: var(--text-light);
|
| 121 |
+
line-height: 1.6;
|
|
|
|
| 122 |
}
|
|
|
|
| 123 |
body.dark {
|
| 124 |
+
background: var(--background-dark);
|
| 125 |
color: var(--text-dark);
|
| 126 |
}
|
|
|
|
| 127 |
.container {
|
| 128 |
+
margin: 20px auto;
|
| 129 |
+
max-width: 1200px;
|
| 130 |
+
padding: 25px;
|
| 131 |
background: var(--card-bg);
|
| 132 |
+
border-radius: 20px;
|
| 133 |
box-shadow: var(--shadow);
|
|
|
|
|
|
|
| 134 |
}
|
|
|
|
| 135 |
body.dark .container {
|
| 136 |
background: var(--card-bg-dark);
|
|
|
|
|
|
|
| 137 |
}
|
|
|
|
| 138 |
h1 {
|
| 139 |
+
font-size: 2em;
|
| 140 |
+
font-weight: 800;
|
| 141 |
text-align: center;
|
| 142 |
+
margin-bottom: 25px;
|
| 143 |
+
background: linear-gradient(135deg, var(--primary), var(--accent));
|
| 144 |
-webkit-background-clip: text;
|
| 145 |
color: transparent;
|
|
|
|
| 146 |
}
|
|
|
|
| 147 |
h2 {
|
| 148 |
+
font-size: 1.5em;
|
| 149 |
+
margin-top: 30px;
|
|
|
|
| 150 |
color: var(--text-light);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
}
|
|
|
|
| 152 |
body.dark h2 {
|
| 153 |
color: var(--text-dark);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
input, textarea {
|
| 156 |
width: 100%;
|
| 157 |
+
padding: 14px;
|
| 158 |
+
margin: 12px 0;
|
| 159 |
+
border: none;
|
| 160 |
+
border-radius: 14px;
|
| 161 |
background: var(--glass-bg);
|
| 162 |
color: var(--text-light);
|
| 163 |
font-size: 1.1em;
|
| 164 |
+
box-shadow: inset 0 3px 10px rgba(0, 0, 0, 0.1);
|
|
|
|
| 165 |
}
|
|
|
|
| 166 |
body.dark input, body.dark textarea {
|
| 167 |
color: var(--text-dark);
|
|
|
|
|
|
|
|
|
|
| 168 |
}
|
|
|
|
| 169 |
input:focus, textarea:focus {
|
| 170 |
outline: none;
|
| 171 |
+
box-shadow: 0 0 0 4px var(--primary);
|
|
|
|
| 172 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
.btn {
|
| 174 |
+
padding: 14px 28px;
|
| 175 |
+
background: var(--primary);
|
| 176 |
color: white;
|
| 177 |
border: none;
|
| 178 |
+
border-radius: 14px;
|
| 179 |
cursor: pointer;
|
| 180 |
+
font-size: 1.1em;
|
| 181 |
font-weight: 600;
|
| 182 |
transition: var(--transition);
|
| 183 |
+
box-shadow: var(--shadow);
|
| 184 |
display: inline-block;
|
| 185 |
text-decoration: none;
|
|
|
|
|
|
|
|
|
|
| 186 |
}
|
|
|
|
| 187 |
.btn:hover {
|
| 188 |
+
transform: scale(1.05);
|
| 189 |
+
background: #e6415f;
|
|
|
|
| 190 |
}
|
|
|
|
| 191 |
.download-btn {
|
| 192 |
+
background: var(--secondary);
|
| 193 |
+
margin-top: 10px;
|
| 194 |
}
|
| 195 |
.download-btn:hover {
|
| 196 |
+
background: #00b8c5;
|
| 197 |
}
|
|
|
|
| 198 |
.delete-btn {
|
| 199 |
+
background: var(--delete-color);
|
| 200 |
+
margin-top: 10px;
|
| 201 |
}
|
| 202 |
.delete-btn:hover {
|
| 203 |
+
background: #cc3333;
|
| 204 |
}
|
|
|
|
| 205 |
.flash {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
color: var(--secondary);
|
| 207 |
+
text-align: center;
|
| 208 |
+
margin-bottom: 15px;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
}
|
|
|
|
|
|
|
| 210 |
.file-grid {
|
| 211 |
display: grid;
|
| 212 |
+
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
| 213 |
+
gap: 20px;
|
| 214 |
+
margin-top: 20px;
|
| 215 |
}
|
|
|
|
| 216 |
.user-list {
|
| 217 |
+
margin-top: 20px;
|
|
|
|
|
|
|
|
|
|
| 218 |
}
|
|
|
|
| 219 |
.user-item {
|
| 220 |
+
padding: 15px;
|
| 221 |
background: var(--card-bg);
|
| 222 |
+
border-radius: 16px;
|
| 223 |
margin-bottom: 10px;
|
| 224 |
box-shadow: var(--shadow);
|
| 225 |
transition: var(--transition);
|
|
|
|
| 226 |
}
|
|
|
|
| 227 |
body.dark .user-item {
|
| 228 |
background: var(--card-bg-dark);
|
|
|
|
|
|
|
| 229 |
}
|
|
|
|
| 230 |
.user-item:hover {
|
| 231 |
+
transform: translateY(-5px);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
}
|
|
|
|
|
|
|
| 233 |
.user-item a {
|
| 234 |
color: var(--primary);
|
| 235 |
text-decoration: none;
|
| 236 |
+
font-weight: 600;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
}
|
|
|
|
| 238 |
.user-item a:hover {
|
| 239 |
+
color: var(--accent);
|
| 240 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
@media (max-width: 768px) {
|
| 242 |
.file-grid {
|
| 243 |
+
grid-template-columns: repeat(2, 1fr);
|
| 244 |
}
|
|
|
|
|
|
|
|
|
|
| 245 |
}
|
|
|
|
| 246 |
@media (max-width: 480px) {
|
| 247 |
.file-grid {
|
| 248 |
grid-template-columns: 1fr;
|
| 249 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
}
|
|
|
|
| 251 |
.file-item {
|
| 252 |
background: var(--card-bg);
|
| 253 |
padding: 15px;
|
| 254 |
+
border-radius: 16px;
|
| 255 |
box-shadow: var(--shadow);
|
| 256 |
text-align: center;
|
| 257 |
transition: var(--transition);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
}
|
|
|
|
| 259 |
body.dark .file-item {
|
| 260 |
background: var(--card-bg-dark);
|
|
|
|
|
|
|
| 261 |
}
|
|
|
|
| 262 |
.file-item:hover {
|
| 263 |
+
transform: translateY(-5px);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
.file-preview {
|
| 266 |
+
max-width: 100%;
|
| 267 |
+
max-height: 200px;
|
| 268 |
+
object-fit: cover;
|
| 269 |
+
border-radius: 10px;
|
| 270 |
+
margin-bottom: 10px;
|
| 271 |
+
loading: lazy;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
}
|
|
|
|
|
|
|
| 273 |
.file-item p {
|
| 274 |
font-size: 0.9em;
|
| 275 |
margin: 5px 0;
|
|
|
|
| 276 |
}
|
| 277 |
+
.file-item a {
|
|
|
|
|
|
|
|
|
|
| 278 |
color: var(--primary);
|
| 279 |
+
text-decoration: none;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
}
|
| 281 |
+
.file-item a:hover {
|
| 282 |
+
color: var(--accent);
|
|
|
|
|
|
|
|
|
|
| 283 |
}
|
|
|
|
|
|
|
| 284 |
.modal {
|
| 285 |
display: none;
|
| 286 |
position: fixed;
|
|
|
|
| 288 |
left: 0;
|
| 289 |
width: 100%;
|
| 290 |
height: 100%;
|
| 291 |
+
background: rgba(0, 0, 0, 0.85);
|
| 292 |
z-index: 2000;
|
| 293 |
justify-content: center;
|
| 294 |
align-items: center;
|
|
|
|
|
|
|
| 295 |
}
|
| 296 |
+
.modal img, .modal video {
|
|
|
|
| 297 |
max-width: 95%;
|
| 298 |
max-height: 95%;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
object-fit: contain;
|
| 300 |
+
border-radius: 20px;
|
| 301 |
+
box-shadow: var(--shadow);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
}
|
|
|
|
|
|
|
| 303 |
#progress-container {
|
| 304 |
width: 100%;
|
|
|
|
| 305 |
background: var(--glass-bg);
|
| 306 |
+
border-radius: 10px;
|
| 307 |
+
margin: 15px 0;
|
| 308 |
+
display: none;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
}
|
|
|
|
| 310 |
#progress-bar {
|
| 311 |
width: 0%;
|
| 312 |
+
height: 20px;
|
| 313 |
+
background: var(--primary);
|
| 314 |
+
border-radius: 10px;
|
| 315 |
+
transition: width 0.3s ease;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
}
|
| 317 |
'''
|
| 318 |
|
|
|
|
| 325 |
data = load_data()
|
| 326 |
|
| 327 |
if username in data['users']:
|
| 328 |
+
flash('Пользователь с таким именем уже существует!')
|
| 329 |
return redirect(url_for('register'))
|
| 330 |
|
| 331 |
if not username or not password:
|
| 332 |
+
flash('Имя пользователя и пароль обязательны!')
|
| 333 |
return redirect(url_for('register'))
|
| 334 |
|
| 335 |
data['users'][username] = {
|
|
|
|
| 337 |
'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
| 338 |
'files': []
|
| 339 |
}
|
| 340 |
+
save_data(data)
|
| 341 |
+
session['username'] = username
|
| 342 |
+
flash('Регистрация прошла успешно!')
|
| 343 |
+
return redirect(url_for('dashboard'))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
|
| 345 |
html = '''
|
| 346 |
<!DOCTYPE html>
|
|
|
|
| 349 |
<meta charset="UTF-8">
|
| 350 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 351 |
<title>Регистрация - Zeus Cloud</title>
|
| 352 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 353 |
<style>''' + BASE_STYLE + '''</style>
|
| 354 |
</head>
|
| 355 |
<body>
|
| 356 |
<div class="container">
|
| 357 |
<h1>Регистрация в Zeus Cloud</h1>
|
| 358 |
+
{% with messages = get_flashed_messages() %}
|
|
|
|
| 359 |
{% if messages %}
|
| 360 |
+
{% for message in messages %}
|
| 361 |
+
<div class="flash">{{ message }}</div>
|
| 362 |
{% endfor %}
|
| 363 |
{% endif %}
|
| 364 |
{% endwith %}
|
|
|
|
| 367 |
<input type="password" name="password" placeholder="Введите пароль" required>
|
| 368 |
<button type="submit" class="btn">Зарегистрироваться</button>
|
| 369 |
</form>
|
| 370 |
+
<p style="margin-top: 20px;">Уже есть аккаунт? <a href="{{ url_for('login') }}">Войти</a></p>
|
| 371 |
</div>
|
|
|
|
| 372 |
</body>
|
| 373 |
</html>
|
| 374 |
'''
|
|
|
|
| 381 |
password = request.form.get('password')
|
| 382 |
data = load_data()
|
| 383 |
|
| 384 |
+
if username in data['users'] and data['users'][username]['password'] == password:
|
| 385 |
session['username'] = username
|
| 386 |
return jsonify({'status': 'success', 'redirect': url_for('dashboard')})
|
| 387 |
else:
|
|
|
|
| 393 |
<head>
|
| 394 |
<meta charset="UTF-8">
|
| 395 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 396 |
+
<title>Zeus Cloud</title>
|
| 397 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 398 |
<style>''' + BASE_STYLE + '''</style>
|
| 399 |
</head>
|
| 400 |
<body>
|
| 401 |
<div class="container">
|
| 402 |
<h1>Zeus Cloud</h1>
|
|
|
|
| 403 |
<div id="flash-messages">
|
| 404 |
+
{% with messages = get_flashed_messages() %}
|
| 405 |
{% if messages %}
|
| 406 |
+
{% for message in messages %}
|
| 407 |
+
<div class="flash">{{ message }}</div>
|
| 408 |
{% endfor %}
|
| 409 |
{% endif %}
|
| 410 |
{% endwith %}
|
|
|
|
| 414 |
<input type="password" name="password" placeholder="Введите пароль" required>
|
| 415 |
<button type="submit" class="btn">Войти</button>
|
| 416 |
</form>
|
| 417 |
+
<p style="margin-top: 20px;">Нет аккаунта? <a href="{{ url_for('register') }}">Зарегистрируйтесь</a></p>
|
| 418 |
</div>
|
| 419 |
<script>
|
|
|
|
|
|
|
| 420 |
const savedCredentials = JSON.parse(localStorage.getItem('zeusCredentials'));
|
| 421 |
if (savedCredentials) {
|
| 422 |
fetch('/', {
|
|
|
|
| 432 |
window.location.href = data.redirect;
|
| 433 |
}
|
| 434 |
})
|
| 435 |
+
.catch(error => console.error('Ошибка автовхода:', error));
|
| 436 |
}
|
| 437 |
|
| 438 |
document.getElementById('login-form').addEventListener('submit', function(e) {
|
| 439 |
e.preventDefault();
|
| 440 |
const formData = new FormData(this);
|
|
|
|
|
|
|
|
|
|
| 441 |
fetch('/', {
|
| 442 |
method: 'POST',
|
| 443 |
body: formData
|
|
|
|
| 450 |
localStorage.setItem('zeusCredentials', JSON.stringify({ username, password }));
|
| 451 |
window.location.href = data.redirect;
|
| 452 |
} else {
|
| 453 |
+
document.getElementById('flash-messages').innerHTML = `<div class="flash">${data.message}</div>`;
|
| 454 |
}
|
| 455 |
})
|
| 456 |
.catch(error => {
|
| 457 |
+
document.getElementById('flash-messages').innerHTML = `<div class="flash">Ошибка соединения!</div>`;
|
| 458 |
});
|
| 459 |
});
|
| 460 |
</script>
|
|
|
|
| 463 |
'''
|
| 464 |
return render_template_string(html)
|
| 465 |
|
|
|
|
| 466 |
@app.route('/dashboard', methods=['GET', 'POST'])
|
| 467 |
def dashboard():
|
| 468 |
if 'username' not in session:
|
| 469 |
+
flash('Пожалуйста, войдите в систему!')
|
| 470 |
return redirect(url_for('login'))
|
| 471 |
|
| 472 |
username = session['username']
|
| 473 |
data = load_data()
|
| 474 |
+
if username not in data['users']:
|
| 475 |
session.pop('username', None)
|
| 476 |
+
flash('Пользователь не найден!')
|
|
|
|
| 477 |
return redirect(url_for('login'))
|
| 478 |
|
| 479 |
+
user_files = sorted(data['users'][username]['files'], key=lambda x: x['upload_date'], reverse=True)
|
| 480 |
+
|
| 481 |
if request.method == 'POST':
|
| 482 |
files = request.files.getlist('files')
|
| 483 |
+
if files and len(files) > 20:
|
| 484 |
+
flash('Максимум 20 файлов за раз!')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
return redirect(url_for('dashboard'))
|
| 486 |
|
| 487 |
+
if files:
|
| 488 |
+
os.makedirs('uploads', exist_ok=True)
|
| 489 |
+
api = HfApi()
|
| 490 |
+
temp_files = []
|
| 491 |
|
| 492 |
+
for file in files:
|
| 493 |
+
if file and file.filename:
|
| 494 |
+
filename = secure_filename(file.filename)
|
| 495 |
+
temp_path = os.path.join('uploads', filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 496 |
file.save(temp_path)
|
| 497 |
+
temp_files.append((temp_path, filename))
|
| 498 |
+
|
| 499 |
+
for temp_path, filename in temp_files:
|
| 500 |
+
file_path = f"cloud_files/{username}/{filename}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 501 |
api.upload_file(
|
| 502 |
path_or_fileobj=temp_path,
|
| 503 |
+
path_in_repo=file_path,
|
| 504 |
repo_id=REPO_ID,
|
| 505 |
repo_type="dataset",
|
| 506 |
token=HF_TOKEN_WRITE,
|
| 507 |
+
commit_message=f"Uploaded file for {username}"
|
| 508 |
)
|
| 509 |
|
| 510 |
file_info = {
|
| 511 |
'filename': filename,
|
| 512 |
+
'path': file_path,
|
| 513 |
'type': get_file_type(filename),
|
| 514 |
'upload_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 515 |
}
|
| 516 |
+
data['users'][username]['files'].append(file_info)
|
|
|
|
| 517 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 518 |
if os.path.exists(temp_path):
|
| 519 |
+
os.remove(temp_path)
|
|
|
|
|
|
|
|
|
|
| 520 |
|
| 521 |
+
save_data(data)
|
| 522 |
+
flash('Файлы успешно загружены!')
|
| 523 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 524 |
return redirect(url_for('dashboard'))
|
| 525 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 526 |
html = '''
|
| 527 |
<!DOCTYPE html>
|
| 528 |
<html lang="ru">
|
|
|
|
| 530 |
<meta charset="UTF-8">
|
| 531 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 532 |
<title>Панель управления - Zeus Cloud</title>
|
| 533 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 534 |
<style>''' + BASE_STYLE + '''</style>
|
| 535 |
</head>
|
| 536 |
<body>
|
| 537 |
<div class="container">
|
| 538 |
<h1>Панель управления Zeus Cloud</h1>
|
| 539 |
+
<p>Пользователь: {{ username }}</p>
|
| 540 |
+
{% with messages = get_flashed_messages() %}
|
|
|
|
|
|
|
|
|
|
| 541 |
{% if messages %}
|
| 542 |
+
{% for message in messages %}
|
| 543 |
+
<div class="flash">{{ message }}</div>
|
| 544 |
{% endfor %}
|
| 545 |
{% endif %}
|
| 546 |
{% endwith %}
|
| 547 |
+
<form id="upload-form" method="POST" enctype="multipart/form-data">
|
| 548 |
+
<input type="file" name="files" multiple required accept="image/*,video/*">
|
| 549 |
+
<button type="submit" class="btn" id="upload-btn">Загрузить файлы</button>
|
|
|
|
|
|
|
|
|
|
| 550 |
</form>
|
|
|
|
| 551 |
<div id="progress-container">
|
| 552 |
+
<div id="progress-bar"></div>
|
| 553 |
</div>
|
| 554 |
+
<h2 style="margin-top: 30px;">Ваши файлы</h2>
|
| 555 |
+
<p style="text-align: center; margin-top: 10px; color: var(--accent);">Ваши файлы под надежной защитой квантовой криптографии</p>
|
| 556 |
<div class="file-grid">
|
| 557 |
{% for file in user_files %}
|
| 558 |
<div class="file-item">
|
| 559 |
+
{% if file['type'] == 'video' %}
|
| 560 |
+
<video class="file-preview" preload="metadata" muted loading="lazy" onclick="openModal('https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}', true)">
|
| 561 |
+
<source src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}" type="video/mp4">
|
| 562 |
+
</video>
|
| 563 |
+
{% elif file['type'] == 'image' %}
|
| 564 |
+
<img class="file-preview" src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}" alt="{{ file['filename'] }}" loading="lazy" onclick="openModal(this.src, false)">
|
| 565 |
+
{% else %}
|
| 566 |
+
<p>{{ file['filename'] }}</p>
|
| 567 |
+
{% endif %}
|
| 568 |
+
<p>{{ file['upload_date'] }}</p>
|
| 569 |
+
<a href="{{ url_for('download_file', file_path=file['path'], filename=file['filename']) }}" class="btn download-btn">Скачать</a>
|
| 570 |
+
<a href="{{ url_for('delete_file', file_path=file['path']) }}" class="btn delete-btn" onclick="return confirm('Вы уверены, что хотите удалить этот файл?');">Удалить</a>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 571 |
</div>
|
| 572 |
{% endfor %}
|
| 573 |
{% if not user_files %}
|
| 574 |
+
<p>Вы еще не загрузили ни одного файла.</p>
|
| 575 |
{% endif %}
|
| 576 |
</div>
|
| 577 |
+
<a href="{{ url_for('logout') }}" class="btn" style="margin-top: 20px;" id="logout-btn">Выйти</a>
|
| 578 |
</div>
|
| 579 |
+
<div class="modal" id="mediaModal" onclick="closeModal(event)">
|
| 580 |
+
<div id="modalContent"></div>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 581 |
</div>
|
|
|
|
| 582 |
<script>
|
| 583 |
+
function openModal(src, isVideo) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 584 |
const modal = document.getElementById('mediaModal');
|
| 585 |
+
const modalContent = document.getElementById('modalContent');
|
| 586 |
+
if (isVideo) {
|
| 587 |
+
modalContent.innerHTML = `<video controls autoplay><source src="${src}" type="video/mp4"></video>`;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 588 |
} else {
|
| 589 |
+
modalContent.innerHTML = `<img src="${src}">`;
|
|
|
|
|
|
|
| 590 |
}
|
| 591 |
modal.style.display = 'flex';
|
|
|
|
| 592 |
}
|
| 593 |
+
function closeModal(event) {
|
|
|
|
| 594 |
const modal = document.getElementById('mediaModal');
|
| 595 |
+
if (event.target === modal) { // Закрывать только при клике на фон
|
| 596 |
+
modal.style.display = 'none';
|
| 597 |
+
const video = modal.querySelector('video');
|
| 598 |
+
if (video) {
|
| 599 |
+
video.pause();
|
| 600 |
+
}
|
| 601 |
+
modalContent.innerHTML = ''; // Очистить содержимое
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 602 |
}
|
| 603 |
+
}
|
|
|
|
| 604 |
|
| 605 |
const form = document.getElementById('upload-form');
|
| 606 |
const progressBar = document.getElementById('progress-bar');
|
|
|
|
| 609 |
|
| 610 |
form.addEventListener('submit', function(e) {
|
| 611 |
e.preventDefault();
|
| 612 |
+
const files = form.querySelector('input[type="file"]').files;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 613 |
if (files.length > 20) {
|
| 614 |
+
alert('Максимум 20 файлов за раз!');
|
| 615 |
return;
|
| 616 |
}
|
| 617 |
+
if (files.length === 0) {
|
| 618 |
+
alert('Пожалуйста, выберите файлы для загрузки.');
|
| 619 |
+
return;
|
| 620 |
+
}
|
| 621 |
|
| 622 |
const formData = new FormData(form);
|
| 623 |
progressContainer.style.display = 'block';
|
| 624 |
progressBar.style.width = '0%';
|
|
|
|
| 625 |
uploadBtn.disabled = true;
|
|
|
|
|
|
|
| 626 |
|
| 627 |
const xhr = new XMLHttpRequest();
|
| 628 |
xhr.open('POST', '/dashboard', true);
|
| 629 |
|
| 630 |
xhr.upload.onprogress = function(event) {
|
| 631 |
if (event.lengthComputable) {
|
| 632 |
+
const percent = (event.loaded / event.total) * 100;
|
| 633 |
progressBar.style.width = percent + '%';
|
|
|
|
| 634 |
}
|
| 635 |
};
|
| 636 |
|
| 637 |
xhr.onload = function() {
|
| 638 |
+
uploadBtn.disabled = false;
|
| 639 |
+
progressContainer.style.display = 'none';
|
| 640 |
+
progressBar.style.width = '0%';
|
| 641 |
+
if (xhr.status === 200) {
|
| 642 |
+
// Не перезагружаем страницу, а обновляем флеш-сообщения или список файлов динамически, если возможно
|
| 643 |
+
// Для простоты пока оставим перезагрузку
|
| 644 |
+
location.reload();
|
| 645 |
+
} else {
|
| 646 |
+
alert('Ошибка загрузки!');
|
| 647 |
+
}
|
| 648 |
};
|
| 649 |
|
| 650 |
xhr.onerror = function() {
|
| 651 |
+
alert('Ошибка соединения!');
|
| 652 |
progressContainer.style.display = 'none';
|
| 653 |
+
progressBar.style.width = '0%';
|
| 654 |
uploadBtn.disabled = false;
|
|
|
|
| 655 |
};
|
| 656 |
|
| 657 |
xhr.send(formData);
|
|
|
|
| 659 |
|
| 660 |
document.getElementById('logout-btn').addEventListener('click', function(e) {
|
| 661 |
e.preventDefault();
|
| 662 |
+
localStorage.removeItem('zeusCredentials');
|
| 663 |
+
window.location.href = '/logout';
|
| 664 |
});
|
| 665 |
</script>
|
| 666 |
</body>
|
|
|
|
| 668 |
'''
|
| 669 |
return render_template_string(html, username=username, user_files=user_files, repo_id=REPO_ID)
|
| 670 |
|
|
|
|
| 671 |
@app.route('/download/<path:file_path>/<filename>')
|
| 672 |
def download_file(file_path, filename):
|
| 673 |
if 'username' not in session:
|
| 674 |
+
flash('Пожалуйста, войдите в систему!')
|
| 675 |
return redirect(url_for('login'))
|
| 676 |
|
| 677 |
username = session['username']
|
| 678 |
data = load_data()
|
| 679 |
+
if username not in data['users']:
|
| 680 |
session.pop('username', None)
|
| 681 |
+
flash('Пользователь не найден!')
|
|
|
|
| 682 |
return redirect(url_for('login'))
|
| 683 |
|
| 684 |
+
# Проверка доступа для обычного пользователя
|
| 685 |
+
user_files = data['users'][username]['files']
|
| 686 |
+
if not any(file['path'] == file_path for file in user_files):
|
| 687 |
+
# Разрешаем скачивание админу, если он залогинен (проверка в админ панели)
|
| 688 |
+
# Но здесь обычный пользователь, ему нельзя
|
| 689 |
+
is_admin_route = request.referrer and 'admhosto' in request.referrer
|
| 690 |
+
if not is_admin_route: # Если это не админ пытается скачать со своей страницы
|
| 691 |
+
flash('У вас нет доступа к этому файлу!')
|
| 692 |
+
return redirect(url_for('dashboard'))
|
| 693 |
+
# Если это админ, доступ разрешен (неявно, т.к. проверка выше не сработает)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 694 |
|
|
|
|
|
|
|
| 695 |
|
| 696 |
+
file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{file_path}?download=true"
|
| 697 |
try:
|
| 698 |
+
api = HfApi()
|
| 699 |
+
# Использование токена для скачивания, если репозиторий приватный
|
| 700 |
+
headers = {}
|
| 701 |
+
if HF_TOKEN_READ:
|
| 702 |
+
headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
|
| 703 |
+
|
| 704 |
+
response = requests.get(file_url, headers=headers, stream=True)
|
| 705 |
+
response.raise_for_status() # Проверка на ошибки HTTP
|
| 706 |
+
|
| 707 |
+
file_content = BytesIO(response.content)
|
| 708 |
+
return send_file(
|
| 709 |
+
file_content,
|
| 710 |
+
as_attachment=True,
|
| 711 |
+
download_name=filename,
|
| 712 |
+
mimetype='application/octet-stream' # Общий тип для скачивания
|
| 713 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 714 |
except requests.exceptions.RequestException as e:
|
| 715 |
+
logging.error(f"Error downloading file from HF: {e}")
|
| 716 |
+
flash('Ошибка скачивания файла!')
|
| 717 |
+
# Определяем, куда редиректить: на дашборд или админку
|
| 718 |
+
if request.referrer and 'admhosto' in request.referrer:
|
| 719 |
+
return redirect(url_for('admin_user_files', username=file_path.split('/')[1])) # Получаем username из пути
|
| 720 |
+
else:
|
| 721 |
+
return redirect(url_for('dashboard'))
|
| 722 |
except Exception as e:
|
| 723 |
+
logging.error(f"Unexpected error during download: {e}")
|
| 724 |
+
flash('Произошла непредвиденная ошибка при скачивании файла.')
|
| 725 |
+
if request.referrer and 'admhosto' in request.referrer:
|
| 726 |
+
return redirect(url_for('admin_user_files', username=file_path.split('/')[1]))
|
| 727 |
+
else:
|
| 728 |
+
return redirect(url_for('dashboard'))
|
| 729 |
|
| 730 |
|
| 731 |
@app.route('/delete/<path:file_path>')
|
| 732 |
def delete_file(file_path):
|
| 733 |
if 'username' not in session:
|
| 734 |
+
flash('Пожалуйста, войдите в систему!')
|
| 735 |
return redirect(url_for('login'))
|
| 736 |
|
| 737 |
username = session['username']
|
| 738 |
data = load_data()
|
| 739 |
+
if username not in data['users']:
|
| 740 |
session.pop('username', None)
|
| 741 |
+
flash('Пользователь не найден!')
|
|
|
|
| 742 |
return redirect(url_for('login'))
|
| 743 |
|
| 744 |
+
user_files = data['users'][username]['files']
|
| 745 |
+
file_to_delete = next((file for file in user_files if file['path'] == file_path), None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 746 |
|
| 747 |
+
if not file_to_delete:
|
| 748 |
+
flash('Файл не найден!')
|
| 749 |
return redirect(url_for('dashboard'))
|
| 750 |
|
| 751 |
try:
|
| 752 |
api = HfApi()
|
|
|
|
| 753 |
api.delete_file(
|
| 754 |
path_in_repo=file_path,
|
| 755 |
repo_id=REPO_ID,
|
| 756 |
repo_type="dataset",
|
| 757 |
token=HF_TOKEN_WRITE,
|
| 758 |
+
commit_message=f"Deleted file {file_path} for {username}"
|
| 759 |
)
|
| 760 |
+
data['users'][username]['files'] = [f for f in user_files if f['path'] != file_path]
|
|
|
|
|
|
|
|
|
|
| 761 |
save_data(data)
|
| 762 |
+
flash('Файл успешно удален!')
|
|
|
|
| 763 |
except Exception as e:
|
| 764 |
+
logging.error(f"Error deleting file: {e}")
|
| 765 |
+
flash('Ошибка удаления файла!')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 766 |
|
| 767 |
return redirect(url_for('dashboard'))
|
| 768 |
|
| 769 |
@app.route('/logout')
|
| 770 |
def logout():
|
| 771 |
session.pop('username', None)
|
| 772 |
+
# Дополнительно очищаем localStorage на клиенте через редирект
|
| 773 |
+
# Простой редирект, JS на странице логина уже обрабатывает выход
|
| 774 |
return redirect(url_for('login'))
|
| 775 |
|
| 776 |
|
| 777 |
@app.route('/admhosto')
|
| 778 |
def admin_panel():
|
| 779 |
+
# Здесь можно добавить проверку админского пароля или сессии
|
|
|
|
|
|
|
| 780 |
data = load_data()
|
| 781 |
+
users = data['users']
|
|
|
|
|
|
|
|
|
|
| 782 |
|
| 783 |
html = '''
|
| 784 |
<!DOCTYPE html>
|
|
|
|
| 786 |
<head>
|
| 787 |
<meta charset="UTF-8">
|
| 788 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 789 |
+
<title>Админ-панель - Zeus Cloud</title>
|
| 790 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 791 |
<style>''' + BASE_STYLE + '''</style>
|
| 792 |
</head>
|
| 793 |
<body>
|
| 794 |
<div class="container">
|
| 795 |
+
<h1>Админ-панель Zeus Cloud</h1>
|
|
|
|
| 796 |
<h2>Список пользователей</h2>
|
| 797 |
<div class="user-list">
|
| 798 |
{% for username, user_data in users.items() %}
|
| 799 |
<div class="user-item">
|
| 800 |
<a href="{{ url_for('admin_user_files', username=username) }}">{{ username }}</a>
|
| 801 |
+
<p>Дата регистрации: {{ user_data.get('created_at', 'N/A') }}</p>
|
| 802 |
<p>Количество файлов: {{ user_data.get('files', []) | length }}</p>
|
| 803 |
+
<!-- Добавить кнопку удаления пользователя -->
|
| 804 |
+
<form method="POST" action="{{ url_for('admin_delete_user', username=username) }}" style="display: inline; margin-left: 10px;" onsubmit="return confirm('Вы уверены, что хотите удалить пользователя {{ username }} и все его файлы? Это действие необратимо!');">
|
| 805 |
+
<button type="submit" class="btn delete-btn" style="padding: 5px 10px; font-size: 0.9em;">Удалить</button>
|
| 806 |
+
</form>
|
| 807 |
</div>
|
| 808 |
{% endfor %}
|
| 809 |
{% if not users %}
|
| 810 |
<p>Пользователей пока нет.</p>
|
| 811 |
{% endif %}
|
| 812 |
</div>
|
| 813 |
+
{% with messages = get_flashed_messages() %}
|
| 814 |
+
{% if messages %}
|
| 815 |
+
<div style="margin-top: 20px;">
|
| 816 |
+
{% for message in messages %}
|
| 817 |
+
<div class="flash">{{ message }}</div>
|
| 818 |
+
{% endfor %}
|
| 819 |
+
</div>
|
| 820 |
+
{% endif %}
|
| 821 |
+
{% endwith %}
|
| 822 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 823 |
</body>
|
| 824 |
</html>
|
| 825 |
'''
|
|
|
|
| 827 |
|
| 828 |
@app.route('/admhosto/user/<username>')
|
| 829 |
def admin_user_files(username):
|
| 830 |
+
# Здесь можно добавить проверку админского пароля или сессии
|
| 831 |
data = load_data()
|
| 832 |
+
if username not in data['users']:
|
| 833 |
+
flash('Пользователь не найден!')
|
| 834 |
return redirect(url_for('admin_panel'))
|
| 835 |
|
| 836 |
+
user_files = sorted(data['users'][username].get('files', []), key=lambda x: x.get('upload_date', ''), reverse=True)
|
|
|
|
| 837 |
|
| 838 |
html = '''
|
| 839 |
<!DOCTYPE html>
|
|
|
|
| 842 |
<meta charset="UTF-8">
|
| 843 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 844 |
<title>Файлы пользователя {{ username }} - Zeus Cloud</title>
|
| 845 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 846 |
+
<style>''' + BASE_STYLE + '''</style>
|
| 847 |
</head>
|
| 848 |
<body>
|
| 849 |
<div class="container">
|
| 850 |
+
<h1>Файлы пользователя: {{ username }}</h1>
|
| 851 |
+
{% with messages = get_flashed_messages() %}
|
|
|
|
| 852 |
{% if messages %}
|
| 853 |
+
{% for message in messages %}
|
| 854 |
+
<div class="flash">{{ message }}</div>
|
| 855 |
{% endfor %}
|
| 856 |
{% endif %}
|
| 857 |
{% endwith %}
|
|
|
|
| 858 |
<div class="file-grid">
|
| 859 |
{% for file in user_files %}
|
| 860 |
+
<div class="file-item">
|
| 861 |
+
{% if file.get('type') == 'video' %}
|
| 862 |
+
<video class="file-preview" preload="metadata" muted loading="lazy" onclick="openModal('https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}?download=true', true)">
|
| 863 |
+
<source src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}?download=true" type="video/mp4">
|
| 864 |
+
</video>
|
| 865 |
+
{% elif file.get('type') == 'image' %}
|
| 866 |
+
<img class="file-preview" src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}?download=true" alt="{{ file['filename'] }}" loading="lazy" onclick="openModal(this.src, false)">
|
| 867 |
+
{% else %}
|
| 868 |
+
<p>{{ file.get('filename', 'N/A') }}</p>
|
| 869 |
+
{% endif %}
|
| 870 |
+
<p>{{ file.get('upload_date', 'N/A') }}</p>
|
| 871 |
+
<a href="{{ url_for('download_file', file_path=file['path'], filename=file['filename']) }}" class="btn download-btn">Скачать</a>
|
| 872 |
+
<!-- Добавить кнопку удаления файла для админа -->
|
| 873 |
+
<form method="POST" action="{{ url_for('admin_delete_file', username=username, file_path=file['path']) }}" style="display: inline; margin-left: 5px;" onsubmit="return confirm('Вы уверены, что хотите удалить этот файл?');">
|
| 874 |
+
<button type="submit" class="btn delete-btn" style="padding: 5px 10px; font-size: 0.9em;">Удалить</button>
|
| 875 |
+
</form>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 876 |
</div>
|
| 877 |
{% endfor %}
|
| 878 |
{% if not user_files %}
|
| 879 |
+
<p>У этого пользователя пока нет файлов.</p>
|
| 880 |
{% endif %}
|
| 881 |
</div>
|
| 882 |
+
<a href="{{ url_for('admin_panel') }}" class="btn" style="margin-top: 20px;">Назад к списку пользователей</a>
|
| 883 |
</div>
|
| 884 |
+
<div class="modal" id="mediaModal" onclick="closeModal(event)">
|
| 885 |
+
<div id="modalContent"></div>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 886 |
</div>
|
| 887 |
+
<script>
|
| 888 |
+
function openModal(src, isVideo) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 889 |
const modal = document.getElementById('mediaModal');
|
| 890 |
+
const modalContent = document.getElementById('modalContent');
|
| 891 |
+
// Добавляем токен, если он есть, для приватных репо
|
| 892 |
+
const tokenParam = HF_TOKEN_READ ? `?token=${HF_TOKEN_READ}` : "";
|
| 893 |
+
const finalSrc = src + tokenParam; // Добавляем параметр токена, если он есть
|
| 894 |
+
|
| 895 |
+
if (isVideo) {
|
| 896 |
+
// Добавляем download=true, если это еще не сделано
|
| 897 |
+
const videoSrc = finalSrc.includes('?download=true') ? finalSrc : finalSrc.replace('?', '?download=true&');
|
| 898 |
+
modalContent.innerHTML = `<video controls autoplay style='max-width: 95%; max-height: 95vh;'><source src="${videoSrc}" type="video/mp4"></video>`;
|
| 899 |
+
} else {
|
| 900 |
+
// Для изображений download=true обычно не нужен для отображения
|
| 901 |
+
const img_src = finalSrc.includes('?download=true') ? finalSrc : finalSrc.replace('?', '?download=true&');
|
| 902 |
+
modalContent.innerHTML = `<img src="${img_src}" style='max-width: 95%; max-height: 95vh;'>`;
|
| 903 |
}
|
| 904 |
modal.style.display = 'flex';
|
|
|
|
| 905 |
}
|
| 906 |
+
function closeModal(event) {
|
|
|
|
| 907 |
const modal = document.getElementById('mediaModal');
|
| 908 |
+
if (event.target === modal) { // Закрывать только при клике на фон
|
| 909 |
+
modal.style.display = 'none';
|
| 910 |
+
const video = modal.querySelector('video');
|
| 911 |
+
if (video) {
|
| 912 |
+
video.pause();
|
| 913 |
+
}
|
| 914 |
+
document.getElementById('modalContent').innerHTML = ''; // Очистить содержимое
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 915 |
}
|
| 916 |
+
}
|
| 917 |
+
// Переменная для токена чтения, если он нужен для прямого доступа к файлам
|
| 918 |
+
const HF_TOKEN_READ = "{{ os.getenv('HF_TOKEN_READ') or os.getenv('HF_TOKEN') }}";
|
| 919 |
</script>
|
| 920 |
</body>
|
| 921 |
</html>
|
| 922 |
'''
|
| 923 |
+
# Передаем переменные окружения в шаблон безопасным способом
|
| 924 |
+
# (Хотя в данном случае это лишь маркер для JS)
|
| 925 |
+
return render_template_string(html, username=username, user_files=user_files, repo_id=REPO_ID, os=os)
|
| 926 |
+
|
| 927 |
+
|
| 928 |
+
@app.route('/admhosto/delete_user/<username>', methods=['POST'])
|
| 929 |
+
def admin_delete_user(username):
|
| 930 |
+
# Добавить проверку админа
|
| 931 |
+
data = load_data()
|
| 932 |
+
if username not in data['users']:
|
| 933 |
+
flash('Пользователь не найден!')
|
| 934 |
+
return redirect(url_for('admin_panel'))
|
| 935 |
+
|
| 936 |
+
user_files_to_delete = data['users'][username].get('files', [])
|
| 937 |
+
|
| 938 |
+
try:
|
| 939 |
+
api = HfApi()
|
| 940 |
+
# Сначала удаляем файлы пользователя из HF Hub
|
| 941 |
+
paths_to_delete = [file['path'] for file in user_files_to_delete]
|
| 942 |
+
if paths_to_delete:
|
| 943 |
+
# Удаление папки целиком, если API поддерживает (или удалять файлы по одному)
|
| 944 |
+
# HfApi может не иметь прямого delete_folder, удаляем по одному или папку если возможно
|
| 945 |
+
# Попробуем удалить папку пользователя
|
| 946 |
+
try:
|
| 947 |
+
api.delete_folder(
|
| 948 |
+
folder_path=f"cloud_files/{username}",
|
| 949 |
+
repo_id=REPO_ID,
|
| 950 |
+
repo_type="dataset",
|
| 951 |
+
token=HF_TOKEN_WRITE,
|
| 952 |
+
commit_message=f"Deleted all files for user {username} by admin"
|
| 953 |
+
)
|
| 954 |
+
logging.info(f"Successfully deleted folder for user {username}")
|
| 955 |
+
except Exception as folder_delete_error:
|
| 956 |
+
logging.warning(f"Could not delete folder for {username}, attempting individual file deletion: {folder_delete_error}")
|
| 957 |
+
# Если удаление папки не удалось, удаляем файлы по одному
|
| 958 |
+
for file_path in paths_to_delete:
|
| 959 |
+
try:
|
| 960 |
+
api.delete_file(
|
| 961 |
+
path_in_repo=file_path,
|
| 962 |
+
repo_id=REPO_ID,
|
| 963 |
+
repo_type="dataset",
|
| 964 |
+
token=HF_TOKEN_WRITE
|
| 965 |
+
)
|
| 966 |
+
except Exception as file_delete_error:
|
| 967 |
+
logging.error(f"Error deleting file {file_path} for user {username}: {file_delete_error}")
|
| 968 |
+
# Продолжаем удаление других файлов
|
| 969 |
+
|
| 970 |
+
# Затем удаляем пользователя из базы данных
|
| 971 |
+
del data['users'][username]
|
| 972 |
+
save_data(data)
|
| 973 |
+
flash(f'Пользователь {username} и его файлы успешно удалены!')
|
| 974 |
+
logging.info(f"Admin deleted user {username} and their files.")
|
| 975 |
+
|
| 976 |
+
except Exception as e:
|
| 977 |
+
logging.error(f"Error deleting user {username}: {e}")
|
| 978 |
+
flash(f'Ошибка при удалении пользователя {username}!')
|
| 979 |
+
|
| 980 |
+
return redirect(url_for('admin_panel'))
|
| 981 |
+
|
| 982 |
+
|
| 983 |
+
@app.route('/admhosto/delete_file/<username>/<path:file_path>', methods=['POST'])
|
| 984 |
+
def admin_delete_file(username, file_path):
|
| 985 |
+
# Добавить проверку админа
|
| 986 |
+
data = load_data()
|
| 987 |
+
if username not in data['users']:
|
| 988 |
+
flash('Пользователь не найден!')
|
| 989 |
+
return redirect(url_for('admin_panel'))
|
| 990 |
+
|
| 991 |
+
user_files = data['users'][username].get('files', [])
|
| 992 |
+
file_exists_in_db = any(f['path'] == file_path for f in user_files)
|
| 993 |
+
|
| 994 |
+
if not file_exists_in_db:
|
| 995 |
+
flash('Файл не найден в базе данных пользователя!')
|
| 996 |
+
# Все равно попытаться удалить из HF на случай рассинхронизации
|
| 997 |
+
# или просто редирект
|
| 998 |
+
|
| 999 |
+
try:
|
| 1000 |
+
api = HfApi()
|
| 1001 |
+
api.delete_file(
|
| 1002 |
+
path_in_repo=file_path,
|
| 1003 |
+
repo_id=REPO_ID,
|
| 1004 |
+
repo_type="dataset",
|
| 1005 |
+
token=HF_TOKEN_WRITE,
|
| 1006 |
+
commit_message=f"Admin deleted file {file_path} for user {username}"
|
| 1007 |
+
)
|
| 1008 |
+
|
| 1009 |
+
# Обновляем базу данных, даже если файла там не было (на всякий случай)
|
| 1010 |
+
data['users'][username]['files'] = [f for f in user_files if f['path'] != file_path]
|
| 1011 |
+
save_data(data)
|
| 1012 |
+
flash('Файл успешно удален!')
|
| 1013 |
+
logging.info(f"Admin deleted file {file_path} for user {username}")
|
| 1014 |
+
|
| 1015 |
+
except Exception as e:
|
| 1016 |
+
logging.error(f"Error deleting file {file_path} by admin: {e}")
|
| 1017 |
+
# Проверить тип ошибки, возможно файл уже удален на HF
|
| 1018 |
+
flash('Ошибка удаления файла!')
|
| 1019 |
+
|
| 1020 |
+
return redirect(url_for('admin_user_files', username=username))
|
| 1021 |
|
| 1022 |
|
| 1023 |
if __name__ == '__main__':
|
| 1024 |
+
# Проверка наличия токенов при старте
|
| 1025 |
+
if not HF_TOKEN_WRITE:
|
| 1026 |
+
logging.warning("HF_TOKEN (write access) is not set. File uploads and deletions will fail.")
|
| 1027 |
+
if not HF_TOKEN_READ:
|
| 1028 |
+
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.")
|
| 1029 |
|
| 1030 |
+
# Запуск периодического бэкапа в отдельном потоке
|
| 1031 |
+
# Убедимся, что бэкап запускается только если есть токен для записи
|
| 1032 |
if HF_TOKEN_WRITE:
|
| 1033 |
+
threading.Thread(target=periodic_backup, daemon=True).start()
|
|
|
|
|
|
|
| 1034 |
else:
|
| 1035 |
+
logging.warning("Periodic backup disabled because HF_TOKEN (write access) is not set.")
|
| 1036 |
+
|
| 1037 |
+
# Запуск Flask приложения
|
| 1038 |
+
app.run(debug=False, host='0.0.0.0', port=7860)
|
| 1039 |
|
|
|
|
|
|
|
|
|
|
|
|