Compare commits
7 Commits
e31e898aba
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 13ddcec9cb | |||
| 290b83840a | |||
| 1f5f6ed30f | |||
| 33f288a464 | |||
| 2ccb49a33c | |||
| c22713040f | |||
| ea7dfea4ef |
@@ -11,4 +11,4 @@ https://t.me/apksherr
|
||||
|
||||
# how 2 run
|
||||
1. pip install -r requirements.txt
|
||||
2. python3 main.py (didn't tested on fakin lыnux) (use "main.py" or "python main.py" to run it on wandws)
|
||||
2. python3 main.py (use "main.py" or "python main.py" to run it on wandws)
|
||||
269
admin_manager.py
Normal file
269
admin_manager.py
Normal file
@@ -0,0 +1,269 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Скрипт для управления административными учетными записями OldMarket
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import sqlite3
|
||||
from getpass import getpass
|
||||
import hashlib
|
||||
from datetime import datetime
|
||||
|
||||
# Добавляем путь к текущей директории для импорта моделей
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Хеширование пароля"""
|
||||
return hashlib.sha256(password.encode()).hexdigest()
|
||||
|
||||
def get_db_connection():
|
||||
"""Подключение к базе данных"""
|
||||
db_path = "oldmarket.db"
|
||||
if not os.path.exists(db_path):
|
||||
print(f"❌ База данных {db_path} не найдена!")
|
||||
sys.exit(1)
|
||||
|
||||
return sqlite3.connect(db_path)
|
||||
|
||||
def list_admins():
|
||||
"""Показать список всех администраторов"""
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute("SELECT id, username, created_at FROM admin_users ORDER BY id")
|
||||
admins = cursor.fetchall()
|
||||
|
||||
if not admins:
|
||||
print("📭 В системе нет администраторов")
|
||||
return
|
||||
|
||||
print("\n📋 Список администраторов:")
|
||||
print("-" * 50)
|
||||
print(f"{'ID':<3} {'Имя пользователя':<20} {'Дата создания'}")
|
||||
print("-" * 50)
|
||||
|
||||
for admin in admins:
|
||||
admin_id, username, created_at = admin
|
||||
print(f"{admin_id:<3} {username:<20} {created_at}")
|
||||
|
||||
def create_admin():
|
||||
"""Создать нового администратора"""
|
||||
print("\n👤 Создание нового администратора")
|
||||
|
||||
username = input("Введите имя пользователя: ").strip()
|
||||
if not username:
|
||||
print("❌ Имя пользователя не может быть пустым!")
|
||||
return
|
||||
|
||||
password = getpass("Введите пароль: ")
|
||||
if not password:
|
||||
print("❌ Пароль не может быть пустым!")
|
||||
return
|
||||
|
||||
confirm_password = getpass("Подтвердите пароль: ")
|
||||
if password != confirm_password:
|
||||
print("❌ Пароли не совпадают!")
|
||||
return
|
||||
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Проверяем, существует ли пользователь
|
||||
cursor.execute("SELECT id FROM admin_users WHERE username = ?", (username,))
|
||||
if cursor.fetchone():
|
||||
print(f"❌ Пользователь '{username}' уже существует!")
|
||||
conn.close()
|
||||
return
|
||||
|
||||
# Создаем нового администратора
|
||||
password_hash = hash_password(password)
|
||||
created_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
cursor.execute(
|
||||
"INSERT INTO admin_users (username, password_hash, created_at) VALUES (?, ?, ?)",
|
||||
(username, password_hash, created_at)
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
print(f"✅ Администратор '{username}' успешно создан!")
|
||||
|
||||
def delete_admin():
|
||||
"""Удалить администратора"""
|
||||
list_admins()
|
||||
|
||||
admin_id = input("\nВведите ID администратора для удаления: ").strip()
|
||||
if not admin_id.isdigit():
|
||||
print("❌ ID должен быть числом!")
|
||||
return
|
||||
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Получаем информацию об администраторе
|
||||
cursor.execute("SELECT username FROM admin_users WHERE id = ?", (admin_id,))
|
||||
admin = cursor.fetchone()
|
||||
|
||||
if not admin:
|
||||
print(f"❌ Администратор с ID {admin_id} не найден!")
|
||||
conn.close()
|
||||
return
|
||||
|
||||
username = admin[0]
|
||||
|
||||
# Подтверждение удаления
|
||||
confirm = input(f"⚠️ Вы уверены, что хотите удалить администратора '{username}' (ID: {admin_id})? (y/N): ")
|
||||
if confirm.lower() != 'y':
|
||||
print("❌ Удаление отменено")
|
||||
conn.close()
|
||||
return
|
||||
|
||||
# Удаляем администратора
|
||||
cursor.execute("DELETE FROM admin_users WHERE id = ?", (admin_id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
print(f"✅ Администратор '{username}' успешно удален!")
|
||||
|
||||
def change_password():
|
||||
"""Изменить пароль администратора"""
|
||||
list_admins()
|
||||
|
||||
admin_id = input("\nВведите ID администратора для смены пароля: ").strip()
|
||||
if not admin_id.isdigit():
|
||||
print("❌ ID должен быть числом!")
|
||||
return
|
||||
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Проверяем существование администратора
|
||||
cursor.execute("SELECT username FROM admin_users WHERE id = ?", (admin_id,))
|
||||
admin = cursor.fetchone()
|
||||
|
||||
if not admin:
|
||||
print(f"❌ Администратор с ID {admin_id} не найден!")
|
||||
conn.close()
|
||||
return
|
||||
|
||||
username = admin[0]
|
||||
|
||||
# Запрашиваем новый пароль
|
||||
new_password = getpass(f"Введите новый пароль для '{username}': ")
|
||||
if not new_password:
|
||||
print("❌ Пароль не может быть пустым!")
|
||||
conn.close()
|
||||
return
|
||||
|
||||
confirm_password = getpass("Подтвердите новый пароль: ")
|
||||
if new_password != confirm_password:
|
||||
print("❌ Пароли не совпадают!")
|
||||
conn.close()
|
||||
return
|
||||
|
||||
# Обновляем пароль
|
||||
new_password_hash = hash_password(new_password)
|
||||
cursor.execute(
|
||||
"UPDATE admin_users SET password_hash = ? WHERE id = ?",
|
||||
(new_password_hash, admin_id)
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
print(f"✅ Пароль для администратора '{username}' успешно изменен!")
|
||||
|
||||
def reset_default_admin():
|
||||
"""Сбросить пароль дефолтного администратора"""
|
||||
print("\n🔄 Сброс пароля дефолтного администратора")
|
||||
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Проверяем существование администратора 'admin'
|
||||
cursor.execute("SELECT id FROM admin_users WHERE username = 'admin'")
|
||||
admin = cursor.fetchone()
|
||||
|
||||
if not admin:
|
||||
# Создаем дефолтного администратора
|
||||
password_hash = hash_password("admin123")
|
||||
created_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
cursor.execute(
|
||||
"INSERT INTO admin_users (username, password_hash, created_at) VALUES (?, ?, ?)",
|
||||
("admin", password_hash, created_at)
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
print("✅ Дефолтный администратор 'admin' создан!")
|
||||
print("🔑 Логин: admin")
|
||||
print("🔑 Пароль: admin123")
|
||||
print("⚠️ Смените пароль после первого входа!")
|
||||
return
|
||||
|
||||
# Сбрасываем пароль
|
||||
new_password = "admin123"
|
||||
new_password_hash = hash_password(new_password)
|
||||
|
||||
cursor.execute(
|
||||
"UPDATE admin_users SET password_hash = ? WHERE username = 'admin'",
|
||||
(new_password_hash,)
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
print("✅ Пароль дефолтного администратора сброшен!")
|
||||
print("🔑 Логин: admin")
|
||||
print("🔑 Пароль: admin123")
|
||||
print("⚠️ Смените пароль после входа!")
|
||||
|
||||
def show_menu():
|
||||
"""Показать меню управления"""
|
||||
print("\n" + "="*50)
|
||||
print("👑 УПРАВЛЕНИЕ АДМИНИСТРАТОРАМИ OLDMARKET")
|
||||
print("="*50)
|
||||
print("1. 📋 Список администраторов")
|
||||
print("2. 👤 Создать администратора")
|
||||
print("3. 🗑️ Удалить администратора")
|
||||
print("4. 🔑 Изменить пароль")
|
||||
print("5. 🔄 Сбросить дефолтного администратора")
|
||||
print("6. ❌ Выход")
|
||||
print("="*50)
|
||||
|
||||
def main():
|
||||
"""Главная функция"""
|
||||
try:
|
||||
while True:
|
||||
show_menu()
|
||||
choice = input("\nВыберите действие (1-6): ").strip()
|
||||
|
||||
if choice == '1':
|
||||
list_admins()
|
||||
elif choice == '2':
|
||||
create_admin()
|
||||
elif choice == '3':
|
||||
delete_admin()
|
||||
elif choice == '4':
|
||||
change_password()
|
||||
elif choice == '5':
|
||||
reset_default_admin()
|
||||
elif choice == '6':
|
||||
print("\n👋 До свидания!")
|
||||
break
|
||||
else:
|
||||
print("❌ Неверный выбор! Попробуйте снова.")
|
||||
|
||||
input("\nНажмите Enter для продолжения...")
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("\n\n👋 Программа прервана пользователем!")
|
||||
except Exception as e:
|
||||
print(f"\n❌ Произошла ошибка: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
BIN
apkinfo.7z
Normal file
BIN
apkinfo.7z
Normal file
Binary file not shown.
318
main.py
318
main.py
@@ -9,6 +9,7 @@ from datetime import datetime
|
||||
import os
|
||||
import json
|
||||
import secrets
|
||||
import random
|
||||
from typing import List, Optional
|
||||
import uvicorn
|
||||
from hashlib import sha256
|
||||
@@ -58,6 +59,24 @@ class AdminUser(Base):
|
||||
password_hash = Column(String(255))
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
|
||||
class DashboardSettings(Base):
|
||||
__tablename__ = "dashboard_settings"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
motd = Column(Text, default="Добро пожаловать в панель управления OldMarket!")
|
||||
image_filename = Column(String(255), default="dashboard_default.jpg")
|
||||
updated_at = Column(DateTime, default=datetime.utcnow)
|
||||
|
||||
class MainImage(Base):
|
||||
__tablename__ = "main_images"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
filename = Column(String(255))
|
||||
description = Column(Text)
|
||||
is_active = Column(Boolean, default=False)
|
||||
uploaded_at = Column(DateTime, default=datetime.utcnow)
|
||||
uploaded_by = Column(String(100))
|
||||
|
||||
# Создаем таблицы
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
@@ -67,6 +86,8 @@ app = FastAPI(title="OldMarket Server")
|
||||
os.makedirs("static/icons", exist_ok=True)
|
||||
os.makedirs("static/apks", exist_ok=True)
|
||||
os.makedirs("static/admin", exist_ok=True)
|
||||
os.makedirs("static/dashboard", exist_ok=True)
|
||||
os.makedirs("static/main_images", exist_ok=True)
|
||||
|
||||
# Монтируем статические файлы
|
||||
app.mount("/static", StaticFiles(directory="static"), name="static")
|
||||
@@ -101,6 +122,28 @@ def create_default_admin(db: Session):
|
||||
db.commit()
|
||||
print("Создан дефолтный администратор: admin / admin123")
|
||||
|
||||
# Создаем дефолтные настройки дашборда
|
||||
def create_default_dashboard_settings(db: Session):
|
||||
if db.query(DashboardSettings).count() == 0:
|
||||
default_settings = DashboardSettings(
|
||||
motd="Добро пожаловать в панель управления OldMarket!",
|
||||
image_filename="dashboard_default.jpg"
|
||||
)
|
||||
db.add(default_settings)
|
||||
db.commit()
|
||||
|
||||
# Создаем дефолтное главное изображение
|
||||
def create_default_main_image(db: Session):
|
||||
if db.query(MainImage).count() == 0:
|
||||
default_image = MainImage(
|
||||
filename="default_main.jpg",
|
||||
description="Дефолтное главное изображение",
|
||||
is_active=True,
|
||||
uploaded_by="system"
|
||||
)
|
||||
db.add(default_image)
|
||||
db.commit()
|
||||
|
||||
# Сессии для аутентификации
|
||||
sessions = {}
|
||||
|
||||
@@ -130,7 +173,38 @@ def require_auth(request: Request, db: Session = Depends(get_db)):
|
||||
)
|
||||
return user
|
||||
|
||||
# API endpoints для клиентов (старая совместимость)
|
||||
# Корневой endpoint - отдает изображение
|
||||
@app.get("/")
|
||||
def get_main_image(db: Session = Depends(get_db)):
|
||||
active_image = db.query(MainImage).filter(MainImage.is_active == True).first()
|
||||
|
||||
if active_image:
|
||||
image_path = f"static/main_images/{active_image.filename}"
|
||||
if os.path.exists(image_path):
|
||||
return FileResponse(
|
||||
image_path,
|
||||
media_type="image/jpeg",
|
||||
filename=active_image.filename
|
||||
)
|
||||
|
||||
all_images = db.query(MainImage).all()
|
||||
if all_images:
|
||||
random_image = random.choice(all_images)
|
||||
image_path = f"static/main_images/{random_image.filename}"
|
||||
if os.path.exists(image_path):
|
||||
return FileResponse(
|
||||
image_path,
|
||||
media_type="image/jpeg",
|
||||
filename=random_image.filename
|
||||
)
|
||||
|
||||
default_path = "static/main_images/default_main.jpg"
|
||||
if os.path.exists(default_path):
|
||||
return FileResponse(default_path, media_type="image/jpeg")
|
||||
else:
|
||||
raise HTTPException(status_code=404, detail="No images available")
|
||||
|
||||
# API endpoints для клиентов
|
||||
@app.get("/api/apps")
|
||||
def get_apps(db: Session = Depends(get_db)):
|
||||
apps = db.query(App).all()
|
||||
@@ -163,14 +237,12 @@ def get_reviews(app_id: int, db: Session = Depends(get_db)):
|
||||
for review in reviews
|
||||
]
|
||||
|
||||
# Скачивание основной версии приложения
|
||||
@app.get("/api/download/{app_id}")
|
||||
def download_app(app_id: int, db: Session = Depends(get_db)):
|
||||
app = db.query(App).filter(App.id == app_id).first()
|
||||
if not app:
|
||||
raise HTTPException(status_code=404, detail="App not found")
|
||||
|
||||
# Увеличиваем счетчик загрузок
|
||||
app.downloads = (app.downloads or 0) + 1
|
||||
db.commit()
|
||||
|
||||
@@ -184,19 +256,16 @@ def download_app(app_id: int, db: Session = Depends(get_db)):
|
||||
media_type='application/vnd.android.package-archive'
|
||||
)
|
||||
|
||||
# Скачивание конкретной версии приложения
|
||||
@app.get("/api/download/{app_id}/{version}")
|
||||
def download_app_version(app_id: int, version: str, db: Session = Depends(get_db)):
|
||||
app = db.query(App).filter(App.id == app_id).first()
|
||||
if not app:
|
||||
raise HTTPException(status_code=404, detail="App not found")
|
||||
|
||||
# Ищем нужную версию в списке версий
|
||||
versions = json.loads(app.versions) if app.versions else []
|
||||
target_version = None
|
||||
|
||||
for ver in versions:
|
||||
# Сравниваем версию, игнорируя регистр и пробелы
|
||||
if ver.get("version", "").replace(" ", "").lower() == version.replace(" ", "").lower():
|
||||
target_version = ver
|
||||
break
|
||||
@@ -204,7 +273,6 @@ def download_app_version(app_id: int, version: str, db: Session = Depends(get_db
|
||||
if not target_version:
|
||||
raise HTTPException(status_code=404, detail=f"Version '{version}' not found for this app")
|
||||
|
||||
# Увеличиваем счетчик загрузок основной версии
|
||||
app.downloads = (app.downloads or 0) + 1
|
||||
db.commit()
|
||||
|
||||
@@ -226,6 +294,8 @@ def download_app_version(app_id: int, version: str, db: Session = Depends(get_db
|
||||
@app.get("/admin/login", response_class=HTMLResponse)
|
||||
def admin_login(request: Request, db: Session = Depends(get_db)):
|
||||
create_default_admin(db)
|
||||
create_default_dashboard_settings(db)
|
||||
create_default_main_image(db)
|
||||
return templates.TemplateResponse("login.html", {"request": request})
|
||||
|
||||
@app.post("/admin/login")
|
||||
@@ -259,16 +329,19 @@ def admin_panel(request: Request, user: AdminUser = Depends(require_auth), db: S
|
||||
apps_count = db.query(App).count()
|
||||
reviews_count = db.query(Review).count()
|
||||
|
||||
# ИСПРАВЛЕННАЯ СТРОКА: используем func.sum для получения суммы загрузок
|
||||
total_downloads_result = db.query(func.sum(App.downloads)).scalar()
|
||||
total_downloads = total_downloads_result if total_downloads_result is not None else 0
|
||||
|
||||
dashboard_settings = db.query(DashboardSettings).first()
|
||||
|
||||
return templates.TemplateResponse("admin.html", {
|
||||
"request": request,
|
||||
"apps_count": apps_count,
|
||||
"reviews_count": reviews_count,
|
||||
"total_downloads": total_downloads,
|
||||
"username": user.username
|
||||
"username": user.username,
|
||||
"motd": dashboard_settings.motd if dashboard_settings else "Добро пожаловать!",
|
||||
"dashboard_image": dashboard_settings.image_filename if dashboard_settings else "dashboard_default.jpg"
|
||||
})
|
||||
|
||||
@app.get("/admin/apps", response_class=HTMLResponse)
|
||||
@@ -294,7 +367,26 @@ def admin_reviews(request: Request, user: AdminUser = Depends(require_auth), db:
|
||||
"username": user.username
|
||||
})
|
||||
|
||||
# API для админ-панели (защищенные)
|
||||
@app.get("/admin/main-images", response_class=HTMLResponse)
|
||||
def admin_main_images(request: Request, user: AdminUser = Depends(require_auth), db: Session = Depends(get_db)):
|
||||
images = db.query(MainImage).all()
|
||||
return templates.TemplateResponse("main_images.html", {
|
||||
"request": request,
|
||||
"images": images,
|
||||
"username": user.username
|
||||
})
|
||||
|
||||
@app.get("/admin/dashboard-settings", response_class=HTMLResponse)
|
||||
def dashboard_settings(request: Request, user: AdminUser = Depends(require_auth), db: Session = Depends(get_db)):
|
||||
dashboard_settings = db.query(DashboardSettings).first()
|
||||
return templates.TemplateResponse("dashboard_settings.html", {
|
||||
"request": request,
|
||||
"username": user.username,
|
||||
"motd": dashboard_settings.motd if dashboard_settings else "",
|
||||
"dashboard_image": dashboard_settings.image_filename if dashboard_settings else "dashboard_default.jpg"
|
||||
})
|
||||
|
||||
# API для админ-панели
|
||||
@app.get("/api/admin/apps")
|
||||
def get_admin_apps(user: AdminUser = Depends(require_auth), db: Session = Depends(get_db)):
|
||||
apps = db.query(App).all()
|
||||
@@ -316,30 +408,27 @@ def create_app(
|
||||
api: str = Form(...),
|
||||
description: str = Form(...),
|
||||
is_game: bool = Form(False),
|
||||
rating: float = Form(0.0),
|
||||
apk_file: UploadFile = File(...),
|
||||
icon: UploadFile = File(...),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
# Сохраняем APK
|
||||
apk_filename = f"{package}_{version.replace(' ', '_')}.apk"
|
||||
apk_path = f"static/apks/{apk_filename}"
|
||||
with open(apk_path, "wb") as f:
|
||||
f.write(apk_file.file.read())
|
||||
|
||||
# Сохраняем иконку
|
||||
icon_filename = f"{package}_icon.png"
|
||||
icon_path = f"static/icons/{icon_filename}"
|
||||
with open(icon_path, "wb") as f:
|
||||
f.write(icon.file.read())
|
||||
|
||||
# Создаем базовую версию
|
||||
base_version = {
|
||||
"api": api,
|
||||
"apk_file": apk_filename,
|
||||
"version": version
|
||||
}
|
||||
|
||||
# Создаем запись в БД
|
||||
db_app = App(
|
||||
name=name,
|
||||
package=package,
|
||||
@@ -347,6 +436,7 @@ def create_app(
|
||||
api=api,
|
||||
description=description,
|
||||
is_game=is_game,
|
||||
rating=rating,
|
||||
apk_file=apk_filename,
|
||||
icon=icon_filename,
|
||||
screenshots="[]",
|
||||
@@ -358,7 +448,6 @@ def create_app(
|
||||
|
||||
return {"message": "Приложение создано", "app_id": db_app.id}
|
||||
|
||||
# НОВЫЙ ENDPOINT: Обновление приложения
|
||||
@app.put("/api/admin/apps/{app_id}")
|
||||
def update_app(
|
||||
app_id: int,
|
||||
@@ -377,7 +466,6 @@ def update_app(
|
||||
if not app:
|
||||
raise HTTPException(status_code=404, detail="App not found")
|
||||
|
||||
# Обновляем поля если они переданы
|
||||
if name is not None:
|
||||
app.name = name
|
||||
if package is not None:
|
||||
@@ -393,7 +481,6 @@ def update_app(
|
||||
if rating is not None:
|
||||
app.rating = rating
|
||||
|
||||
# Обновляем иконку если передана
|
||||
if icon and icon.filename:
|
||||
icon_filename = f"{app.package}_icon.png"
|
||||
icon_path = f"static/icons/{icon_filename}"
|
||||
@@ -417,13 +504,11 @@ def add_app_version(
|
||||
if not app:
|
||||
raise HTTPException(status_code=404, detail="App not found")
|
||||
|
||||
# Сохраняем APK
|
||||
apk_filename = f"{app.package}_{version.replace(' ', '_')}.apk"
|
||||
apk_path = f"static/apks/{apk_filename}"
|
||||
with open(apk_path, "wb") as f:
|
||||
f.write(apk_file.file.read())
|
||||
|
||||
# Добавляем версию
|
||||
versions = json.loads(app.versions) if app.versions else []
|
||||
new_version = {
|
||||
"api": api,
|
||||
@@ -436,29 +521,6 @@ def add_app_version(
|
||||
db.commit()
|
||||
return {"message": "Версия добавлена"}
|
||||
|
||||
@app.delete("/api/admin/apps/{app_id}")
|
||||
def delete_app(app_id: int, user: AdminUser = Depends(require_auth), db: Session = Depends(get_db)):
|
||||
app = db.query(App).filter(App.id == app_id).first()
|
||||
if app:
|
||||
# Удаляем все APK файлы версий
|
||||
versions = json.loads(app.versions) if app.versions else []
|
||||
for version in versions:
|
||||
apk_file = version.get("apk_file")
|
||||
if apk_file and os.path.exists(f"static/apks/{apk_file}"):
|
||||
os.remove(f"static/apks/{apk_file}")
|
||||
|
||||
# Удаляем иконку
|
||||
if os.path.exists(f"static/icons/{app.icon}"):
|
||||
os.remove(f"static/icons/{app.icon}")
|
||||
|
||||
# Удаляем связанные отзывы
|
||||
db.query(Review).filter(Review.app_id == app_id).delete()
|
||||
|
||||
db.delete(app)
|
||||
db.commit()
|
||||
return {"message": "Приложение удалено"}
|
||||
|
||||
# НОВЫЙ ENDPOINT: Установка основной версии из списка версий
|
||||
@app.post("/api/admin/apps/{app_id}/set-version")
|
||||
def set_main_version(
|
||||
app_id: int,
|
||||
@@ -470,7 +532,6 @@ def set_main_version(
|
||||
if not app:
|
||||
raise HTTPException(status_code=404, detail="App not found")
|
||||
|
||||
# Ищем версию в списке версий
|
||||
versions = json.loads(app.versions) if app.versions else []
|
||||
target_version = None
|
||||
|
||||
@@ -482,7 +543,6 @@ def set_main_version(
|
||||
if not target_version:
|
||||
raise HTTPException(status_code=404, detail="Version not found in app versions")
|
||||
|
||||
# Обновляем основную версию и APK файл
|
||||
app.version = version
|
||||
app.apk_file = target_version.get("apk_file")
|
||||
app.api = target_version.get("api")
|
||||
@@ -490,7 +550,25 @@ def set_main_version(
|
||||
db.commit()
|
||||
return {"message": f"Основная версия установлена на {version}"}
|
||||
|
||||
# Исправленный метод для добавления отзывов
|
||||
@app.delete("/api/admin/apps/{app_id}")
|
||||
def delete_app(app_id: int, user: AdminUser = Depends(require_auth), db: Session = Depends(get_db)):
|
||||
app = db.query(App).filter(App.id == app_id).first()
|
||||
if app:
|
||||
versions = json.loads(app.versions) if app.versions else []
|
||||
for version in versions:
|
||||
apk_file = version.get("apk_file")
|
||||
if apk_file and os.path.exists(f"static/apks/{apk_file}"):
|
||||
os.remove(f"static/apks/{apk_file}")
|
||||
|
||||
if os.path.exists(f"static/icons/{app.icon}"):
|
||||
os.remove(f"static/icons/{app.icon}")
|
||||
|
||||
db.query(Review).filter(Review.app_id == app_id).delete()
|
||||
|
||||
db.delete(app)
|
||||
db.commit()
|
||||
return {"message": "Приложение удалено"}
|
||||
|
||||
@app.post("/api/admin/reviews")
|
||||
def create_review(
|
||||
user: AdminUser = Depends(require_auth),
|
||||
@@ -504,23 +582,18 @@ def create_review(
|
||||
try:
|
||||
avatar_filename = "default_avatar.png"
|
||||
|
||||
# Обрабатываем аватар только если он действительно загружен
|
||||
if avatar and avatar.filename and avatar.filename.strip() != "":
|
||||
# Проверяем, что это изображение
|
||||
if not avatar.content_type or not avatar.content_type.startswith('image/'):
|
||||
raise HTTPException(status_code=400, detail="Файл должен быть изображением")
|
||||
|
||||
# Генерируем уникальное имя файла
|
||||
file_extension = os.path.splitext(avatar.filename)[1]
|
||||
avatar_filename = f"avatar_{int(datetime.now().timestamp())}{file_extension}"
|
||||
avatar_path = f"static/icons/{avatar_filename}"
|
||||
|
||||
# Сохраняем аватар
|
||||
contents = avatar.file.read()
|
||||
with open(avatar_path, "wb") as f:
|
||||
f.write(contents)
|
||||
|
||||
# Создаем отзыв
|
||||
db_review = Review(
|
||||
app_id=app_id,
|
||||
username=username,
|
||||
@@ -531,13 +604,15 @@ def create_review(
|
||||
user_id=1
|
||||
)
|
||||
db.add(db_review)
|
||||
db.commit()
|
||||
|
||||
review_count = db.query(Review).filter(Review.app_id == app_id).count()
|
||||
|
||||
# Обновляем счетчик отзывов у приложения
|
||||
app = db.query(App).filter(App.id == app_id).first()
|
||||
if app:
|
||||
app.review_count = db.query(Review).filter(Review.app_id == app_id).count()
|
||||
app.review_count = review_count
|
||||
db.commit()
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_review)
|
||||
|
||||
return {"message": "Отзыв создан", "review_id": db_review.id}
|
||||
@@ -552,14 +627,143 @@ def delete_review(review_id: int, user: AdminUser = Depends(require_auth), db: S
|
||||
if review:
|
||||
app_id = review.app_id
|
||||
db.delete(review)
|
||||
db.commit()
|
||||
|
||||
review_count = db.query(Review).filter(Review.app_id == app_id).count()
|
||||
|
||||
# Обновляем счетчик отзывов у приложения
|
||||
app = db.query(App).filter(App.id == app_id).first()
|
||||
if app:
|
||||
app.review_count = db.query(Review).filter(Review.app_id == app_id).count()
|
||||
app.review_count = review_count
|
||||
db.commit()
|
||||
|
||||
db.commit()
|
||||
return {"message": "Отзыв удален"}
|
||||
|
||||
# API для главных изображений
|
||||
@app.get("/api/admin/main-images")
|
||||
def get_main_images(user: AdminUser = Depends(require_auth), db: Session = Depends(get_db)):
|
||||
images = db.query(MainImage).all()
|
||||
return images
|
||||
|
||||
@app.post("/api/admin/main-images")
|
||||
def upload_main_image(
|
||||
user: AdminUser = Depends(require_auth),
|
||||
description: str = Form(""),
|
||||
image: UploadFile = File(...),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
if not image.content_type.startswith('image/'):
|
||||
raise HTTPException(status_code=400, detail="Файл должен быть изображением")
|
||||
|
||||
file_extension = os.path.splitext(image.filename)[1]
|
||||
filename = f"main_{int(datetime.now().timestamp())}{file_extension}"
|
||||
image_path = f"static/main_images/{filename}"
|
||||
|
||||
contents = image.file.read()
|
||||
with open(image_path, "wb") as f:
|
||||
f.write(contents)
|
||||
|
||||
db_image = MainImage(
|
||||
filename=filename,
|
||||
description=description,
|
||||
uploaded_by=user.username
|
||||
)
|
||||
db.add(db_image)
|
||||
db.commit()
|
||||
db.refresh(db_image)
|
||||
|
||||
return {"message": "Изображение загружено", "image_id": db_image.id}
|
||||
|
||||
@app.post("/api/admin/main-images/{image_id}/activate")
|
||||
def activate_main_image(
|
||||
image_id: int,
|
||||
user: AdminUser = Depends(require_auth),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
db.query(MainImage).update({MainImage.is_active: False})
|
||||
|
||||
image = db.query(MainImage).filter(MainImage.id == image_id).first()
|
||||
if image:
|
||||
image.is_active = True
|
||||
db.commit()
|
||||
return {"message": f"Изображение '{image.filename}' активировано"}
|
||||
else:
|
||||
raise HTTPException(status_code=404, detail="Изображение не найдено")
|
||||
|
||||
@app.delete("/api/admin/main-images/{image_id}")
|
||||
def delete_main_image(
|
||||
image_id: int,
|
||||
user: AdminUser = Depends(require_auth),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
image = db.query(MainImage).filter(MainImage.id == image_id).first()
|
||||
if image:
|
||||
if os.path.exists(f"static/main_images/{image.filename}"):
|
||||
os.remove(f"static/main_images/{image.filename}")
|
||||
|
||||
if image.is_active:
|
||||
other_image = db.query(MainImage).filter(MainImage.id != image_id).first()
|
||||
if other_image:
|
||||
other_image.is_active = True
|
||||
|
||||
db.delete(image)
|
||||
db.commit()
|
||||
return {"message": "Изображение удалено"}
|
||||
else:
|
||||
raise HTTPException(status_code=404, detail="Изображение не найдено")
|
||||
|
||||
# API для настроек дашборда
|
||||
@app.post("/api/admin/dashboard/motd")
|
||||
def update_motd(
|
||||
user: AdminUser = Depends(require_auth),
|
||||
motd: str = Form(...),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
dashboard_settings = db.query(DashboardSettings).first()
|
||||
if not dashboard_settings:
|
||||
dashboard_settings = DashboardSettings()
|
||||
db.add(dashboard_settings)
|
||||
|
||||
dashboard_settings.motd = motd
|
||||
dashboard_settings.updated_at = datetime.utcnow()
|
||||
db.commit()
|
||||
|
||||
return {"message": "MOTD обновлен"}
|
||||
|
||||
@app.post("/api/admin/dashboard/image")
|
||||
def update_dashboard_image(
|
||||
user: AdminUser = Depends(require_auth),
|
||||
image: UploadFile = File(...),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
if not image.content_type.startswith('image/'):
|
||||
raise HTTPException(status_code=400, detail="Файл должен быть изображением")
|
||||
|
||||
file_extension = os.path.splitext(image.filename)[1]
|
||||
image_filename = f"dashboard_{int(datetime.now().timestamp())}{file_extension}"
|
||||
image_path = f"static/dashboard/{image_filename}"
|
||||
|
||||
contents = image.file.read()
|
||||
with open(image_path, "wb") as f:
|
||||
f.write(contents)
|
||||
|
||||
dashboard_settings = db.query(DashboardSettings).first()
|
||||
if not dashboard_settings:
|
||||
dashboard_settings = DashboardSettings()
|
||||
db.add(dashboard_settings)
|
||||
|
||||
if (dashboard_settings.image_filename != "dashboard_default.jpg" and
|
||||
os.path.exists(f"static/dashboard/{dashboard_settings.image_filename}")):
|
||||
os.remove(f"static/dashboard/{dashboard_settings.image_filename}")
|
||||
|
||||
dashboard_settings.image_filename = image_filename
|
||||
dashboard_settings.updated_at = datetime.utcnow()
|
||||
db.commit()
|
||||
|
||||
return {"message": "Изображение дашборда обновлено"}
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run(app, host="0.0.0.0", port=5000)
|
||||
if not os.path.exists("static/main_images/default_main.jpg"):
|
||||
os.makedirs("static/main_images", exist_ok=True)
|
||||
open("static/main_images/default_main.jpg", "wb").close()
|
||||
|
||||
uvicorn.run(app, host="0.0.0.0", port=5001)
|
||||
BIN
oldmarket.db
BIN
oldmarket.db
Binary file not shown.
BIN
static/dashboard/dashboard_1760771646.jpg
Normal file
BIN
static/dashboard/dashboard_1760771646.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 206 KiB |
BIN
static/main_images/main_1760780294.jpg
Normal file
BIN
static/main_images/main_1760780294.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 50 KiB |
BIN
static/main_images/main_1760780334.jpg
Normal file
BIN
static/main_images/main_1760780334.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 216 KiB |
BIN
static/main_images/main_1760780342.jpg
Normal file
BIN
static/main_images/main_1760780342.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 152 KiB |
@@ -26,6 +26,13 @@
|
||||
margin-bottom: 30px;
|
||||
text-align: center;
|
||||
}
|
||||
.sidebar .user-info {
|
||||
background: #34495e;
|
||||
padding: 10px;
|
||||
border-radius: 5px;
|
||||
margin-bottom: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
.sidebar ul {
|
||||
list-style: none;
|
||||
}
|
||||
@@ -52,6 +59,7 @@
|
||||
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
margin-top: 20px;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.card {
|
||||
background: white;
|
||||
@@ -69,80 +77,240 @@
|
||||
font-weight: bold;
|
||||
color: #3498db;
|
||||
}
|
||||
.sidebar .user-info {
|
||||
background: #34495e;
|
||||
padding: 10px;
|
||||
.motd-section {
|
||||
background: white;
|
||||
padding: 25px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.motd-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
.motd-content {
|
||||
font-size: 1.1em;
|
||||
line-height: 1.5;
|
||||
color: #2c3e50;
|
||||
}
|
||||
.dashboard-image-section {
|
||||
background: white;
|
||||
padding: 25px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.dashboard-image {
|
||||
max-width: 100%;
|
||||
max-height: 400px;
|
||||
border-radius: 8px;
|
||||
margin-top: 15px;
|
||||
}
|
||||
.btn {
|
||||
background: #3498db;
|
||||
color: white;
|
||||
padding: 10px 20px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
margin-bottom: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
}
|
||||
.btn:hover {
|
||||
background: #2980b9;
|
||||
}
|
||||
.btn-success {
|
||||
background: #27ae60;
|
||||
}
|
||||
.btn-success:hover {
|
||||
background: #219a52;
|
||||
}
|
||||
.modal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0,0,0,0.5);
|
||||
z-index: 1000;
|
||||
}
|
||||
.modal-content {
|
||||
background: white;
|
||||
margin: 50px auto;
|
||||
padding: 30px;
|
||||
width: 80%;
|
||||
max-width: 600px;
|
||||
border-radius: 10px;
|
||||
max-height: 80vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.form-group {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 5px;
|
||||
font-weight: bold;
|
||||
}
|
||||
input, textarea, select {
|
||||
width: 100%;
|
||||
padding: 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="sidebar">
|
||||
<h2>OldMarket Admin</h2>
|
||||
<div class="user-info">
|
||||
Вы вошли как: <strong>{{ username }}</strong>
|
||||
</div>
|
||||
<ul>
|
||||
<li><a href="/admin">Дашборд</a></li>
|
||||
<li><a href="/admin/apps">Управление приложениями</a></li>
|
||||
<li><a href="/admin/reviews">Управление отзывами</a></li>
|
||||
<li><a href="/api/apps" target="_blank">API приложений</a></li>
|
||||
<li><a href="/admin/logout">Выйти</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="sidebar">
|
||||
<h2>OldMarket Admin</h2>
|
||||
<div class="user-info">
|
||||
Вы вошли как: <strong>{{ username }}</strong>
|
||||
</div>
|
||||
<ul>
|
||||
<li><a href="/admin">Дашборд</a></li>
|
||||
<li><a href="/admin/apps">Управление приложениями</a></li>
|
||||
<li><a href="/admin/reviews">Управление отзывами</a></li>
|
||||
<li><a href="/admin/main-images">Главные изображения</a></li> <!-- НОВАЯ ССЫЛКА -->
|
||||
<li><a href="/admin/dashboard-settings">Настройки дашборда</a></li>
|
||||
<li><a href="/api/apps" target="_blank">API приложений</a></li>
|
||||
<li><a href="/admin/logout">Выйти</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<h1>Дашборд админ-панели</h1>
|
||||
<p>Добро пожаловать в панель управления OldMarket</p>
|
||||
|
||||
<!-- MOTD Section -->
|
||||
<div class="motd-section">
|
||||
<div class="motd-header">
|
||||
<h2>Сообщение дня (MOTD)</h2>
|
||||
<button class="btn" onclick="showMotdModal()">Изменить MOTD</button>
|
||||
</div>
|
||||
<div class="motd-content">
|
||||
{{ motd }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Dashboard Image Section -->
|
||||
<div class="dashboard-image-section">
|
||||
<div class="motd-header">
|
||||
<h2>Изображение дашборда</h2>
|
||||
<button class="btn" onclick="showImageModal()">Изменить изображение</button>
|
||||
</div>
|
||||
<img src="/static/dashboard/{{ dashboard_image }}" alt="Dashboard Image" class="dashboard-image">
|
||||
</div>
|
||||
|
||||
<div class="dashboard-cards">
|
||||
<div class="card">
|
||||
<h3>Приложения</h3>
|
||||
<div class="number" id="apps-count">0</div>
|
||||
<div class="number" id="apps-count">{{ apps_count }}</div>
|
||||
<p>всего в каталоге</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3>Отзывы</h3>
|
||||
<div class="number" id="reviews-count">0</div>
|
||||
<div class="number" id="reviews-count">{{ reviews_count }}</div>
|
||||
<p>всего отзывов</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3>Загрузки</h3>
|
||||
<div class="number" id="downloads-count">0</div>
|
||||
<div class="number" id="downloads-count">{{ total_downloads }}</div>
|
||||
<p>всего скачиваний</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Модальное окно для изменения MOTD -->
|
||||
<div id="motdModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<h2>Изменить сообщение дня (MOTD)</h2>
|
||||
<form id="motdForm">
|
||||
<div class="form-group">
|
||||
<label>Сообщение:</label>
|
||||
<textarea name="motd" rows="4" required>{{ motd }}</textarea>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<button type="submit" class="btn">Сохранить</button>
|
||||
<button type="button" class="btn" onclick="hideMotdModal()">Отмена</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Модальное окно для изменения изображения -->
|
||||
<div id="imageModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<h2>Изменить изображение дашборда</h2>
|
||||
<form id="imageForm" enctype="multipart/form-data">
|
||||
<div class="form-group">
|
||||
<label>Выберите изображение:</label>
|
||||
<input type="file" name="image" accept="image/*" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<button type="submit" class="btn">Загрузить</button>
|
||||
<button type="button" class="btn" onclick="hideImageModal()">Отмена</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Загружаем статистику
|
||||
async function loadStats() {
|
||||
try {
|
||||
const appsResponse = await fetch('/api/admin/apps');
|
||||
const apps = await appsResponse.json();
|
||||
|
||||
document.getElementById('apps-count').textContent = apps.length;
|
||||
|
||||
let totalDownloads = 0;
|
||||
let totalReviews = 0;
|
||||
|
||||
apps.forEach(app => {
|
||||
totalDownloads += app.downloads || 0;
|
||||
// Для отзывов нужно сделать отдельный запрос, упростим
|
||||
totalReviews += app.review_count || 0;
|
||||
});
|
||||
|
||||
document.getElementById('downloads-count').textContent = totalDownloads;
|
||||
document.getElementById('reviews-count').textContent = totalReviews;
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error loading stats:', error);
|
||||
}
|
||||
function showMotdModal() {
|
||||
document.getElementById('motdModal').style.display = 'block';
|
||||
}
|
||||
|
||||
loadStats();
|
||||
function hideMotdModal() {
|
||||
document.getElementById('motdModal').style.display = 'none';
|
||||
}
|
||||
|
||||
function showImageModal() {
|
||||
document.getElementById('imageModal').style.display = 'block';
|
||||
}
|
||||
|
||||
function hideImageModal() {
|
||||
document.getElementById('imageModal').style.display = 'none';
|
||||
}
|
||||
|
||||
document.getElementById('motdForm').addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const formData = new FormData(this);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/admin/dashboard/motd', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
const result = await response.json();
|
||||
alert(result.message);
|
||||
hideMotdModal();
|
||||
location.reload();
|
||||
} catch (error) {
|
||||
alert('Ошибка при сохранении: ' + error);
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('imageForm').addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const formData = new FormData(this);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/admin/dashboard/image', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
const result = await response.json();
|
||||
alert(result.message);
|
||||
hideImageModal();
|
||||
location.reload();
|
||||
} catch (error) {
|
||||
alert('Ошибка при загрузке изображения: ' + error);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
213
templates/dashboard_settings.html
Normal file
213
templates/dashboard_settings.html
Normal file
@@ -0,0 +1,213 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Настройки дашборда - OldMarket Admin</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
.sidebar {
|
||||
width: 250px;
|
||||
background: #2c3e50;
|
||||
color: white;
|
||||
height: 100vh;
|
||||
position: fixed;
|
||||
padding: 20px;
|
||||
}
|
||||
.sidebar h2 {
|
||||
margin-bottom: 30px;
|
||||
text-align: center;
|
||||
}
|
||||
.sidebar .user-info {
|
||||
background: #34495e;
|
||||
padding: 10px;
|
||||
border-radius: 5px;
|
||||
margin-bottom: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
.sidebar ul {
|
||||
list-style: none;
|
||||
}
|
||||
.sidebar li {
|
||||
margin: 15px 0;
|
||||
}
|
||||
.sidebar a {
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
padding: 10px;
|
||||
display: block;
|
||||
border-radius: 5px;
|
||||
transition: background 0.3s;
|
||||
}
|
||||
.sidebar a:hover {
|
||||
background: #34495e;
|
||||
}
|
||||
.content {
|
||||
margin-left: 250px;
|
||||
padding: 40px;
|
||||
}
|
||||
.settings-section {
|
||||
background: white;
|
||||
padding: 25px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.settings-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
.btn {
|
||||
background: #3498db;
|
||||
color: white;
|
||||
padding: 10px 20px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
}
|
||||
.btn:hover {
|
||||
background: #2980b9;
|
||||
}
|
||||
.form-group {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 5px;
|
||||
font-weight: bold;
|
||||
}
|
||||
input, textarea, select {
|
||||
width: 100%;
|
||||
padding: 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.dashboard-image {
|
||||
max-width: 100%;
|
||||
max-height: 400px;
|
||||
border-radius: 8px;
|
||||
margin-top: 15px;
|
||||
}
|
||||
.current-settings {
|
||||
background: #f8f9fa;
|
||||
padding: 15px;
|
||||
border-radius: 5px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="sidebar">
|
||||
<h2>OldMarket Admin</h2>
|
||||
<div class="user-info">
|
||||
Вы вошли как: <strong>{{ username }}</strong>
|
||||
</div>
|
||||
<ul>
|
||||
<li><a href="/admin">Дашборд</a></li>
|
||||
<li><a href="/admin/apps">Управление приложениями</a></li>
|
||||
<li><a href="/admin/reviews">Управление отзывами</a></li>
|
||||
<li><a href="/admin/dashboard-settings">Настройки дашборда</a></li>
|
||||
<li><a href="/api/apps" target="_blank">API приложений</a></li>
|
||||
<li><a href="/admin/logout">Выйти</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<h1>Настройки дашборда</h1>
|
||||
<p>Управление сообщением дня и изображением на главной странице</p>
|
||||
|
||||
<!-- Текущие настройки -->
|
||||
<div class="settings-section">
|
||||
<h2>Текущие настройки</h2>
|
||||
<div class="current-settings">
|
||||
<p><strong>Текущее сообщение дня:</strong></p>
|
||||
<p>{{ motd }}</p>
|
||||
<p><strong>Текущее изображение:</strong></p>
|
||||
<img src="/static/dashboard/{{ dashboard_image }}" alt="Dashboard Image" class="dashboard-image">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Изменение MOTD -->
|
||||
<div class="settings-section">
|
||||
<div class="settings-header">
|
||||
<h2>Изменение сообщения дня (MOTD)</h2>
|
||||
</div>
|
||||
<form id="motdForm">
|
||||
<div class="form-group">
|
||||
<label>Сообщение дня:</label>
|
||||
<textarea name="motd" rows="4" required>{{ motd }}</textarea>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<button type="submit" class="btn">Сохранить MOTD</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Изменение изображения -->
|
||||
<div class="settings-section">
|
||||
<div class="settings-header">
|
||||
<h2>Изменение изображения дашборда</h2>
|
||||
</div>
|
||||
<form id="imageForm" enctype="multipart/form-data">
|
||||
<div class="form-group">
|
||||
<label>Выберите новое изображение:</label>
|
||||
<input type="file" name="image" accept="image/*" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<button type="submit" class="btn">Загрузить изображение</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.getElementById('motdForm').addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const formData = new FormData(this);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/admin/dashboard/motd', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
const result = await response.json();
|
||||
alert(result.message);
|
||||
location.reload();
|
||||
} catch (error) {
|
||||
alert('Ошибка при сохранении: ' + error);
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('imageForm').addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const formData = new FormData(this);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/admin/dashboard/image', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
const result = await response.json();
|
||||
alert(result.message);
|
||||
location.reload();
|
||||
} catch (error) {
|
||||
alert('Ошибка при загрузке изображения: ' + error);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
315
templates/main_images.html
Normal file
315
templates/main_images.html
Normal file
@@ -0,0 +1,315 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Управление главными изображениями - OldMarket Admin</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
.sidebar {
|
||||
width: 250px;
|
||||
background: #2c3e50;
|
||||
color: white;
|
||||
height: 100vh;
|
||||
position: fixed;
|
||||
padding: 20px;
|
||||
}
|
||||
.sidebar h2 {
|
||||
margin-bottom: 30px;
|
||||
text-align: center;
|
||||
}
|
||||
.sidebar .user-info {
|
||||
background: #34495e;
|
||||
padding: 10px;
|
||||
border-radius: 5px;
|
||||
margin-bottom: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
.sidebar ul {
|
||||
list-style: none;
|
||||
}
|
||||
.sidebar li {
|
||||
margin: 15px 0;
|
||||
}
|
||||
.sidebar a {
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
padding: 10px;
|
||||
display: block;
|
||||
border-radius: 5px;
|
||||
transition: background 0.3s;
|
||||
}
|
||||
.sidebar a:hover {
|
||||
background: #34495e;
|
||||
}
|
||||
.content {
|
||||
margin-left: 250px;
|
||||
padding: 40px;
|
||||
}
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.btn {
|
||||
background: #3498db;
|
||||
color: white;
|
||||
padding: 10px 20px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
}
|
||||
.btn:hover {
|
||||
background: #2980b9;
|
||||
}
|
||||
.btn-success {
|
||||
background: #27ae60;
|
||||
}
|
||||
.btn-success:hover {
|
||||
background: #219a52;
|
||||
}
|
||||
.btn-warning {
|
||||
background: #f39c12;
|
||||
}
|
||||
.btn-warning:hover {
|
||||
background: #e67e22;
|
||||
}
|
||||
.btn-danger {
|
||||
background: #e74c3c;
|
||||
}
|
||||
.btn-danger:hover {
|
||||
background: #c0392b;
|
||||
}
|
||||
.images-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
||||
gap: 20px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
.image-card {
|
||||
background: white;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
}
|
||||
.image-card img {
|
||||
width: 100%;
|
||||
height: 200px;
|
||||
object-fit: cover;
|
||||
}
|
||||
.image-info {
|
||||
padding: 15px;
|
||||
}
|
||||
.image-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.image-actions .btn {
|
||||
flex: 1;
|
||||
padding: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.active-badge {
|
||||
background: #27ae60;
|
||||
color: white;
|
||||
padding: 5px 10px;
|
||||
border-radius: 15px;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.modal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0,0,0,0.5);
|
||||
z-index: 1000;
|
||||
}
|
||||
.modal-content {
|
||||
background: white;
|
||||
margin: 50px auto;
|
||||
padding: 30px;
|
||||
width: 80%;
|
||||
max-width: 500px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
.form-group {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 5px;
|
||||
font-weight: bold;
|
||||
}
|
||||
input, textarea, select {
|
||||
width: 100%;
|
||||
padding: 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.preview-image {
|
||||
max-width: 100%;
|
||||
max-height: 300px;
|
||||
border-radius: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="sidebar">
|
||||
<h2>OldMarket Admin</h2>
|
||||
<div class="user-info">
|
||||
Вы вошли как: <strong>{{ username }}</strong>
|
||||
</div>
|
||||
<ul>
|
||||
<li><a href="/admin">Дашборд</a></li>
|
||||
<li><a href="/admin/apps">Управление приложениями</a></li>
|
||||
<li><a href="/admin/reviews">Управление отзывами</a></li>
|
||||
<li><a href="/admin/main-images">Главные изображения</a></li>
|
||||
<li><a href="/admin/dashboard-settings">Настройки дашборда</a></li>
|
||||
<li><a href="/api/apps" target="_blank">API приложений</a></li>
|
||||
<li><a href="/admin/logout">Выйти</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<div class="header">
|
||||
<h1>Управление главными изображениями</h1>
|
||||
<button class="btn" onclick="showUploadForm()">Загрузить изображение</button>
|
||||
</div>
|
||||
|
||||
<p>Эти изображения показываются на корневом пути <code>/</code> сервера</p>
|
||||
|
||||
<div class="images-grid">
|
||||
{% for image in images %}
|
||||
<div class="image-card">
|
||||
<img src="/static/main_images/{{ image.filename }}" alt="{{ image.description }}" onerror="this.src='/static/main_images/default_main.jpg'">
|
||||
<div class="image-info">
|
||||
<h3>{{ image.description or 'Без описания' }}</h3>
|
||||
<p><strong>Файл:</strong> {{ image.filename }}</p>
|
||||
<p><strong>Загружено:</strong> {{ image.uploaded_at.strftime('%Y-%m-%d %H:%M') }}</p>
|
||||
<p><strong>Кем:</strong> {{ image.uploaded_by }}</p>
|
||||
|
||||
<div class="image-actions">
|
||||
{% if image.is_active %}
|
||||
<span class="active-badge">АКТИВНО</span>
|
||||
{% else %}
|
||||
<button class="btn btn-success" onclick="activateImage({{ image.id }})">Сделать активным</button>
|
||||
{% endif %}
|
||||
<button class="btn btn-danger" onclick="deleteImage({{ image.id }})">Удалить</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Модальное окно для загрузки изображения -->
|
||||
<div id="uploadModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<h2>Загрузить новое изображение</h2>
|
||||
<form id="uploadForm" enctype="multipart/form-data">
|
||||
<div class="form-group">
|
||||
<label>Описание (необязательно):</label>
|
||||
<input type="text" name="description" placeholder="Описание изображения">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Выберите изображение:</label>
|
||||
<input type="file" name="image" accept="image/*" required onchange="previewImage(this)">
|
||||
<img id="imagePreview" class="preview-image" style="display: none;">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<button type="submit" class="btn">Загрузить</button>
|
||||
<button type="button" class="btn" onclick="hideUploadForm()">Отмена</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function showUploadForm() {
|
||||
document.getElementById('uploadModal').style.display = 'block';
|
||||
}
|
||||
|
||||
function hideUploadForm() {
|
||||
document.getElementById('uploadModal').style.display = 'none';
|
||||
document.getElementById('imagePreview').style.display = 'none';
|
||||
}
|
||||
|
||||
function previewImage(input) {
|
||||
const preview = document.getElementById('imagePreview');
|
||||
if (input.files && input.files[0]) {
|
||||
const reader = new FileReader();
|
||||
reader.onload = function(e) {
|
||||
preview.src = e.target.result;
|
||||
preview.style.display = 'block';
|
||||
}
|
||||
reader.readAsDataURL(input.files[0]);
|
||||
}
|
||||
}
|
||||
|
||||
async function activateImage(imageId) {
|
||||
if (confirm('Сделать это изображение активным? Оно будет показываться на корневом пути /')) {
|
||||
try {
|
||||
const response = await fetch(`/api/admin/main-images/${imageId}/activate`, {
|
||||
method: 'POST'
|
||||
});
|
||||
const result = await response.json();
|
||||
alert(result.message);
|
||||
location.reload();
|
||||
} catch (error) {
|
||||
alert('Ошибка при активации: ' + error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteImage(imageId) {
|
||||
if (confirm('Вы уверены, что хотите удалить это изображение?')) {
|
||||
try {
|
||||
const response = await fetch(`/api/admin/main-images/${imageId}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
const result = await response.json();
|
||||
alert(result.message);
|
||||
location.reload();
|
||||
} catch (error) {
|
||||
alert('Ошибка при удалении: ' + error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('uploadForm').addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const formData = new FormData(this);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/admin/main-images', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
const result = await response.json();
|
||||
alert(result.message);
|
||||
hideUploadForm();
|
||||
location.reload();
|
||||
} catch (error) {
|
||||
alert('Ошибка при загрузке: ' + error);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user