Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
from flask import Flask, render_template_string, request, redirect, url_for, session, flash, send_file, jsonify
|
| 2 |
from flask_caching import Cache
|
| 3 |
import json
|
|
@@ -12,46 +14,95 @@ import requests
|
|
| 12 |
from io import BytesIO
|
| 13 |
|
| 14 |
app = Flask(__name__)
|
| 15 |
-
|
|
|
|
| 16 |
DATA_FILE = 'cloud_data.json'
|
| 17 |
-
REPO_ID = "Eluza133/Z1e1u"
|
| 18 |
-
HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
|
| 19 |
-
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE
|
| 20 |
-
REGISTRATION_CODE
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
|
| 23 |
-
logging.basicConfig(level=logging.INFO)
|
| 24 |
|
| 25 |
-
#
|
| 26 |
-
@cache.memoize(timeout=300)
|
| 27 |
def load_data():
|
|
|
|
| 28 |
try:
|
|
|
|
| 29 |
download_db_from_hf()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
with open(DATA_FILE, 'r', encoding='utf-8') as file:
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
except Exception as e:
|
| 40 |
-
logging.error(f"
|
|
|
|
| 41 |
return {'users': {}, 'files': {}}
|
| 42 |
|
| 43 |
def save_data(data):
|
|
|
|
| 44 |
try:
|
|
|
|
|
|
|
|
|
|
| 45 |
with open(DATA_FILE, 'w', encoding='utf-8') as file:
|
| 46 |
json.dump(data, file, ensure_ascii=False, indent=4)
|
|
|
|
|
|
|
|
|
|
| 47 |
upload_db_to_hf()
|
| 48 |
-
|
| 49 |
-
|
|
|
|
| 50 |
except Exception as e:
|
| 51 |
-
logging.error(f"
|
| 52 |
-
raise
|
|
|
|
| 53 |
|
| 54 |
def upload_db_to_hf():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
try:
|
| 56 |
api = HfApi()
|
| 57 |
api.upload_file(
|
|
@@ -60,229 +111,506 @@ def upload_db_to_hf():
|
|
| 60 |
repo_id=REPO_ID,
|
| 61 |
repo_type="dataset",
|
| 62 |
token=HF_TOKEN_WRITE,
|
| 63 |
-
commit_message=f"
|
| 64 |
)
|
| 65 |
-
logging.info("
|
| 66 |
except Exception as e:
|
| 67 |
-
logging.error(f"
|
| 68 |
|
| 69 |
def download_db_from_hf():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
try:
|
|
|
|
| 71 |
hf_hub_download(
|
| 72 |
repo_id=REPO_ID,
|
| 73 |
filename=DATA_FILE,
|
| 74 |
repo_type="dataset",
|
| 75 |
token=HF_TOKEN_READ,
|
| 76 |
-
local_dir=".",
|
| 77 |
-
local_dir_use_symlinks=False
|
|
|
|
|
|
|
| 78 |
)
|
| 79 |
-
logging.info("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
except Exception as e:
|
| 81 |
-
logging.error(f"
|
|
|
|
| 82 |
if not os.path.exists(DATA_FILE):
|
| 83 |
-
|
| 84 |
-
|
|
|
|
| 85 |
|
| 86 |
def periodic_backup():
|
|
|
|
|
|
|
| 87 |
while True:
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
def get_file_type(filename):
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
return 'video'
|
| 96 |
-
elif
|
| 97 |
return 'image'
|
|
|
|
|
|
|
| 98 |
return 'other'
|
| 99 |
|
|
|
|
| 100 |
BASE_STYLE = '''
|
|
|
|
|
|
|
|
|
|
| 101 |
:root {
|
| 102 |
-
--primary:
|
| 103 |
-
--secondary:
|
| 104 |
-
--accent:
|
| 105 |
-
|
| 106 |
-
--
|
| 107 |
-
--
|
| 108 |
-
--
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
--text-dark: #e8e1ff;
|
| 111 |
-
--
|
| 112 |
-
--
|
| 113 |
-
--
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
|
|
|
|
|
|
|
|
|
| 122 |
}
|
|
|
|
| 123 |
body.dark {
|
| 124 |
background: var(--background-dark);
|
| 125 |
color: var(--text-dark);
|
| 126 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
.container {
|
| 128 |
-
margin:
|
| 129 |
max-width: 1200px;
|
| 130 |
-
padding:
|
| 131 |
-
background: var(--card-bg);
|
| 132 |
-
border-radius:
|
| 133 |
-
box-shadow: var(--shadow);
|
|
|
|
|
|
|
|
|
|
| 134 |
}
|
| 135 |
body.dark .container {
|
| 136 |
background: var(--card-bg-dark);
|
|
|
|
|
|
|
| 137 |
}
|
|
|
|
| 138 |
h1 {
|
| 139 |
-
font-size:
|
| 140 |
font-weight: 800;
|
| 141 |
text-align: center;
|
| 142 |
-
margin-bottom:
|
| 143 |
background: linear-gradient(135deg, var(--primary), var(--accent));
|
| 144 |
-webkit-background-clip: text;
|
|
|
|
| 145 |
color: transparent;
|
| 146 |
}
|
|
|
|
| 147 |
h2 {
|
| 148 |
-
font-size: 1.
|
| 149 |
-
|
|
|
|
|
|
|
| 150 |
color: var(--text-light);
|
|
|
|
|
|
|
| 151 |
}
|
| 152 |
body.dark h2 {
|
| 153 |
color: var(--text-dark);
|
|
|
|
| 154 |
}
|
| 155 |
-
|
|
|
|
| 156 |
width: 100%;
|
| 157 |
-
padding:
|
| 158 |
margin: 12px 0;
|
| 159 |
-
border:
|
| 160 |
-
border-radius:
|
| 161 |
-
background: var(--
|
| 162 |
color: var(--text-light);
|
| 163 |
-
font-size:
|
| 164 |
-
box-shadow: inset 0
|
|
|
|
|
|
|
| 165 |
}
|
| 166 |
-
body.dark input, body.dark textarea {
|
|
|
|
| 167 |
color: var(--text-dark);
|
|
|
|
| 168 |
}
|
| 169 |
-
|
|
|
|
| 170 |
outline: none;
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
}
|
|
|
|
|
|
|
|
|
|
| 173 |
.btn {
|
| 174 |
padding: 14px 28px;
|
| 175 |
-
background: var(--primary);
|
| 176 |
-
color: white;
|
| 177 |
border: none;
|
| 178 |
-
border-radius:
|
| 179 |
cursor: pointer;
|
| 180 |
font-size: 1.1em;
|
| 181 |
font-weight: 600;
|
| 182 |
-
transition: var(--transition);
|
| 183 |
-
box-shadow:
|
| 184 |
-
display: inline-
|
|
|
|
|
|
|
| 185 |
text-decoration: none;
|
|
|
|
|
|
|
| 186 |
}
|
| 187 |
.btn:hover {
|
| 188 |
-
transform:
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
}
|
|
|
|
|
|
|
| 191 |
.download-btn {
|
| 192 |
-
background: var(--
|
| 193 |
margin-top: 10px;
|
| 194 |
}
|
| 195 |
.download-btn:hover {
|
| 196 |
-
background:
|
| 197 |
}
|
|
|
|
| 198 |
.delete-btn {
|
| 199 |
background: var(--delete-color);
|
| 200 |
margin-top: 10px;
|
| 201 |
}
|
| 202 |
.delete-btn:hover {
|
| 203 |
-
background:
|
| 204 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
.flash {
|
| 206 |
-
|
|
|
|
|
|
|
| 207 |
text-align: center;
|
| 208 |
-
|
|
|
|
| 209 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
.file-grid {
|
| 211 |
display: grid;
|
| 212 |
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
| 213 |
-
gap:
|
| 214 |
-
margin-top:
|
| 215 |
}
|
|
|
|
|
|
|
| 216 |
.user-list {
|
| 217 |
margin-top: 20px;
|
|
|
|
|
|
|
|
|
|
| 218 |
}
|
|
|
|
| 219 |
.user-item {
|
| 220 |
-
padding:
|
| 221 |
-
background: var(--card-bg);
|
| 222 |
-
border-radius:
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
|
|
|
| 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
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
@media (max-width: 768px) {
|
| 242 |
-
.file-grid {
|
| 243 |
-
grid-template-columns: repeat(2, 1fr);
|
| 244 |
-
}
|
| 245 |
}
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
grid-template-columns: 1fr;
|
| 249 |
-
}
|
| 250 |
}
|
|
|
|
|
|
|
|
|
|
| 251 |
.file-item {
|
| 252 |
-
background: var(--card-bg);
|
| 253 |
padding: 15px;
|
| 254 |
-
border-radius:
|
| 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:
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
}
|
| 273 |
-
.file-
|
| 274 |
font-size: 0.9em;
|
| 275 |
margin: 5px 0;
|
|
|
|
| 276 |
}
|
| 277 |
-
.file-
|
| 278 |
-
|
| 279 |
-
text-decoration: none;
|
| 280 |
}
|
| 281 |
-
.file-
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
}
|
|
|
|
|
|
|
|
|
|
| 284 |
.modal {
|
| 285 |
-
display: none;
|
| 286 |
position: fixed;
|
| 287 |
top: 0;
|
| 288 |
left: 0;
|
|
@@ -292,125 +620,242 @@ body.dark .file-item {
|
|
| 292 |
z-index: 2000;
|
| 293 |
justify-content: center;
|
| 294 |
align-items: center;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
}
|
| 296 |
.modal img, .modal video {
|
| 297 |
-
|
| 298 |
-
max-
|
|
|
|
| 299 |
object-fit: contain;
|
| 300 |
-
border-radius:
|
| 301 |
-
box-shadow:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
}
|
|
|
|
|
|
|
|
|
|
| 303 |
#progress-container {
|
| 304 |
width: 100%;
|
| 305 |
-
background: var(--
|
| 306 |
-
border-radius:
|
| 307 |
-
margin:
|
| 308 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
}
|
| 310 |
#progress-bar {
|
| 311 |
width: 0%;
|
| 312 |
height: 20px;
|
| 313 |
-
background: var(--primary);
|
| 314 |
-
border-radius:
|
| 315 |
-
transition: width 0.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
}
|
| 317 |
'''
|
| 318 |
|
|
|
|
|
|
|
| 319 |
@app.route('/register', methods=['GET', 'POST'])
|
| 320 |
def register():
|
|
|
|
| 321 |
if request.method == 'POST':
|
| 322 |
-
username = request.form.get('username')
|
| 323 |
-
password = request.form.get('password')
|
| 324 |
-
code = request.form.get('code')
|
| 325 |
-
|
| 326 |
-
data = load_data()
|
| 327 |
-
|
| 328 |
-
if username in data['users']:
|
| 329 |
-
flash('Пользователь с таким логином уже существует!')
|
| 330 |
-
return redirect(url_for('register'))
|
| 331 |
-
|
| 332 |
-
if code != REGISTRATION_CODE:
|
| 333 |
-
flash('Неверный регистрационный код!')
|
| 334 |
-
return redirect(url_for('register'))
|
| 335 |
-
|
| 336 |
if not username or not password:
|
| 337 |
-
flash('Логин и пароль об
|
| 338 |
return redirect(url_for('register'))
|
| 339 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
data['users'][username] = {
|
| 341 |
-
'password': password,
|
| 342 |
'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
| 343 |
'files': []
|
| 344 |
}
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
html = '''
|
| 351 |
<!DOCTYPE html>
|
| 352 |
-
<html lang="
|
| 353 |
<head>
|
| 354 |
<meta charset="UTF-8">
|
| 355 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 356 |
<title>Регистрация - Zeus Cloud</title>
|
| 357 |
-
<
|
| 358 |
-
<style>''' + BASE_STYLE + '''</style>
|
| 359 |
</head>
|
| 360 |
-
<body>
|
|
|
|
|
|
|
|
|
|
| 361 |
<div class="container">
|
| 362 |
<h1>Регистрация в Zeus Cloud</h1>
|
| 363 |
-
{% with messages = get_flashed_messages() %}
|
| 364 |
{% if messages %}
|
| 365 |
-
{% for message in messages %}
|
| 366 |
-
<div class="flash">{{ message }}</div>
|
| 367 |
{% endfor %}
|
| 368 |
{% endif %}
|
| 369 |
{% endwith %}
|
| 370 |
<form method="POST" id="register-form">
|
| 371 |
-
<input type="text" name="username" placeholder="
|
| 372 |
-
<input type="password" name="password" placeholder="
|
| 373 |
-
<
|
| 374 |
-
<button type="submit" class="btn">Зарегистрироваться</button>
|
| 375 |
</form>
|
| 376 |
-
<p style="margin-top: 20px;">Уже есть аккаунт? <a href="{{ url_for('login') }}">Войдите</a></p>
|
| 377 |
</div>
|
|
|
|
| 378 |
</body>
|
| 379 |
</html>
|
| 380 |
'''
|
| 381 |
-
|
|
|
|
| 382 |
|
| 383 |
@app.route('/', methods=['GET', 'POST'])
|
| 384 |
def login():
|
|
|
|
| 385 |
if request.method == 'POST':
|
| 386 |
-
username = request.form.get('username')
|
| 387 |
-
password = request.form.get('password')
|
| 388 |
data = load_data()
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
return jsonify({'status': 'success', 'redirect': url_for('dashboard')})
|
| 393 |
else:
|
|
|
|
|
|
|
| 394 |
return jsonify({'status': 'error', 'message': 'Неверный логин или пароль!'})
|
| 395 |
-
|
|
|
|
| 396 |
html = '''
|
| 397 |
<!DOCTYPE html>
|
| 398 |
-
<html lang="
|
| 399 |
<head>
|
| 400 |
<meta charset="UTF-8">
|
| 401 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 402 |
-
<title>Zeus Cloud</title>
|
| 403 |
-
<
|
| 404 |
-
<style>''' + BASE_STYLE + '''</style>
|
| 405 |
</head>
|
| 406 |
-
<body>
|
|
|
|
|
|
|
|
|
|
| 407 |
<div class="container">
|
| 408 |
<h1>Zeus Cloud</h1>
|
| 409 |
<div id="flash-messages">
|
| 410 |
-
{% with messages = get_flashed_messages() %}
|
| 411 |
{% if messages %}
|
| 412 |
-
{% for message in messages %}
|
| 413 |
-
<div class="flash">{{ message }}</div>
|
| 414 |
{% endfor %}
|
| 415 |
{% endif %}
|
| 416 |
{% endwith %}
|
|
@@ -418,444 +863,790 @@ def login():
|
|
| 418 |
<form method="POST" id="login-form">
|
| 419 |
<input type="text" name="username" placeholder="Введите логин" required>
|
| 420 |
<input type="password" name="password" placeholder="Введите пароль" required>
|
| 421 |
-
<button type="submit" class="btn">Войти</button>
|
| 422 |
</form>
|
| 423 |
<p style="margin-top: 20px;">Нет аккаунта? <a href="{{ url_for('register') }}">Зарегистрируйтесь</a></p>
|
| 424 |
</div>
|
| 425 |
<script>
|
| 426 |
-
//
|
|
|
|
|
|
|
|
|
|
| 427 |
const savedCredentials = JSON.parse(localStorage.getItem('zeusCredentials'));
|
| 428 |
-
if (savedCredentials) {
|
| 429 |
-
|
|
|
|
| 430 |
method: 'POST',
|
| 431 |
-
headers: {
|
| 432 |
-
'Content-Type': 'application/x-www-form-urlencoded',
|
| 433 |
-
},
|
| 434 |
-
body: `username=${encodeURIComponent(savedCredentials.username)}&password=${encodeURIComponent(savedCredentials.password)}`
|
| 435 |
-
})
|
| 436 |
.then(response => response.json())
|
| 437 |
-
.then(data => {
|
| 438 |
-
if (data.status === 'success') {
|
|
|
|
| 439 |
window.location.href = data.redirect;
|
| 440 |
-
}
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
|
| 445 |
-
//
|
| 446 |
-
document.getElementById('login-form').addEventListener('submit', function(e) {
|
| 447 |
-
e.preventDefault();
|
| 448 |
const formData = new FormData(this);
|
| 449 |
-
|
|
|
|
|
|
|
|
|
|
| 450 |
method: 'POST',
|
| 451 |
body: formData
|
| 452 |
-
})
|
| 453 |
.then(response => response.json())
|
| 454 |
-
.then(data => {
|
| 455 |
-
if (data.status === 'success') {
|
|
|
|
| 456 |
const username = formData.get('username');
|
| 457 |
const password = formData.get('password');
|
| 458 |
-
localStorage.setItem('zeusCredentials', JSON.stringify({ username, password }));
|
| 459 |
-
window.location.href = data.redirect;
|
| 460 |
-
} else {
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
|
|
|
|
|
|
| 468 |
</script>
|
| 469 |
</body>
|
| 470 |
</html>
|
| 471 |
'''
|
| 472 |
-
|
|
|
|
| 473 |
|
| 474 |
@app.route('/dashboard', methods=['GET', 'POST'])
|
| 475 |
def dashboard():
|
|
|
|
| 476 |
if 'username' not in session:
|
| 477 |
-
flash('Пожалуйста, войдите
|
| 478 |
return redirect(url_for('login'))
|
| 479 |
-
|
| 480 |
username = session['username']
|
| 481 |
data = load_data()
|
| 482 |
-
if username not in data
|
| 483 |
-
session.pop('username', None)
|
| 484 |
-
flash('
|
| 485 |
return redirect(url_for('login'))
|
| 486 |
-
|
| 487 |
-
user_files = sorted(data['users'][username]['files'], key=lambda x: x['upload_date'], reverse=True)
|
| 488 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
if request.method == 'POST':
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 493 |
return redirect(url_for('dashboard'))
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 504 |
file.save(temp_path)
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
'
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 533 |
|
|
|
|
| 534 |
html = '''
|
| 535 |
<!DOCTYPE html>
|
| 536 |
-
<html lang="
|
| 537 |
<head>
|
| 538 |
<meta charset="UTF-8">
|
| 539 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 540 |
-
<title>
|
| 541 |
-
<
|
| 542 |
-
<style>''' + BASE_STYLE + '''</style>
|
| 543 |
</head>
|
| 544 |
-
<body>
|
|
|
|
|
|
|
|
|
|
| 545 |
<div class="container">
|
| 546 |
-
<h1>Zeus Cloud
|
| 547 |
-
<p>Пользователь: {{ username }}</p>
|
| 548 |
-
|
|
|
|
| 549 |
{% if messages %}
|
| 550 |
-
{% for message in messages %}
|
| 551 |
-
<div class="flash">{{ message }}</div>
|
| 552 |
{% endfor %}
|
| 553 |
{% endif %}
|
| 554 |
{% endwith %}
|
|
|
|
|
|
|
| 555 |
<form id="upload-form" method="POST" enctype="multipart/form-data">
|
| 556 |
-
<input type="file" name="files" multiple required accept="image/*,video/*">
|
| 557 |
-
<button type="submit" class="btn" id="upload-btn">Загрузить
|
| 558 |
</form>
|
| 559 |
<div id="progress-container">
|
| 560 |
-
<div id="progress-bar"></div>
|
| 561 |
</div>
|
| 562 |
-
|
|
|
|
| 563 |
<div class="file-grid">
|
| 564 |
{% for file in user_files %}
|
| 565 |
<div class="file-item">
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 578 |
</div>
|
|
|
|
|
|
|
| 579 |
{% endfor %}
|
| 580 |
-
{% if not user_files %}
|
| 581 |
-
<p>У вас пока нет загруженных файлов.</p>
|
| 582 |
-
{% endif %}
|
| 583 |
</div>
|
| 584 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 585 |
</div>
|
| 586 |
-
|
| 587 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 588 |
</div>
|
|
|
|
| 589 |
<script>
|
| 590 |
-
|
|
|
|
|
|
|
|
|
|
| 591 |
const modal = document.getElementById('mediaModal');
|
| 592 |
-
const modalContent = document.getElementById('
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
modalContent.innerHTML = `<
|
| 597 |
-
}
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
|
|
|
| 607 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 608 |
const form = document.getElementById('upload-form');
|
| 609 |
const progressBar = document.getElementById('progress-bar');
|
| 610 |
const progressContainer = document.getElementById('progress-container');
|
| 611 |
const uploadBtn = document.getElementById('upload-btn');
|
|
|
|
| 612 |
|
| 613 |
-
form.addEventListener('submit', function(e) {
|
| 614 |
-
e.preventDefault();
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
|
|
|
| 618 |
return;
|
| 619 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 620 |
|
| 621 |
const formData = new FormData(form);
|
| 622 |
progressContainer.style.display = 'block';
|
| 623 |
progressBar.style.width = '0%';
|
|
|
|
| 624 |
uploadBtn.disabled = true;
|
|
|
|
| 625 |
|
| 626 |
const xhr = new XMLHttpRequest();
|
| 627 |
xhr.open('POST', '/dashboard', true);
|
|
|
|
|
|
|
| 628 |
|
| 629 |
-
xhr.upload.onprogress = function(event) {
|
| 630 |
-
if (event.lengthComputable) {
|
| 631 |
-
const percent = (event.loaded / event.total) * 100;
|
| 632 |
progressBar.style.width = percent + '%';
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 651 |
|
| 652 |
xhr.send(formData);
|
| 653 |
-
});
|
| 654 |
|
| 655 |
-
//
|
| 656 |
-
document.getElementById('logout-btn').addEventListener('click', function(e) {
|
| 657 |
-
e.preventDefault();
|
| 658 |
-
localStorage.removeItem('zeusCredentials');
|
| 659 |
-
|
| 660 |
-
|
|
|
|
| 661 |
</script>
|
| 662 |
</body>
|
| 663 |
</html>
|
| 664 |
'''
|
| 665 |
-
|
|
|
|
|
|
|
| 666 |
|
| 667 |
@app.route('/download/<path:file_path>/<filename>')
|
| 668 |
def download_file(file_path, filename):
|
|
|
|
| 669 |
if 'username' not in session:
|
| 670 |
-
flash('Пожалуйста, войдите
|
| 671 |
return redirect(url_for('login'))
|
| 672 |
-
|
| 673 |
username = session['username']
|
| 674 |
data = load_data()
|
| 675 |
-
if username not in data
|
| 676 |
session.pop('username', None)
|
| 677 |
-
flash('Пользователь не найден!')
|
| 678 |
return redirect(url_for('login'))
|
| 679 |
-
|
| 680 |
-
user_files = data['users'][username]
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 685 |
file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{file_path}"
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 690 |
return send_file(
|
| 691 |
file_content,
|
| 692 |
as_attachment=True,
|
| 693 |
-
download_name=filename,
|
| 694 |
-
mimetype='application/octet-stream'
|
| 695 |
)
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 699 |
|
| 700 |
@app.route('/delete/<path:file_path>')
|
| 701 |
def delete_file(file_path):
|
|
|
|
| 702 |
if 'username' not in session:
|
| 703 |
-
flash('Пожалуйста, войдите
|
| 704 |
return redirect(url_for('login'))
|
| 705 |
-
|
| 706 |
username = session['username']
|
| 707 |
data = load_data()
|
| 708 |
-
if username not in data
|
| 709 |
session.pop('username', None)
|
| 710 |
-
flash('Пользователь не найден!')
|
| 711 |
return redirect(url_for('login'))
|
| 712 |
-
|
| 713 |
-
user_files = data['users'][username]
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
if not
|
| 717 |
-
flash('Файл не найден!')
|
| 718 |
return redirect(url_for('dashboard'))
|
| 719 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 720 |
try:
|
| 721 |
api = HfApi()
|
|
|
|
| 722 |
api.delete_file(
|
| 723 |
path_in_repo=file_path,
|
| 724 |
repo_id=REPO_ID,
|
| 725 |
repo_type="dataset",
|
| 726 |
token=HF_TOKEN_WRITE,
|
| 727 |
-
commit_message=f"
|
| 728 |
)
|
| 729 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 730 |
save_data(data)
|
| 731 |
-
flash(
|
|
|
|
| 732 |
except Exception as e:
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
|
|
|
| 736 |
return redirect(url_for('dashboard'))
|
| 737 |
|
|
|
|
| 738 |
@app.route('/logout')
|
| 739 |
def logout():
|
| 740 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 741 |
return redirect(url_for('login'))
|
| 742 |
|
| 743 |
-
#
|
| 744 |
-
@app.route('/admhosto')
|
| 745 |
def admin_panel():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 746 |
data = load_data()
|
| 747 |
-
users = data
|
| 748 |
-
|
| 749 |
html = '''
|
| 750 |
<!DOCTYPE html>
|
| 751 |
-
<html lang="
|
| 752 |
<head>
|
| 753 |
<meta charset="UTF-8">
|
| 754 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 755 |
<title>Админ-панель - Zeus Cloud</title>
|
| 756 |
-
<
|
| 757 |
-
<style>''' + BASE_STYLE + '''</style>
|
| 758 |
</head>
|
| 759 |
-
<body>
|
|
|
|
|
|
|
|
|
|
| 760 |
<div class="container">
|
| 761 |
-
<h1>Админ-панель Zeus Cloud</h1>
|
| 762 |
<h2>Список пользователей</h2>
|
| 763 |
<div class="user-list">
|
| 764 |
-
{%
|
| 765 |
-
|
| 766 |
-
<
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 772 |
<p>Пользователей пока нет.</p>
|
| 773 |
{% endif %}
|
| 774 |
</div>
|
|
|
|
| 775 |
</div>
|
|
|
|
| 776 |
</body>
|
| 777 |
</html>
|
| 778 |
'''
|
| 779 |
-
|
|
|
|
|
|
|
| 780 |
|
| 781 |
@app.route('/admhosto/user/<username>')
|
| 782 |
def admin_user_files(username):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 783 |
data = load_data()
|
| 784 |
-
if username not in data
|
| 785 |
-
flash('Пользователь не найден!')
|
| 786 |
return redirect(url_for('admin_panel'))
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
|
|
|
|
|
|
| 790 |
html = '''
|
| 791 |
<!DOCTYPE html>
|
| 792 |
-
<html lang="
|
| 793 |
<head>
|
| 794 |
<meta charset="UTF-8">
|
| 795 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 796 |
<title>Файлы пользователя {{ username }} - Zeus Cloud</title>
|
| 797 |
-
<
|
| 798 |
-
<style>''' + BASE_STYLE + '''</style>
|
| 799 |
</head>
|
| 800 |
-
<body>
|
|
|
|
|
|
|
|
|
|
| 801 |
<div class="container">
|
| 802 |
-
<h1>Файлы пользователя: {{ username }}</h1>
|
| 803 |
-
{% with messages = get_flashed_messages() %}
|
| 804 |
{% if messages %}
|
| 805 |
-
{% for message in messages %}
|
| 806 |
-
<div class="flash">{{ message }}</div>
|
| 807 |
{% endfor %}
|
| 808 |
{% endif %}
|
| 809 |
{% endwith %}
|
|
|
|
| 810 |
<div class="file-grid">
|
| 811 |
-
|
| 812 |
<div class="file-item">
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 824 |
</div>
|
|
|
|
|
|
|
| 825 |
{% endfor %}
|
| 826 |
-
{% if not user_files %}
|
| 827 |
-
<p>У пользователя пока нет файлов.</p>
|
| 828 |
-
{% endif %}
|
| 829 |
</div>
|
| 830 |
-
|
|
|
|
| 831 |
</div>
|
| 832 |
-
|
| 833 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 834 |
</div>
|
| 835 |
-
|
| 836 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 837 |
const modal = document.getElementById('mediaModal');
|
| 838 |
-
const modalContent = document.getElementById('
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
}
|
| 844 |
modal.style.display = 'flex';
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
}
|
|
|
|
|
|
|
|
|
|
| 853 |
</script>
|
| 854 |
</body>
|
| 855 |
</html>
|
| 856 |
'''
|
| 857 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 858 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 859 |
if __name__ == '__main__':
|
| 860 |
-
|
| 861 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# IMPORTANT: Change this secret key in a real deployment! Use environment variables.
|
| 18 |
+
app.secret_key = os.getenv("FLASK_SECRET_KEY", "a-very-strong-and-random-secret-key-!@#$%^&*()")
|
| 19 |
DATA_FILE = 'cloud_data.json'
|
| 20 |
+
REPO_ID = "Eluza133/Z1e1u" # Replace with your Hugging Face repo ID if needed
|
| 21 |
+
HF_TOKEN_WRITE = os.getenv("HF_TOKEN") # Your Hugging Face write token (needs to be set as env variable)
|
| 22 |
+
HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE # Read token (defaults to write token if not set)
|
| 23 |
+
# REGISTRATION_CODE removed as requested
|
| 24 |
+
|
| 25 |
+
# --- Input Validation ---
|
| 26 |
+
# Check if essential environment variables are set
|
| 27 |
+
if not HF_TOKEN_WRITE:
|
| 28 |
+
print("CRITICAL ERROR: HF_TOKEN environment variable is not set. File uploads/backups will fail.")
|
| 29 |
+
# Depending on the deployment strategy, you might want to exit here:
|
| 30 |
+
# import sys
|
| 31 |
+
# sys.exit("Exiting due to missing Hugging Face write token.")
|
| 32 |
+
else:
|
| 33 |
+
print("INFO: HF_TOKEN found.")
|
| 34 |
+
|
| 35 |
+
if not HF_TOKEN_READ:
|
| 36 |
+
print("INFO: HF_TOKEN_READ not set, using HF_TOKEN for reads.")
|
| 37 |
+
|
| 38 |
|
| 39 |
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
|
| 40 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 41 |
|
| 42 |
+
# --- Database & Hugging Face Functions ---
|
| 43 |
+
@cache.memoize(timeout=300) # Cache DB data for 5 minutes
|
| 44 |
def load_data():
|
| 45 |
+
"""Loads data from local JSON, downloading from HF if necessary."""
|
| 46 |
try:
|
| 47 |
+
# Attempt to download the latest DB first
|
| 48 |
download_db_from_hf()
|
| 49 |
+
|
| 50 |
+
# Check if file exists after attempting download
|
| 51 |
+
if not os.path.exists(DATA_FILE):
|
| 52 |
+
logging.warning(f"{DATA_FILE} not found locally after download attempt. Initializing empty DB.")
|
| 53 |
+
return {'users': {}, 'files': {}} # Return default structure
|
| 54 |
+
|
| 55 |
+
# Load from local file
|
| 56 |
with open(DATA_FILE, 'r', encoding='utf-8') as file:
|
| 57 |
+
try:
|
| 58 |
+
data = json.load(file)
|
| 59 |
+
if not isinstance(data, dict):
|
| 60 |
+
logging.warning("Data in JSON is not a dictionary. Initializing empty structure.")
|
| 61 |
+
return {'users': {}, 'files': {}}
|
| 62 |
+
# Ensure top-level keys exist
|
| 63 |
+
data.setdefault('users', {})
|
| 64 |
+
data.setdefault('files', {}) # Although files are user-specific now, keep for potential future use
|
| 65 |
+
logging.info("Data successfully loaded from JSON.")
|
| 66 |
+
return data
|
| 67 |
+
except json.JSONDecodeError as json_err:
|
| 68 |
+
logging.error(f"Error decoding JSON from {DATA_FILE}: {json_err}. Returning empty structure.")
|
| 69 |
+
# Optionally: backup the corrupted file before overwriting
|
| 70 |
+
# os.rename(DATA_FILE, DATA_FILE + ".corrupted_" + datetime.now().strftime('%Y%m%d%H%M%S'))
|
| 71 |
+
return {'users': {}, 'files': {}} # Return default structure on decode error
|
| 72 |
except Exception as e:
|
| 73 |
+
logging.error(f"Unexpected error during data loading: {e}", exc_info=True)
|
| 74 |
+
# Fallback: if absolutely anything else goes wrong, return an empty structure
|
| 75 |
return {'users': {}, 'files': {}}
|
| 76 |
|
| 77 |
def save_data(data):
|
| 78 |
+
"""Saves data to local JSON and uploads to Hugging Face."""
|
| 79 |
try:
|
| 80 |
+
# Create directory if it doesn't exist (good practice)
|
| 81 |
+
os.makedirs(os.path.dirname(DATA_FILE) or '.', exist_ok=True)
|
| 82 |
+
|
| 83 |
with open(DATA_FILE, 'w', encoding='utf-8') as file:
|
| 84 |
json.dump(data, file, ensure_ascii=False, indent=4)
|
| 85 |
+
logging.info(f"Data successfully saved locally to {DATA_FILE}.")
|
| 86 |
+
|
| 87 |
+
# Attempt to upload to Hugging Face
|
| 88 |
upload_db_to_hf()
|
| 89 |
+
|
| 90 |
+
cache.clear() # Clear cache after successful save and upload
|
| 91 |
+
logging.info("Cache cleared after saving data.")
|
| 92 |
except Exception as e:
|
| 93 |
+
logging.error(f"Error during data saving or upload: {e}", exc_info=True)
|
| 94 |
+
# Decide if you want to re-raise the exception or handle it
|
| 95 |
+
# raise # Re-raise if the caller needs to know about the failure
|
| 96 |
|
| 97 |
def upload_db_to_hf():
|
| 98 |
+
"""Uploads the local database file to Hugging Face Hub."""
|
| 99 |
+
if not HF_TOKEN_WRITE:
|
| 100 |
+
logging.error("Cannot upload database to Hugging Face: HF_TOKEN_WRITE is not set.")
|
| 101 |
+
return # Don't proceed if the token is missing
|
| 102 |
+
if not os.path.exists(DATA_FILE):
|
| 103 |
+
logging.error(f"Cannot upload database to Hugging Face: {DATA_FILE} does not exist locally.")
|
| 104 |
+
return
|
| 105 |
+
|
| 106 |
try:
|
| 107 |
api = HfApi()
|
| 108 |
api.upload_file(
|
|
|
|
| 111 |
repo_id=REPO_ID,
|
| 112 |
repo_type="dataset",
|
| 113 |
token=HF_TOKEN_WRITE,
|
| 114 |
+
commit_message=f"Automated backup {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
|
| 115 |
)
|
| 116 |
+
logging.info(f"Database '{DATA_FILE}' uploaded successfully to Hugging Face repo '{REPO_ID}'.")
|
| 117 |
except Exception as e:
|
| 118 |
+
logging.error(f"Failed to upload database to Hugging Face: {e}", exc_info=True)
|
| 119 |
|
| 120 |
def download_db_from_hf():
|
| 121 |
+
"""Downloads the database file from Hugging Face Hub."""
|
| 122 |
+
if not HF_TOKEN_READ:
|
| 123 |
+
logging.warning("HF_TOKEN_READ is not set. Skipping database download from Hugging Face.")
|
| 124 |
+
# If the file doesn't exist locally, create an empty one
|
| 125 |
+
if not os.path.exists(DATA_FILE):
|
| 126 |
+
logging.warning(f"{DATA_FILE} not found locally and cannot download. Creating empty file.")
|
| 127 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 128 |
+
json.dump({'users': {}, 'files': {}}, f)
|
| 129 |
+
return
|
| 130 |
+
|
| 131 |
try:
|
| 132 |
+
logging.info(f"Attempting to download {DATA_FILE} from Hugging Face repo {REPO_ID}...")
|
| 133 |
hf_hub_download(
|
| 134 |
repo_id=REPO_ID,
|
| 135 |
filename=DATA_FILE,
|
| 136 |
repo_type="dataset",
|
| 137 |
token=HF_TOKEN_READ,
|
| 138 |
+
local_dir=".", # Download to current directory
|
| 139 |
+
local_dir_use_symlinks=False, # Recommended for cross-platform compatibility
|
| 140 |
+
force_download=True, # Ensure we get the latest version
|
| 141 |
+
etag_timeout=60 # Increase timeout for potentially large files or slow connections
|
| 142 |
)
|
| 143 |
+
logging.info(f"Database '{DATA_FILE}' downloaded successfully from Hugging Face.")
|
| 144 |
+
except requests.exceptions.HTTPError as http_err:
|
| 145 |
+
# Specifically catch HTTP errors (like 404 Not Found)
|
| 146 |
+
if http_err.response.status_code == 404:
|
| 147 |
+
logging.warning(f"Database file '{DATA_FILE}' not found in Hugging Face repo '{REPO_ID}'.")
|
| 148 |
+
# If the file doesn't exist locally, create an empty one
|
| 149 |
+
if not os.path.exists(DATA_FILE):
|
| 150 |
+
logging.warning(f"Creating empty local {DATA_FILE} as it wasn't found on HF.")
|
| 151 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 152 |
+
json.dump({'users': {}, 'files': {}}, f)
|
| 153 |
+
else:
|
| 154 |
+
logging.error(f"HTTP error downloading database from Hugging Face: {http_err}", exc_info=True)
|
| 155 |
except Exception as e:
|
| 156 |
+
logging.error(f"Generic error downloading database from Hugging Face: {e}", exc_info=True)
|
| 157 |
+
# If download fails and file doesn't exist, create an empty one
|
| 158 |
if not os.path.exists(DATA_FILE):
|
| 159 |
+
logging.warning(f"Creating empty local {DATA_FILE} due to download error.")
|
| 160 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
| 161 |
+
json.dump({'users': {}, 'files': {}}, f)
|
| 162 |
|
| 163 |
def periodic_backup():
|
| 164 |
+
"""Periodically triggers the database upload to Hugging Face."""
|
| 165 |
+
logging.info("Periodic backup thread started.")
|
| 166 |
while True:
|
| 167 |
+
logging.info("Running periodic backup...")
|
| 168 |
+
# Ensure data is saved locally before upload attempt, in case changes occurred
|
| 169 |
+
# This might be redundant if save_data is called frequently elsewhere,
|
| 170 |
+
# but provides a safety net. Consider the performance impact.
|
| 171 |
+
# current_data = load_data() # Reload data to ensure it's current (optional)
|
| 172 |
+
# save_data(current_data) # Save it (includes upload)
|
| 173 |
+
upload_db_to_hf() # Directly upload the existing file
|
| 174 |
+
logging.info(f"Periodic backup finished. Next backup in 30 minutes.")
|
| 175 |
+
time.sleep(1800) # Backup every 30 minutes (1800 seconds)
|
| 176 |
|
| 177 |
def get_file_type(filename):
|
| 178 |
+
"""Determines file type based on extension."""
|
| 179 |
+
if not filename or '.' not in filename:
|
| 180 |
+
return 'other'
|
| 181 |
+
ext = os.path.splitext(filename)[1].lower()
|
| 182 |
+
video_extensions = ('.mp4', '.mov', '.avi', '.mkv', '.webm', '.flv')
|
| 183 |
+
image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg')
|
| 184 |
+
audio_extensions = ('.mp3', '.wav', '.ogg', '.aac', '.flac')
|
| 185 |
+
|
| 186 |
+
if ext in video_extensions:
|
| 187 |
return 'video'
|
| 188 |
+
elif ext in image_extensions:
|
| 189 |
return 'image'
|
| 190 |
+
elif ext in audio_extensions:
|
| 191 |
+
return 'audio'
|
| 192 |
return 'other'
|
| 193 |
|
| 194 |
+
# --- Enhanced CSS (BASE_STYLE) ---
|
| 195 |
BASE_STYLE = '''
|
| 196 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;800&display=swap');
|
| 197 |
+
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css'); /* Font Awesome */
|
| 198 |
+
|
| 199 |
:root {
|
| 200 |
+
--primary-hue: 345; /* Base hue for primary color (pink/red) */
|
| 201 |
+
--secondary-hue: 195; /* Base hue for secondary color (cyan/blue) */
|
| 202 |
+
--accent-hue: 260; /* Base hue for accent color (purple) */
|
| 203 |
+
|
| 204 |
+
--primary: hsl(var(--primary-hue), 100%, 60%);
|
| 205 |
+
--primary-light: hsl(var(--primary-hue), 100%, 70%);
|
| 206 |
+
--primary-dark: hsl(var(--primary-hue), 100%, 50%);
|
| 207 |
+
|
| 208 |
+
--secondary: hsl(var(--secondary-hue), 100%, 50%);
|
| 209 |
+
--secondary-light: hsl(var(--secondary-hue), 100%, 60%);
|
| 210 |
+
--secondary-dark: hsl(var(--secondary-hue), 100%, 40%);
|
| 211 |
+
|
| 212 |
+
--accent: hsl(var(--accent-hue), 80%, 65%);
|
| 213 |
+
--accent-light: hsl(var(--accent-hue), 80%, 75%);
|
| 214 |
+
--accent-dark: hsl(var(--accent-hue), 80%, 55%);
|
| 215 |
+
|
| 216 |
+
--grey-light-1: #f8f9fa;
|
| 217 |
+
--grey-light-2: #e9ecef;
|
| 218 |
+
--grey-dark-1: #343a40;
|
| 219 |
+
--grey-dark-2: #212529;
|
| 220 |
+
--black: #1a1625;
|
| 221 |
+
--white: #ffffff;
|
| 222 |
+
|
| 223 |
+
--background-light: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
|
| 224 |
+
--text-light: #333;
|
| 225 |
+
--card-bg-light: rgba(255, 255, 255, 0.7);
|
| 226 |
+
--input-bg-light: rgba(255, 255, 255, 0.5);
|
| 227 |
+
--shadow-light: 0 12px 35px rgba(50, 50, 93, 0.15), 0 5px 15px rgba(0, 0, 0, 0.1);
|
| 228 |
+
|
| 229 |
+
--background-dark: linear-gradient(135deg, #232526 0%, #414345 100%);
|
| 230 |
--text-dark: #e8e1ff;
|
| 231 |
+
--card-bg-dark: rgba(40, 35, 60, 0.7);
|
| 232 |
+
--input-bg-dark: rgba(60, 55, 80, 0.5);
|
| 233 |
+
--shadow-dark: 0 12px 35px rgba(0, 0, 0, 0.4), 0 5px 15px rgba(0, 0, 0, 0.3);
|
| 234 |
+
|
| 235 |
+
--border-radius-sm: 8px;
|
| 236 |
+
--border-radius-md: 16px;
|
| 237 |
+
--border-radius-lg: 24px;
|
| 238 |
+
--transition-fast: all 0.2s ease-in-out;
|
| 239 |
+
--transition-med: all 0.3s ease-in-out;
|
| 240 |
+
|
| 241 |
--delete-color: #ff4444;
|
| 242 |
+
--delete-hover: #cc3333;
|
| 243 |
+
--download-color: var(--secondary);
|
| 244 |
+
--download-hover: var(--secondary-dark);
|
| 245 |
}
|
| 246 |
+
|
| 247 |
* { margin: 0; padding: 0; box-sizing: border-box; }
|
| 248 |
+
|
| 249 |
+
html { scroll-behavior: smooth; }
|
| 250 |
+
|
| 251 |
body {
|
| 252 |
font-family: 'Inter', sans-serif;
|
| 253 |
background: var(--background-light);
|
| 254 |
color: var(--text-light);
|
| 255 |
+
line-height: 1.7;
|
| 256 |
+
transition: var(--transition-med);
|
| 257 |
+
min-height: 100vh;
|
| 258 |
+
padding: 20px;
|
| 259 |
}
|
| 260 |
+
|
| 261 |
body.dark {
|
| 262 |
background: var(--background-dark);
|
| 263 |
color: var(--text-dark);
|
| 264 |
}
|
| 265 |
+
|
| 266 |
+
.theme-toggle {
|
| 267 |
+
position: fixed;
|
| 268 |
+
top: 20px;
|
| 269 |
+
right: 20px;
|
| 270 |
+
background: var(--card-bg-light);
|
| 271 |
+
color: var(--text-light);
|
| 272 |
+
border: 1px solid rgba(0,0,0,0.1);
|
| 273 |
+
border-radius: 50%;
|
| 274 |
+
width: 45px;
|
| 275 |
+
height: 45px;
|
| 276 |
+
display: flex;
|
| 277 |
+
justify-content: center;
|
| 278 |
+
align-items: center;
|
| 279 |
+
cursor: pointer;
|
| 280 |
+
box-shadow: var(--shadow-light);
|
| 281 |
+
z-index: 1500;
|
| 282 |
+
transition: var(--transition-med);
|
| 283 |
+
}
|
| 284 |
+
body.dark .theme-toggle {
|
| 285 |
+
background: var(--card-bg-dark);
|
| 286 |
+
color: var(--text-dark);
|
| 287 |
+
border: 1px solid rgba(255,255,255,0.1);
|
| 288 |
+
box-shadow: var(--shadow-dark);
|
| 289 |
+
}
|
| 290 |
+
.theme-toggle:hover {
|
| 291 |
+
transform: scale(1.1) rotate(15deg);
|
| 292 |
+
}
|
| 293 |
+
.theme-toggle .fa-sun { display: block; }
|
| 294 |
+
.theme-toggle .fa-moon { display: none; }
|
| 295 |
+
body.dark .theme-toggle .fa-sun { display: none; }
|
| 296 |
+
body.dark .theme-toggle .fa-moon { display: block; }
|
| 297 |
+
|
| 298 |
+
|
| 299 |
.container {
|
| 300 |
+
margin: 40px auto;
|
| 301 |
max-width: 1200px;
|
| 302 |
+
padding: 35px 40px;
|
| 303 |
+
background: var(--card-bg-light);
|
| 304 |
+
border-radius: var(--border-radius-lg);
|
| 305 |
+
box-shadow: var(--shadow-light);
|
| 306 |
+
backdrop-filter: blur(10px); /* Glassmorphism */
|
| 307 |
+
border: 1px solid rgba(255, 255, 255, 0.2);
|
| 308 |
+
transition: var(--transition-med);
|
| 309 |
}
|
| 310 |
body.dark .container {
|
| 311 |
background: var(--card-bg-dark);
|
| 312 |
+
box-shadow: var(--shadow-dark);
|
| 313 |
+
border: 1px solid rgba(255, 255, 255, 0.1);
|
| 314 |
}
|
| 315 |
+
|
| 316 |
h1 {
|
| 317 |
+
font-size: 2.8em;
|
| 318 |
font-weight: 800;
|
| 319 |
text-align: center;
|
| 320 |
+
margin-bottom: 35px;
|
| 321 |
background: linear-gradient(135deg, var(--primary), var(--accent));
|
| 322 |
-webkit-background-clip: text;
|
| 323 |
+
background-clip: text;
|
| 324 |
color: transparent;
|
| 325 |
}
|
| 326 |
+
|
| 327 |
h2 {
|
| 328 |
+
font-size: 1.8em;
|
| 329 |
+
font-weight: 600;
|
| 330 |
+
margin-top: 40px;
|
| 331 |
+
margin-bottom: 20px;
|
| 332 |
color: var(--text-light);
|
| 333 |
+
border-bottom: 2px solid var(--primary-light);
|
| 334 |
+
padding-bottom: 10px;
|
| 335 |
}
|
| 336 |
body.dark h2 {
|
| 337 |
color: var(--text-dark);
|
| 338 |
+
border-bottom-color: var(--primary-dark);
|
| 339 |
}
|
| 340 |
+
|
| 341 |
+
input, textarea, select { /* Added select styling */
|
| 342 |
width: 100%;
|
| 343 |
+
padding: 15px 20px;
|
| 344 |
margin: 12px 0;
|
| 345 |
+
border: 1px solid transparent;
|
| 346 |
+
border-radius: var(--border-radius-md);
|
| 347 |
+
background: var(--input-bg-light);
|
| 348 |
color: var(--text-light);
|
| 349 |
+
font-size: 1em; /* Adjusted size */
|
| 350 |
+
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.06);
|
| 351 |
+
transition: var(--transition-fast);
|
| 352 |
+
backdrop-filter: blur(5px);
|
| 353 |
}
|
| 354 |
+
body.dark input, body.dark textarea, body.dark select {
|
| 355 |
+
background: var(--input-bg-dark);
|
| 356 |
color: var(--text-dark);
|
| 357 |
+
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.2);
|
| 358 |
}
|
| 359 |
+
|
| 360 |
+
input:focus, textarea:focus, select:focus {
|
| 361 |
outline: none;
|
| 362 |
+
border-color: var(--primary);
|
| 363 |
+
box-shadow: 0 0 0 3px hsla(var(--primary-hue), 100%, 60%, 0.3);
|
| 364 |
+
}
|
| 365 |
+
body.dark input:focus, body.dark textarea:focus, body.dark select:focus {
|
| 366 |
+
border-color: var(--primary-light);
|
| 367 |
+
box-shadow: 0 0 0 3px hsla(var(--primary-hue), 100%, 70%, 0.3);
|
| 368 |
}
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
/* --- Buttons --- */
|
| 372 |
.btn {
|
| 373 |
padding: 14px 28px;
|
|
|
|
|
|
|
| 374 |
border: none;
|
| 375 |
+
border-radius: var(--border-radius-md);
|
| 376 |
cursor: pointer;
|
| 377 |
font-size: 1.1em;
|
| 378 |
font-weight: 600;
|
| 379 |
+
transition: var(--transition-fast);
|
| 380 |
+
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
|
| 381 |
+
display: inline-flex; /* Use flex for icon alignment */
|
| 382 |
+
align-items: center;
|
| 383 |
+
gap: 8px; /* Space between icon and text */
|
| 384 |
text-decoration: none;
|
| 385 |
+
background: var(--primary);
|
| 386 |
+
color: var(--white);
|
| 387 |
}
|
| 388 |
.btn:hover {
|
| 389 |
+
transform: translateY(-2px);
|
| 390 |
+
box-shadow: 0 7px 20px rgba(0, 0, 0, 0.15);
|
| 391 |
+
background: var(--primary-dark);
|
| 392 |
+
}
|
| 393 |
+
.btn:active {
|
| 394 |
+
transform: translateY(0);
|
| 395 |
+
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
|
| 396 |
+
}
|
| 397 |
+
.btn i { /* Icon styling */
|
| 398 |
+
font-size: 1.1em;
|
| 399 |
}
|
| 400 |
+
|
| 401 |
+
|
| 402 |
.download-btn {
|
| 403 |
+
background: var(--download-color);
|
| 404 |
margin-top: 10px;
|
| 405 |
}
|
| 406 |
.download-btn:hover {
|
| 407 |
+
background: var(--download-hover);
|
| 408 |
}
|
| 409 |
+
|
| 410 |
.delete-btn {
|
| 411 |
background: var(--delete-color);
|
| 412 |
margin-top: 10px;
|
| 413 |
}
|
| 414 |
.delete-btn:hover {
|
| 415 |
+
background: var(--delete-hover);
|
| 416 |
}
|
| 417 |
+
|
| 418 |
+
a { /* General link styling */
|
| 419 |
+
color: var(--primary);
|
| 420 |
+
text-decoration: none;
|
| 421 |
+
transition: var(--transition-fast);
|
| 422 |
+
}
|
| 423 |
+
a:hover {
|
| 424 |
+
color: var(--accent);
|
| 425 |
+
text-decoration: underline;
|
| 426 |
+
}
|
| 427 |
+
body.dark a {
|
| 428 |
+
color: var(--primary-light);
|
| 429 |
+
}
|
| 430 |
+
body.dark a:hover {
|
| 431 |
+
color: var(--accent-light);
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
/* Flash Messages */
|
| 435 |
.flash {
|
| 436 |
+
padding: 15px 20px;
|
| 437 |
+
margin-bottom: 20px;
|
| 438 |
+
border-radius: var(--border-radius-sm);
|
| 439 |
text-align: center;
|
| 440 |
+
font-weight: 600;
|
| 441 |
+
border: 1px solid transparent;
|
| 442 |
}
|
| 443 |
+
.flash-success { /* Example specific flash type */
|
| 444 |
+
background-color: hsla(var(--secondary-hue), 80%, 85%, 0.8);
|
| 445 |
+
color: var(--secondary-dark);
|
| 446 |
+
border-color: var(--secondary);
|
| 447 |
+
}
|
| 448 |
+
.flash-error { /* Example specific flash type */
|
| 449 |
+
background-color: hsla(var(--primary-hue), 80%, 85%, 0.8);
|
| 450 |
+
color: var(--primary-dark);
|
| 451 |
+
border-color: var(--primary);
|
| 452 |
+
}
|
| 453 |
+
body.dark .flash-success {
|
| 454 |
+
background-color: hsla(var(--secondary-hue), 60%, 30%, 0.8);
|
| 455 |
+
color: var(--secondary-light);
|
| 456 |
+
border-color: var(--secondary-dark);
|
| 457 |
+
}
|
| 458 |
+
body.dark .flash-error {
|
| 459 |
+
background-color: hsla(var(--primary-hue), 60%, 30%, 0.8);
|
| 460 |
+
color: var(--primary-light);
|
| 461 |
+
border-color: var(--primary-dark);
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
/* File Grid */
|
| 465 |
.file-grid {
|
| 466 |
display: grid;
|
| 467 |
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
| 468 |
+
gap: 25px;
|
| 469 |
+
margin-top: 30px;
|
| 470 |
}
|
| 471 |
+
|
| 472 |
+
/* User List */
|
| 473 |
.user-list {
|
| 474 |
margin-top: 20px;
|
| 475 |
+
display: flex;
|
| 476 |
+
flex-direction: column;
|
| 477 |
+
gap: 15px;
|
| 478 |
}
|
| 479 |
+
|
| 480 |
.user-item {
|
| 481 |
+
padding: 20px 25px;
|
| 482 |
+
background: var(--card-bg-light);
|
| 483 |
+
border-radius: var(--border-radius-md);
|
| 484 |
+
box-shadow: var(--shadow-light);
|
| 485 |
+
transition: var(--transition-med);
|
| 486 |
+
border: 1px solid rgba(0,0,0,0.05);
|
| 487 |
+
backdrop-filter: blur(5px);
|
| 488 |
}
|
| 489 |
body.dark .user-item {
|
| 490 |
background: var(--card-bg-dark);
|
| 491 |
+
box-shadow: var(--shadow-dark);
|
| 492 |
+
border: 1px solid rgba(255,255,255,0.1);
|
| 493 |
}
|
| 494 |
.user-item:hover {
|
| 495 |
+
transform: translateY(-5px) scale(1.02);
|
| 496 |
+
box-shadow: 0 15px 40px rgba(50, 50, 93, 0.2), 0 8px 20px rgba(0, 0, 0, 0.15);
|
| 497 |
+
}
|
| 498 |
+
body.dark .user-item:hover {
|
| 499 |
+
box-shadow: 0 15px 40px rgba(0, 0, 0, 0.5), 0 8px 20px rgba(0, 0, 0, 0.35);
|
| 500 |
}
|
| 501 |
.user-item a {
|
|
|
|
|
|
|
| 502 |
font-weight: 600;
|
| 503 |
+
font-size: 1.2em;
|
| 504 |
+
display: block;
|
| 505 |
+
margin-bottom: 8px;
|
| 506 |
}
|
| 507 |
+
.user-item p {
|
| 508 |
+
font-size: 0.9em;
|
| 509 |
+
color: #666; /* Slightly muted text */
|
|
|
|
|
|
|
|
|
|
|
|
|
| 510 |
}
|
| 511 |
+
body.dark .user-item p {
|
| 512 |
+
color: #aaa;
|
|
|
|
|
|
|
| 513 |
}
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
/* File Items */
|
| 517 |
.file-item {
|
| 518 |
+
background: var(--card-bg-light);
|
| 519 |
padding: 15px;
|
| 520 |
+
border-radius: var(--border-radius-md);
|
| 521 |
+
box-shadow: var(--shadow-light);
|
| 522 |
text-align: center;
|
| 523 |
+
transition: var(--transition-med);
|
| 524 |
+
display: flex;
|
| 525 |
+
flex-direction: column;
|
| 526 |
+
justify-content: space-between;
|
| 527 |
+
overflow: hidden; /* Ensure content stays within bounds */
|
| 528 |
+
border: 1px solid rgba(0,0,0,0.05);
|
| 529 |
+
backdrop-filter: blur(5px);
|
| 530 |
}
|
| 531 |
body.dark .file-item {
|
| 532 |
background: var(--card-bg-dark);
|
| 533 |
+
box-shadow: var(--shadow-dark);
|
| 534 |
+
border: 1px solid rgba(255,255,255,0.1);
|
| 535 |
}
|
| 536 |
.file-item:hover {
|
| 537 |
transform: translateY(-5px);
|
| 538 |
+
box-shadow: 0 15px 40px rgba(50, 50, 93, 0.2), 0 8px 20px rgba(0, 0, 0, 0.15);
|
| 539 |
+
}
|
| 540 |
+
body.dark .file-item:hover {
|
| 541 |
+
box-shadow: 0 15px 40px rgba(0, 0, 0, 0.5), 0 8px 20px rgba(0, 0, 0, 0.35);
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
.file-preview-container { /* Container for consistent preview size */
|
| 545 |
+
width: 100%;
|
| 546 |
+
height: 180px; /* Fixed height */
|
| 547 |
+
overflow: hidden;
|
| 548 |
+
border-radius: var(--border-radius-sm);
|
| 549 |
+
margin-bottom: 15px;
|
| 550 |
+
background-color: var(--grey-light-2); /* Placeholder background */
|
| 551 |
+
display: flex;
|
| 552 |
+
justify-content: center;
|
| 553 |
+
align-items: center;
|
| 554 |
+
}
|
| 555 |
+
body.dark .file-preview-container {
|
| 556 |
+
background-color: var(--grey-dark-1);
|
| 557 |
}
|
| 558 |
+
|
| 559 |
.file-preview {
|
| 560 |
max-width: 100%;
|
| 561 |
+
max-height: 100%;
|
| 562 |
+
width: auto;
|
| 563 |
+
height: auto;
|
| 564 |
+
object-fit: cover; /* Changed to cover for better filling */
|
| 565 |
+
display: block; /* Remove extra space below image */
|
| 566 |
+
cursor: pointer;
|
| 567 |
+
}
|
| 568 |
+
.file-preview[src=""] { /* Hide broken image icons if src is empty */
|
| 569 |
+
display: none;
|
| 570 |
+
}
|
| 571 |
+
.file-preview-placeholder { /* Style for text placeholder */
|
| 572 |
+
font-size: 3em;
|
| 573 |
+
color: var(--grey-dark-1);
|
| 574 |
+
opacity: 0.5;
|
| 575 |
+
}
|
| 576 |
+
body.dark .file-preview-placeholder {
|
| 577 |
+
color: var(--grey-light-1);
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
.file-info {
|
| 582 |
+
margin-bottom: 15px;
|
| 583 |
}
|
| 584 |
+
.file-info p {
|
| 585 |
font-size: 0.9em;
|
| 586 |
margin: 5px 0;
|
| 587 |
+
word-break: break-all; /* Prevent long filenames from overflowing */
|
| 588 |
}
|
| 589 |
+
.file-info .filename {
|
| 590 |
+
font-weight: 600;
|
|
|
|
| 591 |
}
|
| 592 |
+
.file-info .filedate {
|
| 593 |
+
font-size: 0.8em;
|
| 594 |
+
color: #777;
|
| 595 |
+
}
|
| 596 |
+
body.dark .file-info .filedate {
|
| 597 |
+
color: #bbb;
|
| 598 |
+
}
|
| 599 |
+
|
| 600 |
+
.file-actions {
|
| 601 |
+
display: flex;
|
| 602 |
+
justify-content: space-around; /* Space out buttons */
|
| 603 |
+
gap: 10px;
|
| 604 |
+
}
|
| 605 |
+
.file-actions .btn { /* Make buttons smaller in file card */
|
| 606 |
+
padding: 8px 15px;
|
| 607 |
+
font-size: 0.9em;
|
| 608 |
}
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
/* Modal */
|
| 612 |
.modal {
|
| 613 |
+
display: none; /* Hidden by default */
|
| 614 |
position: fixed;
|
| 615 |
top: 0;
|
| 616 |
left: 0;
|
|
|
|
| 620 |
z-index: 2000;
|
| 621 |
justify-content: center;
|
| 622 |
align-items: center;
|
| 623 |
+
padding: 20px;
|
| 624 |
+
cursor: pointer; /* Indicate background can be clicked to close */
|
| 625 |
+
}
|
| 626 |
+
.modal-content {
|
| 627 |
+
max-width: 90vw; /* Use viewport width */
|
| 628 |
+
max-height: 90vh; /* Use viewport height */
|
| 629 |
+
display: flex; /* Use flex to center content within modal-content if needed */
|
| 630 |
+
justify-content: center;
|
| 631 |
+
align-items: center;
|
| 632 |
+
position: relative; /* Needed for close button */
|
| 633 |
+
cursor: default; /* Prevent background cursor on the content itself */
|
| 634 |
}
|
| 635 |
.modal img, .modal video {
|
| 636 |
+
display: block; /* Remove extra space */
|
| 637 |
+
max-width: 100%;
|
| 638 |
+
max-height: 100%;
|
| 639 |
object-fit: contain;
|
| 640 |
+
border-radius: var(--border-radius-md);
|
| 641 |
+
box-shadow: 0 20px 50px rgba(0,0,0,0.5);
|
| 642 |
+
}
|
| 643 |
+
.modal-close {
|
| 644 |
+
position: absolute;
|
| 645 |
+
top: -10px;
|
| 646 |
+
right: -10px;
|
| 647 |
+
width: 35px;
|
| 648 |
+
height: 35px;
|
| 649 |
+
background: rgba(255, 255, 255, 0.9);
|
| 650 |
+
color: #333;
|
| 651 |
+
border-radius: 50%;
|
| 652 |
+
display: flex;
|
| 653 |
+
justify-content: center;
|
| 654 |
+
align-items: center;
|
| 655 |
+
font-size: 1.5em;
|
| 656 |
+
font-weight: bold;
|
| 657 |
+
cursor: pointer;
|
| 658 |
+
transition: var(--transition-fast);
|
| 659 |
+
border: 1px solid rgba(0,0,0,0.2);
|
| 660 |
+
z-index: 2010; /* Above modal content */
|
| 661 |
+
}
|
| 662 |
+
.modal-close:hover {
|
| 663 |
+
background: var(--white);
|
| 664 |
+
transform: scale(1.1);
|
| 665 |
+
color: var(--primary);
|
| 666 |
}
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
/* Progress Bar */
|
| 670 |
#progress-container {
|
| 671 |
width: 100%;
|
| 672 |
+
background: var(--input-bg-light);
|
| 673 |
+
border-radius: var(--border-radius-sm);
|
| 674 |
+
margin: 20px 0;
|
| 675 |
+
padding: 4px;
|
| 676 |
+
box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
|
| 677 |
+
display: none; /* Hidden by default */
|
| 678 |
+
}
|
| 679 |
+
body.dark #progress-container {
|
| 680 |
+
background: var(--input-bg-dark);
|
| 681 |
+
box-shadow: inset 0 1px 3px rgba(0,0,0,0.3);
|
| 682 |
}
|
| 683 |
#progress-bar {
|
| 684 |
width: 0%;
|
| 685 |
height: 20px;
|
| 686 |
+
background: linear-gradient(90deg, var(--primary-light), var(--primary));
|
| 687 |
+
border-radius: 5px;
|
| 688 |
+
transition: width 0.4s ease;
|
| 689 |
+
text-align: center;
|
| 690 |
+
color: white;
|
| 691 |
+
font-weight: 600;
|
| 692 |
+
line-height: 20px; /* Vertically center text */
|
| 693 |
+
font-size: 0.8em;
|
| 694 |
+
}
|
| 695 |
+
|
| 696 |
+
/* Forms */
|
| 697 |
+
#register-form, #login-form, #upload-form {
|
| 698 |
+
margin-top: 25px;
|
| 699 |
+
}
|
| 700 |
+
|
| 701 |
+
/* Responsiveness */
|
| 702 |
+
@media (max-width: 768px) {
|
| 703 |
+
h1 { font-size: 2.2em; }
|
| 704 |
+
h2 { font-size: 1.5em; }
|
| 705 |
+
.container { padding: 25px 20px; margin: 20px; }
|
| 706 |
+
.file-grid { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px; }
|
| 707 |
+
.theme-toggle { top: 10px; right: 10px; width: 40px; height: 40px; }
|
| 708 |
+
}
|
| 709 |
+
@media (max-width: 480px) {
|
| 710 |
+
body { padding: 10px; }
|
| 711 |
+
.container { margin: 10px; padding: 20px 15px; }
|
| 712 |
+
h1 { font-size: 1.8em; margin-bottom: 25px; }
|
| 713 |
+
.file-grid { grid-template-columns: 1fr; /* Single column on very small screens */ gap: 15px; }
|
| 714 |
+
.btn { padding: 12px 20px; font-size: 1em; }
|
| 715 |
+
input, textarea, select { padding: 12px 15px; font-size: 0.95em;}
|
| 716 |
+
.file-item { padding: 10px; }
|
| 717 |
+
.file-preview-container { height: 150px; }
|
| 718 |
+
.file-actions { flex-direction: column; } /* Stack buttons vertically */
|
| 719 |
+
.modal-content { max-width: 95vw; max-height: 85vh; }
|
| 720 |
+
.modal-close { top: 5px; right: 5px; width: 30px; height: 30px; font-size: 1.2em;}
|
| 721 |
}
|
| 722 |
'''
|
| 723 |
|
| 724 |
+
# --- Flask Routes ---
|
| 725 |
+
|
| 726 |
@app.route('/register', methods=['GET', 'POST'])
|
| 727 |
def register():
|
| 728 |
+
"""Handles user registration."""
|
| 729 |
if request.method == 'POST':
|
| 730 |
+
username = request.form.get('username', '').strip()
|
| 731 |
+
password = request.form.get('password', '').strip()
|
| 732 |
+
# Removed code = request.form.get('code')
|
| 733 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 734 |
if not username or not password:
|
| 735 |
+
flash('Логин и пароль не могут быть пустыми!', 'error') # Use category
|
| 736 |
return redirect(url_for('register'))
|
| 737 |
+
|
| 738 |
+
if len(password) < 6: # Basic password length check
|
| 739 |
+
flash('Пароль должен содержать не менее 6 символов!', 'error')
|
| 740 |
+
return redirect(url_for('register'))
|
| 741 |
+
|
| 742 |
+
data = load_data()
|
| 743 |
+
|
| 744 |
+
# Case-insensitive username check
|
| 745 |
+
if username.lower() in (k.lower() for k in data['users']):
|
| 746 |
+
flash('Пользователь с таким логином уже существует!', 'error')
|
| 747 |
+
return redirect(url_for('register'))
|
| 748 |
+
|
| 749 |
+
# --- REMOVED REGISTRATION CODE CHECK ---
|
| 750 |
+
# if code != REGISTRATION_CODE:
|
| 751 |
+
# flash('Неверный регистрационный код!')
|
| 752 |
+
# return redirect(url_for('register'))
|
| 753 |
+
|
| 754 |
+
# !! SECURITY WARNING: Storing plain text passwords !!
|
| 755 |
+
# Replace with password hashing in a real application
|
| 756 |
data['users'][username] = {
|
| 757 |
+
'password': password, # HASH THIS PASSWORD IN PRODUCTION
|
| 758 |
'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
| 759 |
'files': []
|
| 760 |
}
|
| 761 |
+
try:
|
| 762 |
+
save_data(data)
|
| 763 |
+
session['username'] = username # Log in the user immediately after registration
|
| 764 |
+
flash('Регистрация успешна! Вы вошли в систему.', 'success') # Use category
|
| 765 |
+
return redirect(url_for('dashboard'))
|
| 766 |
+
except Exception as e:
|
| 767 |
+
logging.error(f"Error saving data during registration for {username}: {e}")
|
| 768 |
+
flash('Произошла ошибка при сохранении данных. Попробуйте снова.', 'error')
|
| 769 |
+
return redirect(url_for('register'))
|
| 770 |
+
|
| 771 |
+
# GET Request
|
| 772 |
html = '''
|
| 773 |
<!DOCTYPE html>
|
| 774 |
+
<html lang="ru">
|
| 775 |
<head>
|
| 776 |
<meta charset="UTF-8">
|
| 777 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 778 |
<title>Регистрация - Zeus Cloud</title>
|
| 779 |
+
<style>{style}</style>
|
|
|
|
| 780 |
</head>
|
| 781 |
+
<body class="">
|
| 782 |
+
<div class="theme-toggle" id="theme-toggle">
|
| 783 |
+
<i class="fas fa-sun"></i><i class="fas fa-moon"></i>
|
| 784 |
+
</div>
|
| 785 |
<div class="container">
|
| 786 |
<h1>Регистрация в Zeus Cloud</h1>
|
| 787 |
+
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 788 |
{% if messages %}
|
| 789 |
+
{% for category, message in messages %}
|
| 790 |
+
<div class="flash flash-{{ category }}">{{ message }}</div>
|
| 791 |
{% endfor %}
|
| 792 |
{% endif %}
|
| 793 |
{% endwith %}
|
| 794 |
<form method="POST" id="register-form">
|
| 795 |
+
<input type="text" name="username" placeholder="Придумайте логин" required>
|
| 796 |
+
<input type="password" name="password" placeholder="Придумайте пароль (минимум 6 символов)" required minlength="6">
|
| 797 |
+
<!-- Removed Registration Code Input -->
|
| 798 |
+
<button type="submit" class="btn"><i class="fas fa-user-plus"></i> Зарегистрироваться</button>
|
| 799 |
</form>
|
| 800 |
+
<p style="margin-top: 20px;">Уже есть аккаунт? <a href="{{ url_for('login') }}">Войдите здесь</a></p>
|
| 801 |
</div>
|
| 802 |
+
<script>{script}</script>
|
| 803 |
</body>
|
| 804 |
</html>
|
| 805 |
'''
|
| 806 |
+
script = get_common_script() # Get theme toggle script
|
| 807 |
+
return render_template_string(html, style=BASE_STYLE, script=script)
|
| 808 |
|
| 809 |
@app.route('/', methods=['GET', 'POST'])
|
| 810 |
def login():
|
| 811 |
+
"""Handles user login."""
|
| 812 |
if request.method == 'POST':
|
| 813 |
+
username = request.form.get('username', '').strip()
|
| 814 |
+
password = request.form.get('password', '').strip()
|
| 815 |
data = load_data()
|
| 816 |
+
|
| 817 |
+
# Case-insensitive login check, retrieve original casing
|
| 818 |
+
found_user = None
|
| 819 |
+
for stored_username, user_data in data['users'].items():
|
| 820 |
+
if stored_username.lower() == username.lower():
|
| 821 |
+
# !! SECURITY WARNING: Comparing plain text passwords !!
|
| 822 |
+
if user_data.get('password') == password:
|
| 823 |
+
found_user = stored_username # Use the correctly cased username
|
| 824 |
+
break
|
| 825 |
+
else:
|
| 826 |
+
# Password incorrect, but username found (potential timing attack vector, less critical with hashing)
|
| 827 |
+
return jsonify({'status': 'error', 'message': 'Неверный логин или пароль!'})
|
| 828 |
+
|
| 829 |
+
if found_user:
|
| 830 |
+
session['username'] = found_user # Store correctly cased username in session
|
| 831 |
+
logging.info(f"User '{found_user}' logged in successfully.")
|
| 832 |
return jsonify({'status': 'success', 'redirect': url_for('dashboard')})
|
| 833 |
else:
|
| 834 |
+
# Username not found
|
| 835 |
+
logging.warning(f"Failed login attempt for username: '{username}'")
|
| 836 |
return jsonify({'status': 'error', 'message': 'Неверный логин или пароль!'})
|
| 837 |
+
|
| 838 |
+
# GET Request
|
| 839 |
html = '''
|
| 840 |
<!DOCTYPE html>
|
| 841 |
+
<html lang="ru">
|
| 842 |
<head>
|
| 843 |
<meta charset="UTF-8">
|
| 844 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 845 |
+
<title>Вход - Zeus Cloud</title>
|
| 846 |
+
<style>{style}</style>
|
|
|
|
| 847 |
</head>
|
| 848 |
+
<body class="">
|
| 849 |
+
<div class="theme-toggle" id="theme-toggle">
|
| 850 |
+
<i class="fas fa-sun"></i><i class="fas fa-moon"></i>
|
| 851 |
+
</div>
|
| 852 |
<div class="container">
|
| 853 |
<h1>Zeus Cloud</h1>
|
| 854 |
<div id="flash-messages">
|
| 855 |
+
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 856 |
{% if messages %}
|
| 857 |
+
{% for category, message in messages %}
|
| 858 |
+
<div class="flash flash-{{ category }}">{{ message }}</div>
|
| 859 |
{% endfor %}
|
| 860 |
{% endif %}
|
| 861 |
{% endwith %}
|
|
|
|
| 863 |
<form method="POST" id="login-form">
|
| 864 |
<input type="text" name="username" placeholder="Введите логин" required>
|
| 865 |
<input type="password" name="password" placeholder="Введите пароль" required>
|
| 866 |
+
<button type="submit" class="btn"><i class="fas fa-sign-in-alt"></i> Войти</button>
|
| 867 |
</form>
|
| 868 |
<p style="margin-top: 20px;">Нет аккаунта? <a href="{{ url_for('register') }}">Зарегистрируйтесь</a></p>
|
| 869 |
</div>
|
| 870 |
<script>
|
| 871 |
+
// --- Login Page Specific Script ---
|
| 872 |
+
{script} // Include common script first
|
| 873 |
+
|
| 874 |
+
// Auto-login attempt from localStorage
|
| 875 |
const savedCredentials = JSON.parse(localStorage.getItem('zeusCredentials'));
|
| 876 |
+
if (savedCredentials && savedCredentials.username && savedCredentials.password) {{
|
| 877 |
+
console.log("Attempting auto-login for:", savedCredentials.username);
|
| 878 |
+
fetch('/', {{
|
| 879 |
method: 'POST',
|
| 880 |
+
headers: {{
|
| 881 |
+
'Content-Type': 'application/x-www-form-urlencoded', // Correct content type for form data
|
| 882 |
+
}},
|
| 883 |
+
body: `username=${{encodeURIComponent(savedCredentials.username)}}&password=${{encodeURIComponent(savedCredentials.password)}}`
|
| 884 |
+
}})
|
| 885 |
.then(response => response.json())
|
| 886 |
+
.then(data => {{
|
| 887 |
+
if (data.status === 'success') {{
|
| 888 |
+
console.log("Auto-login successful, redirecting...");
|
| 889 |
window.location.href = data.redirect;
|
| 890 |
+
}} else {{
|
| 891 |
+
console.log("Auto-login failed:", data.message);
|
| 892 |
+
// Optionally clear invalid credentials
|
| 893 |
+
// localStorage.removeItem('zeusCredentials');
|
| 894 |
+
}}
|
| 895 |
+
}})
|
| 896 |
+
.catch(error => console.error('Ошибка при попытке автоматического входа:', error));
|
| 897 |
+
}}
|
| 898 |
|
| 899 |
+
// Handle login form submission via Fetch API for smoother UX
|
| 900 |
+
document.getElementById('login-form').addEventListener('submit', function(e) {{
|
| 901 |
+
e.preventDefault(); // Prevent default form submission
|
| 902 |
const formData = new FormData(this);
|
| 903 |
+
const flashContainer = document.getElementById('flash-messages');
|
| 904 |
+
flashContainer.innerHTML = ''; // Clear previous messages
|
| 905 |
+
|
| 906 |
+
fetch('/', {{
|
| 907 |
method: 'POST',
|
| 908 |
body: formData
|
| 909 |
+
}})
|
| 910 |
.then(response => response.json())
|
| 911 |
+
.then(data => {{
|
| 912 |
+
if (data.status === 'success') {{
|
| 913 |
+
// Store credentials on successful manual login
|
| 914 |
const username = formData.get('username');
|
| 915 |
const password = formData.get('password');
|
| 916 |
+
localStorage.setItem('zeusCredentials', JSON.stringify({{ username, password }}));
|
| 917 |
+
window.location.href = data.redirect; // Redirect on success
|
| 918 |
+
}} else {{
|
| 919 |
+
// Display error message
|
| 920 |
+
flashContainer.innerHTML = `<div class="flash flash-error">${{data.message || 'Произошла ошибка'}}</div>`;
|
| 921 |
+
}}
|
| 922 |
+
}})
|
| 923 |
+
.catch(error => {{
|
| 924 |
+
console.error('Ошибка при отправке формы входа:', error);
|
| 925 |
+
flashContainer.innerHTML = `<div class="flash flash-error">Ошибка соединения. Попробуйте снова.</div>`;
|
| 926 |
+
}});
|
| 927 |
+
}});
|
| 928 |
</script>
|
| 929 |
</body>
|
| 930 |
</html>
|
| 931 |
'''
|
| 932 |
+
script = get_common_script() # Get theme toggle script
|
| 933 |
+
return render_template_string(html, style=BASE_STYLE, script=script)
|
| 934 |
|
| 935 |
@app.route('/dashboard', methods=['GET', 'POST'])
|
| 936 |
def dashboard():
|
| 937 |
+
"""Displays user's files and handles uploads."""
|
| 938 |
if 'username' not in session:
|
| 939 |
+
flash('Пожалуйста, войдите, чтобы получить доступ к панели управления.', 'error')
|
| 940 |
return redirect(url_for('login'))
|
| 941 |
+
|
| 942 |
username = session['username']
|
| 943 |
data = load_data()
|
| 944 |
+
if username not in data.get('users', {}): # Safer access
|
| 945 |
+
session.pop('username', None) # Clear invalid session
|
| 946 |
+
flash('Ваша сессия недействительна или пользователь был удален.', 'error')
|
| 947 |
return redirect(url_for('login'))
|
|
|
|
|
|
|
| 948 |
|
| 949 |
+
user_data = data['users'][username]
|
| 950 |
+
# Ensure 'files' list exists for the user
|
| 951 |
+
user_files_list = user_data.setdefault('files', [])
|
| 952 |
+
|
| 953 |
+
# Sort files by date, newest first
|
| 954 |
+
user_files = sorted(user_files_list, key=lambda x: x.get('upload_date', ''), reverse=True)
|
| 955 |
+
|
| 956 |
+
# --- Handle File Upload (POST Request) ---
|
| 957 |
if request.method == 'POST':
|
| 958 |
+
if not HF_TOKEN_WRITE:
|
| 959 |
+
flash('Ошибка: Загрузка невозможна. Отсутствует токен для записи в Hugging Face.', 'error')
|
| 960 |
+
return redirect(url_for('dashboard')) # Or return an error response
|
| 961 |
+
|
| 962 |
+
files = request.files.getlist('files') # Use getlist for multiple files
|
| 963 |
+
|
| 964 |
+
if not files or all(f.filename == '' for f in files):
|
| 965 |
+
flash('Файлы не выбраны для загрузки.', 'error')
|
| 966 |
+
return redirect(url_for('dashboard'))
|
| 967 |
+
|
| 968 |
+
# Limit number of files per upload
|
| 969 |
+
MAX_FILES_PER_UPLOAD = 20
|
| 970 |
+
if len(files) > MAX_FILES_PER_UPLOAD:
|
| 971 |
+
flash(f'Можно загружать не более {MAX_FILES_PER_UPLOAD} файлов за раз!', 'error')
|
| 972 |
return redirect(url_for('dashboard'))
|
| 973 |
+
|
| 974 |
+
# --- File Processing Logic ---
|
| 975 |
+
uploads_dir = 'temp_uploads' # Use a temporary directory
|
| 976 |
+
os.makedirs(uploads_dir, exist_ok=True)
|
| 977 |
+
api = HfApi()
|
| 978 |
+
processed_files_info = []
|
| 979 |
+
errors_occurred = False
|
| 980 |
+
|
| 981 |
+
for file in files:
|
| 982 |
+
if file and file.filename: # Check if file exists and has a name
|
| 983 |
+
original_filename = file.filename
|
| 984 |
+
# Sanitize filename
|
| 985 |
+
filename = secure_filename(original_filename)
|
| 986 |
+
if not filename: # Handle cases where secure_filename returns empty (e.g., ".txt")
|
| 987 |
+
filename = f"file_{int(time.time())}" # Generate a fallback name
|
| 988 |
+
|
| 989 |
+
temp_path = os.path.join(uploads_dir, f"{username}_{filename}") # Prefix with username for uniqueness
|
| 990 |
+
file_path_in_repo = f"cloud_files/{username}/{filename}" # Path in Hugging Face repo
|
| 991 |
+
|
| 992 |
+
try:
|
| 993 |
file.save(temp_path)
|
| 994 |
+
logging.info(f"File '{filename}' saved temporarily to '{temp_path}' for user '{username}'.")
|
| 995 |
+
|
| 996 |
+
# Check for duplicates in repo (optional, can be slow)
|
| 997 |
+
# try:
|
| 998 |
+
# api.file_info(repo_id=REPO_ID, path_in_repo=file_path_in_repo, repo_type="dataset", token=HF_TOKEN_READ)
|
| 999 |
+
# logging.warning(f"File '{file_path_in_repo}' already exists in repo. Skipping upload.")
|
| 1000 |
+
# # Decide how to handle duplicates: skip, overwrite, rename?
|
| 1001 |
+
# # For now, let's skip adding it to DB and delete temp file
|
| 1002 |
+
# if os.path.exists(temp_path): os.remove(temp_path)
|
| 1003 |
+
# continue # Skip to next file
|
| 1004 |
+
# except Exception: # HfHubHTTPError with 404 means file doesn't exist, proceed
|
| 1005 |
+
# pass
|
| 1006 |
+
|
| 1007 |
+
# Upload to Hugging Face
|
| 1008 |
+
logging.info(f"Uploading '{temp_path}' to '{file_path_in_repo}' in repo '{REPO_ID}'...")
|
| 1009 |
+
api.upload_file(
|
| 1010 |
+
path_or_fileobj=temp_path,
|
| 1011 |
+
path_in_repo=file_path_in_repo,
|
| 1012 |
+
repo_id=REPO_ID,
|
| 1013 |
+
repo_type="dataset",
|
| 1014 |
+
token=HF_TOKEN_WRITE,
|
| 1015 |
+
commit_message=f"User '{username}' uploaded: {filename}"
|
| 1016 |
+
)
|
| 1017 |
+
logging.info(f"Successfully uploaded '{filename}' to Hugging Face for user '{username}'.")
|
| 1018 |
+
|
| 1019 |
+
# Get file info for database
|
| 1020 |
+
file_info = {
|
| 1021 |
+
'filename': filename, # Store secured filename
|
| 1022 |
+
'original_filename': original_filename, # Optionally store original name
|
| 1023 |
+
'path': file_path_in_repo,
|
| 1024 |
+
'type': get_file_type(filename),
|
| 1025 |
+
'upload_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 1026 |
+
# Consider adding file size: 'size': os.path.getsize(temp_path)
|
| 1027 |
+
}
|
| 1028 |
+
processed_files_info.append(file_info)
|
| 1029 |
+
|
| 1030 |
+
except Exception as upload_err:
|
| 1031 |
+
logging.error(f"Error processing or uploading file '{filename}' for user '{username}': {upload_err}", exc_info=True)
|
| 1032 |
+
errors_occurred = True
|
| 1033 |
+
finally:
|
| 1034 |
+
# Clean up temporary file
|
| 1035 |
+
if os.path.exists(temp_path):
|
| 1036 |
+
try:
|
| 1037 |
+
os.remove(temp_path)
|
| 1038 |
+
except OSError as remove_err:
|
| 1039 |
+
logging.error(f"Error removing temporary file '{temp_path}': {remove_err}")
|
| 1040 |
+
|
| 1041 |
+
|
| 1042 |
+
# --- Update Database if uploads were successful ---
|
| 1043 |
+
if processed_files_info:
|
| 1044 |
+
current_data = load_data() # Reload data to avoid race conditions
|
| 1045 |
+
user_data_for_update = current_data['users'].setdefault(username, {'files': []}) # Ensure user exists
|
| 1046 |
+
user_files_list_for_update = user_data_for_update.setdefault('files', [])
|
| 1047 |
+
user_files_list_for_update.extend(processed_files_info) # Add new files
|
| 1048 |
+
try:
|
| 1049 |
+
save_data(current_data)
|
| 1050 |
+
flash(f"{len(processed_files_info)} файл(ов) успешно загружено!", 'success')
|
| 1051 |
+
except Exception as save_err:
|
| 1052 |
+
logging.error(f"CRITICAL: Failed to save data after successful uploads for user {username}: {save_err}", exc_info=True)
|
| 1053 |
+
flash('Файлы были загружены в хранилище, но произошла ошибка при обновлении списка файлов. Свяжитесь с администратором.', 'error')
|
| 1054 |
+
errors_occurred = True # Mark as error even if uploads worked but save failed
|
| 1055 |
+
|
| 1056 |
+
# --- Final Feedback ---
|
| 1057 |
+
if errors_occurred and not processed_files_info:
|
| 1058 |
+
flash('Произошла ошибка при загрузке всех файлов.', 'error')
|
| 1059 |
+
elif errors_occurred:
|
| 1060 |
+
flash('Некоторые файлы не удалось загрузить.', 'warning') # Use warning if some succeeded
|
| 1061 |
+
|
| 1062 |
+
|
| 1063 |
+
# Cleanup uploads directory if empty (optional)
|
| 1064 |
+
try:
|
| 1065 |
+
if not os.listdir(uploads_dir):
|
| 1066 |
+
os.rmdir(uploads_dir)
|
| 1067 |
+
except OSError:
|
| 1068 |
+
pass # Ignore errors if dir is not empty or other issues
|
| 1069 |
+
|
| 1070 |
+
# Use AJAX response for progress bar version, otherwise redirect
|
| 1071 |
+
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
|
| 1072 |
+
# If request came via AJAX (like the progress bar script)
|
| 1073 |
+
# Return JSON instead of redirecting to let JS handle it
|
| 1074 |
+
# Note: The provided JS script uses location.reload(), so this might not be strictly needed
|
| 1075 |
+
# unless the JS is changed to handle the response differently.
|
| 1076 |
+
return jsonify({'status': 'completed', 'errors': errors_occurred, 'uploaded_count': len(processed_files_info)})
|
| 1077 |
+
else:
|
| 1078 |
+
# Standard form submission, redirect back
|
| 1079 |
+
return redirect(url_for('dashboard'))
|
| 1080 |
+
|
| 1081 |
|
| 1082 |
+
# --- Render Dashboard (GET Request) ---
|
| 1083 |
html = '''
|
| 1084 |
<!DOCTYPE html>
|
| 1085 |
+
<html lang="ru">
|
| 1086 |
<head>
|
| 1087 |
<meta charset="UTF-8">
|
| 1088 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 1089 |
+
<title>Панель управления - Zeus Cloud</title>
|
| 1090 |
+
<style>{style}</style>
|
|
|
|
| 1091 |
</head>
|
| 1092 |
+
<body class="">
|
| 1093 |
+
<div class="theme-toggle" id="theme-toggle">
|
| 1094 |
+
<i class="fas fa-sun"></i><i class="fas fa-moon"></i>
|
| 1095 |
+
</div>
|
| 1096 |
<div class="container">
|
| 1097 |
+
<h1><i class="fas fa-cloud"></i> Zeus Cloud</h1>
|
| 1098 |
+
<p style="text-align: center; margin-top: -20px; margin-bottom: 20px; font-size: 1.1em;">Пользователь: <strong>{{ username }}</strong></p>
|
| 1099 |
+
|
| 1100 |
+
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 1101 |
{% if messages %}
|
| 1102 |
+
{% for category, message in messages %}
|
| 1103 |
+
<div class="flash flash-{{ category }}">{{ message }}</div>
|
| 1104 |
{% endfor %}
|
| 1105 |
{% endif %}
|
| 1106 |
{% endwith %}
|
| 1107 |
+
|
| 1108 |
+
<h2><i class="fas fa-upload"></i> Загрузить новые файлы</h2>
|
| 1109 |
<form id="upload-form" method="POST" enctype="multipart/form-data">
|
| 1110 |
+
<input type="file" name="files" multiple required accept="image/*,video/*,audio/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar">
|
| 1111 |
+
<button type="submit" class="btn" id="upload-btn"><i class="fas fa-cloud-upload-alt"></i> Загрузить</button>
|
| 1112 |
</form>
|
| 1113 |
<div id="progress-container">
|
| 1114 |
+
<div id="progress-bar">0%</div>
|
| 1115 |
</div>
|
| 1116 |
+
|
| 1117 |
+
<h2><i class="fas fa-folder-open"></i> Ваши файлы</h2>
|
| 1118 |
<div class="file-grid">
|
| 1119 |
{% for file in user_files %}
|
| 1120 |
<div class="file-item">
|
| 1121 |
+
<div class="file-preview-container">
|
| 1122 |
+
{% set file_url = "https://huggingface.co/datasets/{repo_id}/resolve/main/{file_path}" | format(repo_id=repo_id, file_path=file['path']) %}
|
| 1123 |
+
{% if file['type'] == 'video' %}
|
| 1124 |
+
<video class="file-preview" preload="metadata" muted loading="lazy" onclick="openModal('{file_url}', 'video')">
|
| 1125 |
+
<source src="{file_url}#t=0.5" type="video/mp4"> <!-- #t=0.5 for thumbnail -->
|
| 1126 |
+
Ваш браузер не поддерживает видео.
|
| 1127 |
+
</video>
|
| 1128 |
+
{% elif file['type'] == 'image' %}
|
| 1129 |
+
<img class="file-preview" src="{file_url}" alt="{file['filename']}" loading="lazy" onclick="openModal('{file_url}', 'image')">
|
| 1130 |
+
{% elif file['type'] == 'audio' %}
|
| 1131 |
+
<div class="file-preview-placeholder" onclick="openModal('{file_url}', 'audio')"><i class="fas fa-music"></i></div>
|
| 1132 |
+
{% else %}
|
| 1133 |
+
<div class="file-preview-placeholder"><i class="fas fa-file-alt"></i></div>
|
| 1134 |
+
{% endif %}
|
| 1135 |
+
</div>
|
| 1136 |
+
<div class="file-info">
|
| 1137 |
+
<p class="filename" title="{{ file.get('original_filename', file['filename']) }}">{{ file['filename'] }}</p>
|
| 1138 |
+
<p class="filedate">{{ file['upload_date'] }}</p>
|
| 1139 |
+
</div>
|
| 1140 |
+
<div class="file-actions">
|
| 1141 |
+
<a href="{{ url_for('download_file', file_path=file['path'], filename=file['filename']) }}" class="btn download-btn" title="Скачать">
|
| 1142 |
+
<i class="fas fa-download"></i>
|
| 1143 |
+
</a>
|
| 1144 |
+
<a href="{{ url_for('delete_file', file_path=file['path']) }}" class="btn delete-btn" title="Удалить" onclick="return confirm('Вы уверены, что хотите безвозвратно удалить этот файл \\'{{ file['filename'] }}\\'?');">
|
| 1145 |
+
<i class="fas fa-trash-alt"></i>
|
| 1146 |
+
</a>
|
| 1147 |
+
</div>
|
| 1148 |
</div>
|
| 1149 |
+
{% else %} {# Use else directly with for loop #}
|
| 1150 |
+
<p>У вас пока нет загруженных файлов. Начните загрузку!</p>
|
| 1151 |
{% endfor %}
|
|
|
|
|
|
|
|
|
|
| 1152 |
</div>
|
| 1153 |
+
|
| 1154 |
+
<a href="{{ url_for('logout') }}" class="btn" style="margin-top: 40px; background-color: var(--accent);" id="logout-btn">
|
| 1155 |
+
<i class="fas fa-sign-out-alt"></i> Выйти
|
| 1156 |
+
</a>
|
| 1157 |
+
<a href="{{ url_for('admin_panel') }}" class="btn" style="margin-top: 40px; margin-left: 10px; background-color: var(--secondary);" id="admin-btn">
|
| 1158 |
+
<i class="fas fa-user-shield"></i> Админ Панель
|
| 1159 |
+
</a>
|
| 1160 |
</div>
|
| 1161 |
+
|
| 1162 |
+
<!-- Media Modal -->
|
| 1163 |
+
<div class="modal" id="mediaModal" onclick="closeModalOnClick(event)">
|
| 1164 |
+
<div class="modal-content" onclick="event.stopPropagation()"> <!-- Prevent closing when clicking content -->
|
| 1165 |
+
<div id="modalContentArea"></div>
|
| 1166 |
+
<span class="modal-close" onclick="closeModal()">×</span>
|
| 1167 |
+
</div>
|
| 1168 |
</div>
|
| 1169 |
+
|
| 1170 |
<script>
|
| 1171 |
+
{script_common} // Include common script (theme toggle)
|
| 1172 |
+
|
| 1173 |
+
// --- Dashboard Specific Script ---
|
| 1174 |
+
function openModal(src, type) {{
|
| 1175 |
const modal = document.getElementById('mediaModal');
|
| 1176 |
+
const modalContent = document.getElementById('modalContentArea');
|
| 1177 |
+
modalContent.innerHTML = ''; // Clear previous content
|
| 1178 |
+
|
| 1179 |
+
if (type === 'video') {{
|
| 1180 |
+
modalContent.innerHTML = `<video controls autoplay><source src="${{src}}" type="video/mp4">Ваш браузер не поддерживает видео.</video>`;
|
| 1181 |
+
}} else if (type === 'image') {{
|
| 1182 |
+
modalContent.innerHTML = `<img src="${{src}}" alt="Просмотр изображения">`;
|
| 1183 |
+
}} else if (type === 'audio') {{
|
| 1184 |
+
modalContent.innerHTML = `<audio controls autoplay><source src="${{src}}">Ваш браузер не поддерживает аудио.</audio>`;
|
| 1185 |
+
}}
|
| 1186 |
+
// Add handlers for other types if needed
|
| 1187 |
+
|
| 1188 |
+
modal.style.display = 'flex'; // Show modal
|
| 1189 |
+
// Optional: Add class to body to prevent scrolling
|
| 1190 |
+
document.body.style.overflow = 'hidden';
|
| 1191 |
+
}}
|
| 1192 |
|
| 1193 |
+
function closeModal() {{
|
| 1194 |
+
const modal = document.getElementById('mediaModal');
|
| 1195 |
+
const modalContent = document.getElementById('modalContentArea');
|
| 1196 |
+
modal.style.display = 'none'; // Hide modal
|
| 1197 |
+
modalContent.innerHTML = ''; // Clear content to stop playback etc.
|
| 1198 |
+
// Optional: Restore body scrolling
|
| 1199 |
+
document.body.style.overflow = 'auto';
|
| 1200 |
+
}}
|
| 1201 |
+
|
| 1202 |
+
function closeModalOnClick(event) {{
|
| 1203 |
+
// Close only if the click is directly on the modal backdrop (not its children)
|
| 1204 |
+
if (event.target.id === 'mediaModal') {{
|
| 1205 |
+
closeModal();
|
| 1206 |
+
}}
|
| 1207 |
+
}}
|
| 1208 |
+
|
| 1209 |
+
// --- Upload Progress ---
|
| 1210 |
const form = document.getElementById('upload-form');
|
| 1211 |
const progressBar = document.getElementById('progress-bar');
|
| 1212 |
const progressContainer = document.getElementById('progress-container');
|
| 1213 |
const uploadBtn = document.getElementById('upload-btn');
|
| 1214 |
+
const fileInput = form.querySelector('input[type="file"]');
|
| 1215 |
|
| 1216 |
+
form.addEventListener('submit', function(e) {{
|
| 1217 |
+
e.preventDefault(); // Prevent default submission
|
| 1218 |
+
|
| 1219 |
+
const files = fileInput.files;
|
| 1220 |
+
if (files.length === 0) {{
|
| 1221 |
+
alert('Пожалуйста, выберите файлы для загрузки.');
|
| 1222 |
return;
|
| 1223 |
+
}}
|
| 1224 |
+
const MAX_FILES = 20; // Should match server-side limit
|
| 1225 |
+
if (files.length > MAX_FILES) {{
|
| 1226 |
+
alert(`Максимум ${MAX_FILES} файлов за раз! Выбрано: ${files.length}`);
|
| 1227 |
+
return;
|
| 1228 |
+
}}
|
| 1229 |
|
| 1230 |
const formData = new FormData(form);
|
| 1231 |
progressContainer.style.display = 'block';
|
| 1232 |
progressBar.style.width = '0%';
|
| 1233 |
+
progressBar.textContent = '0%';
|
| 1234 |
uploadBtn.disabled = true;
|
| 1235 |
+
uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Загрузка...'; // Indicate loading
|
| 1236 |
|
| 1237 |
const xhr = new XMLHttpRequest();
|
| 1238 |
xhr.open('POST', '/dashboard', true);
|
| 1239 |
+
// Important for backend to know it's AJAX
|
| 1240 |
+
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
|
| 1241 |
|
| 1242 |
+
xhr.upload.onprogress = function(event) {{
|
| 1243 |
+
if (event.lengthComputable) {{
|
| 1244 |
+
const percent = Math.round((event.loaded / event.total) * 100);
|
| 1245 |
progressBar.style.width = percent + '%';
|
| 1246 |
+
progressBar.textContent = percent + '%';
|
| 1247 |
+
}}
|
| 1248 |
+
}};
|
| 1249 |
+
|
| 1250 |
+
xhr.onload = function() {{
|
| 1251 |
+
progressContainer.style.display = 'none'; // Hide progress bar on completion/error
|
| 1252 |
+
uploadBtn.disabled = false;
|
| 1253 |
+
uploadBtn.innerHTML = '<i class="fas fa-cloud-upload-alt"></i> Загрузить'; // Restore button text
|
| 1254 |
+
|
| 1255 |
+
if (xhr.status >= 200 && xhr.status < 300) {{
|
| 1256 |
+
// Success - reload the page to show new files
|
| 1257 |
+
// Consider parsing JSON response if you want more granular updates without full reload
|
| 1258 |
+
// For now, reload is simple and effective
|
| 1259 |
+
console.log('Upload successful, reloading page...');
|
| 1260 |
+
location.reload();
|
| 1261 |
+
}} else {{
|
| 1262 |
+
// Error
|
| 1263 |
+
console.error('Upload failed with status:', xhr.status, xhr.responseText);
|
| 1264 |
+
alert('Ошибка загрузки! Статус: ' + xhr.status + '. Попробуйте снова.');
|
| 1265 |
+
}}
|
| 1266 |
+
// Reset the file input
|
| 1267 |
+
fileInput.value = '';
|
| 1268 |
+
}};
|
| 1269 |
+
|
| 1270 |
+
xhr.onerror = function() {{
|
| 1271 |
+
console.error('Upload failed due to network error.');
|
| 1272 |
+
alert('Ошибка сети при загрузке! Проверьте соединение и попробуйте снова.');
|
| 1273 |
+
progressContainer.style.display = 'none';
|
| 1274 |
+
uploadBtn.disabled = false;
|
| 1275 |
+
uploadBtn.innerHTML = '<i class="fas fa-cloud-upload-alt"></i> Загрузить';
|
| 1276 |
+
fileInput.value = '';
|
| 1277 |
+
}};
|
| 1278 |
|
| 1279 |
xhr.send(formData);
|
| 1280 |
+
}});
|
| 1281 |
|
| 1282 |
+
// --- Logout Handling ---
|
| 1283 |
+
document.getElementById('logout-btn').addEventListener('click', function(e) {{
|
| 1284 |
+
e.preventDefault(); // Prevent default link behavior
|
| 1285 |
+
localStorage.removeItem('zeusCredentials'); // Clear saved login info
|
| 1286 |
+
console.log('Credentials cleared, redirecting to logout...');
|
| 1287 |
+
window.location.href = this.href; // Proceed to logout URL
|
| 1288 |
+
}});
|
| 1289 |
</script>
|
| 1290 |
</body>
|
| 1291 |
</html>
|
| 1292 |
'''
|
| 1293 |
+
script_common = get_common_script() # Get theme toggle script
|
| 1294 |
+
return render_template_string(html, style=BASE_STYLE, script_common=script_common, username=username, user_files=user_files, repo_id=REPO_ID)
|
| 1295 |
+
|
| 1296 |
|
| 1297 |
@app.route('/download/<path:file_path>/<filename>')
|
| 1298 |
def download_file(file_path, filename):
|
| 1299 |
+
"""Handles file downloads, checking permissions."""
|
| 1300 |
if 'username' not in session:
|
| 1301 |
+
flash('Пожалуйста, войдите для скачивания файлов.', 'error')
|
| 1302 |
return redirect(url_for('login'))
|
| 1303 |
+
|
| 1304 |
username = session['username']
|
| 1305 |
data = load_data()
|
| 1306 |
+
if username not in data.get('users', {}):
|
| 1307 |
session.pop('username', None)
|
| 1308 |
+
flash('Пользователь не найден!', 'error')
|
| 1309 |
return redirect(url_for('login'))
|
| 1310 |
+
|
| 1311 |
+
user_files = data['users'][username].get('files', [])
|
| 1312 |
+
# Ensure the requested file_path belongs to the logged-in user
|
| 1313 |
+
if not any(file.get('path') == file_path for file in user_files):
|
| 1314 |
+
# Check if accessed via admin panel (allow admin download)
|
| 1315 |
+
# Simple check: is the request coming from the admin user files page?
|
| 1316 |
+
# More robust check would involve admin roles/sessions
|
| 1317 |
+
is_admin_request = request.referrer and '/admhosto/user/' in request.referrer
|
| 1318 |
+
if not is_admin_request:
|
| 1319 |
+
flash('У вас нет доступа к этому файлу или он не существует!', 'error')
|
| 1320 |
+
logging.warning(f"Access denied for user '{username}' trying to download '{file_path}'.")
|
| 1321 |
+
return redirect(url_for('dashboard'))
|
| 1322 |
+
else:
|
| 1323 |
+
# Allow download if accessed via admin page (basic check)
|
| 1324 |
+
logging.info(f"Admin download allowed for file '{file_path}'.")
|
| 1325 |
+
|
| 1326 |
+
|
| 1327 |
+
# Construct the direct download URL from Hugging Face
|
| 1328 |
+
# Use hf_hub_url for potentially better handling of URLs
|
| 1329 |
+
# file_url = hf_hub_url(repo_id=REPO_ID, filename=file_path, repo_type="dataset") # Alternative
|
| 1330 |
file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{file_path}"
|
| 1331 |
+
logging.info(f"Attempting to download file from URL: {file_url}")
|
| 1332 |
+
|
| 1333 |
+
try:
|
| 1334 |
+
# Use streaming for potentially large files
|
| 1335 |
+
response = requests.get(file_url, stream=True, allow_redirects=True, headers={'Authorization': f'Bearer {HF_TOKEN_READ}'} if HF_TOKEN_READ else None)
|
| 1336 |
+
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
|
| 1337 |
+
|
| 1338 |
+
file_content = BytesIO(response.content) # Read content into memory (consider streaming for very large files)
|
| 1339 |
+
|
| 1340 |
return send_file(
|
| 1341 |
file_content,
|
| 1342 |
as_attachment=True,
|
| 1343 |
+
download_name=filename, # Use the provided filename for the download dialog
|
| 1344 |
+
mimetype='application/octet-stream' # Generic MIME type for download
|
| 1345 |
)
|
| 1346 |
+
|
| 1347 |
+
except requests.exceptions.RequestException as req_err:
|
| 1348 |
+
logging.error(f"Error downloading file '{file_path}' from Hugging Face: {req_err}", exc_info=True)
|
| 1349 |
+
status_code = req_err.response.status_code if req_err.response else 'N/A'
|
| 1350 |
+
if status_code == 404:
|
| 1351 |
+
flash(f'Ошибка: Файл не найден в хранилище ({status_code}). Возможно, он был удален.', 'error')
|
| 1352 |
+
else:
|
| 1353 |
+
flash(f'Ошибка при скачивании файла ({status_code}). Попробуйте позже.', 'error')
|
| 1354 |
+
# Redirect back to where the user came from, if possible
|
| 1355 |
+
return redirect(request.referrer or url_for('dashboard'))
|
| 1356 |
+
except Exception as e:
|
| 1357 |
+
logging.error(f"Unexpected error during file download '{file_path}': {e}", exc_info=True)
|
| 1358 |
+
flash('Произошла непредвиденная ошибка при скачивании файла.', 'error')
|
| 1359 |
+
return redirect(request.referrer or url_for('dashboard'))
|
| 1360 |
+
|
| 1361 |
|
| 1362 |
@app.route('/delete/<path:file_path>')
|
| 1363 |
def delete_file(file_path):
|
| 1364 |
+
"""Handles file deletion from HF and database."""
|
| 1365 |
if 'username' not in session:
|
| 1366 |
+
flash('Пожалуйста, войдите, чтобы удалять файлы.', 'error')
|
| 1367 |
return redirect(url_for('login'))
|
| 1368 |
+
|
| 1369 |
username = session['username']
|
| 1370 |
data = load_data()
|
| 1371 |
+
if username not in data.get('users', {}):
|
| 1372 |
session.pop('username', None)
|
| 1373 |
+
flash('Пользователь не найден!', 'error')
|
| 1374 |
return redirect(url_for('login'))
|
| 1375 |
+
|
| 1376 |
+
user_files = data['users'][username].get('files', [])
|
| 1377 |
+
file_to_delete_info = next((file for file in user_files if file.get('path') == file_path), None)
|
| 1378 |
+
|
| 1379 |
+
if not file_to_delete_info:
|
| 1380 |
+
flash('Файл не найден в вашем списке!', 'error')
|
| 1381 |
return redirect(url_for('dashboard'))
|
| 1382 |
+
|
| 1383 |
+
if not HF_TOKEN_WRITE:
|
| 1384 |
+
flash('Ошибка: Удаление невозможно. Отсутствует токен для записи в Hugging Face.', 'error')
|
| 1385 |
+
return redirect(url_for('dashboard'))
|
| 1386 |
+
|
| 1387 |
try:
|
| 1388 |
api = HfApi()
|
| 1389 |
+
logging.info(f"Attempting to delete file '{file_path}' from repo '{REPO_ID}' for user '{username}'...")
|
| 1390 |
api.delete_file(
|
| 1391 |
path_in_repo=file_path,
|
| 1392 |
repo_id=REPO_ID,
|
| 1393 |
repo_type="dataset",
|
| 1394 |
token=HF_TOKEN_WRITE,
|
| 1395 |
+
commit_message=f"User '{username}' deleted: {file_path}"
|
| 1396 |
)
|
| 1397 |
+
logging.info(f"Successfully deleted file '{file_path}' from Hugging Face.")
|
| 1398 |
+
|
| 1399 |
+
# Remove file from user's list in the database
|
| 1400 |
+
# Create a *new* list excluding the deleted file
|
| 1401 |
+
data['users'][username]['files'] = [f for f in user_files if f.get('path') != file_path]
|
| 1402 |
+
|
| 1403 |
+
# Save the updated data
|
| 1404 |
save_data(data)
|
| 1405 |
+
flash(f"Файл '{file_to_delete_info.get('filename', file_path)}' успешно удален!", 'success')
|
| 1406 |
+
|
| 1407 |
except Exception as e:
|
| 1408 |
+
# More specific error handling could be added here (e.g., HfHubHTTPError)
|
| 1409 |
+
logging.error(f"Error deleting file '{file_path}' for user '{username}': {e}", exc_info=True)
|
| 1410 |
+
flash('Ошибка при удалении файла из хранилища или базы данных. Файл может все еще существовать.', 'error')
|
| 1411 |
+
|
| 1412 |
return redirect(url_for('dashboard'))
|
| 1413 |
|
| 1414 |
+
|
| 1415 |
@app.route('/logout')
|
| 1416 |
def logout():
|
| 1417 |
+
"""Logs the user out."""
|
| 1418 |
+
username = session.pop('username', None) # Remove username from session
|
| 1419 |
+
# No need to clear localStorage here, handled by JS on button click
|
| 1420 |
+
if username:
|
| 1421 |
+
logging.info(f"User '{username}' logged out.")
|
| 1422 |
+
flash('Вы успешно вышли из системы.', 'success')
|
| 1423 |
+
else:
|
| 1424 |
+
flash('Вы не были авторизованы.', 'info') # Optional message if somehow accessed directly
|
| 1425 |
return redirect(url_for('login'))
|
| 1426 |
|
| 1427 |
+
# --- Admin Panel Routes ---
|
| 1428 |
+
@app.route('/admhosto') # Keep the obscure path
|
| 1429 |
def admin_panel():
|
| 1430 |
+
"""Displays the admin panel with a list of users."""
|
| 1431 |
+
# Basic security: Check if logged-in user is allowed admin access
|
| 1432 |
+
# In a real app, this should be based on roles, not just session existence
|
| 1433 |
+
# For now, just checking if *any* user is logged in (very basic)
|
| 1434 |
+
# if 'username' not in session:
|
| 1435 |
+
# flash('Доступ запрещен.', 'error')
|
| 1436 |
+
# return redirect(url_for('login'))
|
| 1437 |
+
|
| 1438 |
data = load_data()
|
| 1439 |
+
users = data.get('users', {}) # Use .get for safer access
|
| 1440 |
+
|
| 1441 |
html = '''
|
| 1442 |
<!DOCTYPE html>
|
| 1443 |
+
<html lang="ru">
|
| 1444 |
<head>
|
| 1445 |
<meta charset="UTF-8">
|
| 1446 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 1447 |
<title>Админ-панель - Zeus Cloud</title>
|
| 1448 |
+
<style>{style}</style>
|
|
|
|
| 1449 |
</head>
|
| 1450 |
+
<body class="">
|
| 1451 |
+
<div class="theme-toggle" id="theme-toggle">
|
| 1452 |
+
<i class="fas fa-sun"></i><i class="fas fa-moon"></i>
|
| 1453 |
+
</div>
|
| 1454 |
<div class="container">
|
| 1455 |
+
<h1><i class="fas fa-user-shield"></i> Админ-панель Zeus Cloud</h1>
|
| 1456 |
<h2>Список пользователей</h2>
|
| 1457 |
<div class="user-list">
|
| 1458 |
+
{% if users %}
|
| 1459 |
+
{% for username, user_data in users.items() | sort %} {# Sort users alphabetically #}
|
| 1460 |
+
<div class="user-item">
|
| 1461 |
+
<a href="{{ url_for('admin_user_files', username=username) }}">{{ username }}</a>
|
| 1462 |
+
<p>Дата регистрации: {{ user_data.get('created_at', 'N/A') }}</p>
|
| 1463 |
+
<p>Количество файлов: {{ user_data.get('files', []) | length }}</p>
|
| 1464 |
+
{# Add more user info or actions here if needed #}
|
| 1465 |
+
{# Example: Delete user button (implement with caution!) #}
|
| 1466 |
+
{# <a href="/admhosto/delete_user/{{ username }}" class="btn delete-btn" style="font-size: 0.8em; padding: 5px 10px;" onclick="return confirm('УДАЛИТЬ пользователя {{ username }} и ВСЕ ЕГО ФАЙЛЫ? Это действие необратимо!')"><i class="fas fa-user-slash"></i> Удалить</a> #}
|
| 1467 |
+
</div>
|
| 1468 |
+
{% endfor %}
|
| 1469 |
+
{% else %}
|
| 1470 |
<p>Пользователей пока нет.</p>
|
| 1471 |
{% endif %}
|
| 1472 |
</div>
|
| 1473 |
+
<a href="{{ url_for('dashboard') }}" class="btn" style="margin-top: 30px;"><i class="fas fa-arrow-left"></i> Назад в Дашборд</a>
|
| 1474 |
</div>
|
| 1475 |
+
<script>{script}</script>
|
| 1476 |
</body>
|
| 1477 |
</html>
|
| 1478 |
'''
|
| 1479 |
+
script = get_common_script()
|
| 1480 |
+
return render_template_string(html, style=BASE_STYLE, script=script, users=users)
|
| 1481 |
+
|
| 1482 |
|
| 1483 |
@app.route('/admhosto/user/<username>')
|
| 1484 |
def admin_user_files(username):
|
| 1485 |
+
"""Displays files for a specific user (Admin view)."""
|
| 1486 |
+
# Basic security check (as above)
|
| 1487 |
+
# if 'username' not in session:
|
| 1488 |
+
# flash('Доступ запрещен.', 'error')
|
| 1489 |
+
# return redirect(url_for('login'))
|
| 1490 |
+
|
| 1491 |
data = load_data()
|
| 1492 |
+
if username not in data.get('users', {}):
|
| 1493 |
+
flash(f'Пользователь "{username}" не найден!', 'error')
|
| 1494 |
return redirect(url_for('admin_panel'))
|
| 1495 |
+
|
| 1496 |
+
user_data = data['users'][username]
|
| 1497 |
+
user_files_list = user_data.get('files', [])
|
| 1498 |
+
user_files = sorted(user_files_list, key=lambda x: x.get('upload_date', ''), reverse=True)
|
| 1499 |
+
|
| 1500 |
html = '''
|
| 1501 |
<!DOCTYPE html>
|
| 1502 |
+
<html lang="ru">
|
| 1503 |
<head>
|
| 1504 |
<meta charset="UTF-8">
|
| 1505 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 1506 |
<title>Файлы пользователя {{ username }} - Zeus Cloud</title>
|
| 1507 |
+
<style>{style}</style>
|
|
|
|
| 1508 |
</head>
|
| 1509 |
+
<body class="">
|
| 1510 |
+
<div class="theme-toggle" id="theme-toggle">
|
| 1511 |
+
<i class="fas fa-sun"></i><i class="fas fa-moon"></i>
|
| 1512 |
+
</div>
|
| 1513 |
<div class="container">
|
| 1514 |
+
<h1><i class="fas fa-folder-open"></i> Файлы пользователя: {{ username }}</h1>
|
| 1515 |
+
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 1516 |
{% if messages %}
|
| 1517 |
+
{% for category, message in messages %}
|
| 1518 |
+
<div class="flash flash-{{ category }}">{{ message }}</div>
|
| 1519 |
{% endfor %}
|
| 1520 |
{% endif %}
|
| 1521 |
{% endwith %}
|
| 1522 |
+
|
| 1523 |
<div class="file-grid">
|
| 1524 |
+
{% for file in user_files %}
|
| 1525 |
<div class="file-item">
|
| 1526 |
+
<div class="file-preview-container">
|
| 1527 |
+
{% set file_url = "https://huggingface.co/datasets/{repo_id}/resolve/main/{file_path}" | format(repo_id=repo_id, file_path=file['path']) %}
|
| 1528 |
+
{% if file['type'] == 'video' %}
|
| 1529 |
+
<video class="file-preview" preload="metadata" muted loading="lazy" onclick="openModal('{file_url}', 'video')">
|
| 1530 |
+
<source src="{file_url}#t=0.5" type="video/mp4">
|
| 1531 |
+
Ваш браузер не поддерживает видео.
|
| 1532 |
+
</video>
|
| 1533 |
+
{% elif file['type'] == 'image' %}
|
| 1534 |
+
<img class="file-preview" src="{file_url}" alt="{file['filename']}" loading="lazy" onclick="openModal('{file_url}', 'image')">
|
| 1535 |
+
{% elif file['type'] == 'audio' %}
|
| 1536 |
+
<div class="file-preview-placeholder" onclick="openModal('{file_url}', 'audio')"><i class="fas fa-music"></i></div>
|
| 1537 |
+
{% else %}
|
| 1538 |
+
<div class="file-preview-placeholder"><i class="fas fa-file-alt"></i></div>
|
| 1539 |
+
{% endif %}
|
| 1540 |
+
</div>
|
| 1541 |
+
<div class="file-info">
|
| 1542 |
+
<p class="filename" title="{{ file.get('original_filename', file['filename']) }}">{{ file['filename'] }}</p>
|
| 1543 |
+
<p class="filedate">{{ file['upload_date'] }}</p>
|
| 1544 |
+
</div>
|
| 1545 |
+
<div class="file-actions">
|
| 1546 |
+
{# Admin can download any user's file via the download route #}
|
| 1547 |
+
<a href="{{ url_for('download_file', file_path=file['path'], filename=file['filename']) }}" class="btn download-btn" title="Скачать">
|
| 1548 |
+
<i class="fas fa-download"></i>
|
| 1549 |
+
</a>
|
| 1550 |
+
{# Add admin-specific delete if needed - CAREFUL! #}
|
| 1551 |
+
{# <a href="/admhosto/delete_user_file/{{ username }}/{{ file['path'] | urlencode }}" class="btn delete-btn" title="Удалить (Админ)" onclick="return confirm('УДАЛИТЬ файл {{ file['filename'] }} пользователя {{ username }}?');">
|
| 1552 |
+
<i class="fas fa-trash-alt"></i> Admin Delete
|
| 1553 |
+
</a> #}
|
| 1554 |
+
</div>
|
| 1555 |
</div>
|
| 1556 |
+
{% else %}
|
| 1557 |
+
<p>У этого пользователя пока нет загр��женных файлов.</p>
|
| 1558 |
{% endfor %}
|
|
|
|
|
|
|
|
|
|
| 1559 |
</div>
|
| 1560 |
+
|
| 1561 |
+
<a href="{{ url_for('admin_panel') }}" class="btn" style="margin-top: 30px;"><i class="fas fa-arrow-left"></i> Назад к списку пользователей</a>
|
| 1562 |
</div>
|
| 1563 |
+
|
| 1564 |
+
<!-- Media Modal (same as dashboard) -->
|
| 1565 |
+
<div class="modal" id="mediaModal" onclick="closeModalOnClick(event)">
|
| 1566 |
+
<div class="modal-content" onclick="event.stopPropagation()">
|
| 1567 |
+
<div id="modalContentArea"></div>
|
| 1568 |
+
<span class="modal-close" onclick="closeModal()">×</span>
|
| 1569 |
+
</div>
|
| 1570 |
</div>
|
| 1571 |
+
|
| 1572 |
+
<script>
|
| 1573 |
+
{script_common} // Common script (theme toggle)
|
| 1574 |
+
|
| 1575 |
+
// Modal functions (same as dashboard)
|
| 1576 |
+
function openModal(src, type) {{
|
| 1577 |
const modal = document.getElementById('mediaModal');
|
| 1578 |
+
const modalContent = document.getElementById('modalContentArea');
|
| 1579 |
+
modalContent.innerHTML = '';
|
| 1580 |
+
if (type === 'video') modalContent.innerHTML = `<video controls autoplay><source src="${{src}}" type="video/mp4">Video not supported.</video>`;
|
| 1581 |
+
else if (type === 'image') modalContent.innerHTML = `<img src="${{src}}" alt="Image preview">`;
|
| 1582 |
+
else if (type === 'audio') modalContent.innerHTML = `<audio controls autoplay><source src="${{src}}">Audio not supported.</audio>`;
|
|
|
|
| 1583 |
modal.style.display = 'flex';
|
| 1584 |
+
document.body.style.overflow = 'hidden';
|
| 1585 |
+
}}
|
| 1586 |
+
function closeModal() {{
|
| 1587 |
+
const modal = document.getElementById('mediaModal');
|
| 1588 |
+
modal.style.display = 'none';
|
| 1589 |
+
document.getElementById('modalContentArea').innerHTML = '';
|
| 1590 |
+
document.body.style.overflow = 'auto';
|
| 1591 |
+
}}
|
| 1592 |
+
function closeModalOnClick(event) {{
|
| 1593 |
+
if (event.target.id === 'mediaModal') closeModal();
|
| 1594 |
+
}}
|
| 1595 |
</script>
|
| 1596 |
</body>
|
| 1597 |
</html>
|
| 1598 |
'''
|
| 1599 |
+
script_common = get_common_script()
|
| 1600 |
+
return render_template_string(html, style=BASE_STYLE, script_common=script_common, username=username, user_files=user_files, repo_id=REPO_ID)
|
| 1601 |
+
|
| 1602 |
+
# --- Helper Functions ---
|
| 1603 |
+
def get_common_script():
|
| 1604 |
+
"""Returns common JavaScript for theme toggling."""
|
| 1605 |
+
return '''
|
| 1606 |
+
// --- Theme Toggle Script ---
|
| 1607 |
+
const themeToggle = document.getElementById('theme-toggle');
|
| 1608 |
+
const currentTheme = localStorage.getItem('theme');
|
| 1609 |
|
| 1610 |
+
// Apply saved theme on initial load
|
| 1611 |
+
if (currentTheme === 'dark') {
|
| 1612 |
+
document.body.classList.add('dark');
|
| 1613 |
+
} else {
|
| 1614 |
+
// Default to light theme if no setting or setting is 'light'
|
| 1615 |
+
document.body.classList.remove('dark');
|
| 1616 |
+
}
|
| 1617 |
+
|
| 1618 |
+
themeToggle.addEventListener('click', () => {
|
| 1619 |
+
document.body.classList.toggle('dark');
|
| 1620 |
+
let theme = 'light';
|
| 1621 |
+
if (document.body.classList.contains('dark')) {
|
| 1622 |
+
theme = 'dark';
|
| 1623 |
+
}
|
| 1624 |
+
localStorage.setItem('theme', theme); // Save preference
|
| 1625 |
+
console.log("Theme changed to:", theme);
|
| 1626 |
+
});
|
| 1627 |
+
'''
|
| 1628 |
+
|
| 1629 |
+
# --- Main Execution ---
|
| 1630 |
if __name__ == '__main__':
|
| 1631 |
+
# Ensure essential setup runs before starting background tasks or server
|
| 1632 |
+
print("--- Initializing Zeus Cloud ---")
|
| 1633 |
+
if not os.path.exists(DATA_FILE):
|
| 1634 |
+
print(f"INFO: Local data file '{DATA_FILE}' not found. Attempting initial download or creation.")
|
| 1635 |
+
download_db_from_hf() # Attempt initial download/creation
|
| 1636 |
+
|
| 1637 |
+
# Start periodic backup in a separate thread
|
| 1638 |
+
# Check if token exists before starting thread
|
| 1639 |
+
if HF_TOKEN_WRITE:
|
| 1640 |
+
print("INFO: Starting periodic backup thread...")
|
| 1641 |
+
backup_thread = threading.Thread(target=periodic_backup, daemon=True)
|
| 1642 |
+
backup_thread.start()
|
| 1643 |
+
else:
|
| 1644 |
+
print("WARNING: Periodic backup thread NOT started because HF_TOKEN_WRITE is missing.")
|
| 1645 |
+
|
| 1646 |
+
# Run the Flask app
|
| 1647 |
+
# Use debug=False for production/semi-production
|
| 1648 |
+
# Use host='0.0.0.0' to make it accessible on the network
|
| 1649 |
+
print("--- Starting Flask Development Server ---")
|
| 1650 |
+
print("Access the application at http://<your-server-ip>:7860")
|
| 1651 |
+
app.run(debug=False, host='0.0.0.0', port=7860)
|
| 1652 |
+
|