cloudairambo / core /admin.py
rihancloud's picture
Deploy clean FastAPI backend without node_modules
99fdb5f
Raw History Blame Contribute Delete
12.6 kB
import os
import uuid
import anyio
from starlette.requests import Request
from starlette.datastructures import UploadFile
from markupsafe import Markup
# Import WTForms fields
from wtforms import FileField, SelectMultipleField, StringField, TextAreaField, SelectField
from sqladmin import Admin, ModelView
from sqladmin.authentication import AuthenticationBackend
# Import your application-specific components
from core.database import engine
from core.config import settings
from core.models import (
UsageStat, AdUnit, AdPlacement, AdStat, AdGlobalSettings, Rating,
)
from core.models import ToolRatingAggregate
# ==============================================================
# πŸ—„οΈ CONFIGURATION & UTILITIES
# ==============================================================
UPLOAD_DIR = "static/uploads"
os.makedirs(UPLOAD_DIR, exist_ok=True)
async def save_ad_file(upload: UploadFile) -> str:
"""Saves the UploadFile asynchronously using a unique name and returns the public file path."""
# 1. Generate a unique and safe filename
file_extension = upload.filename.split(".")[-1] if "." in upload.filename else "file"
unique_filename = f"{uuid.uuid4().hex}.{file_extension}"
save_path_full = os.path.join(UPLOAD_DIR, unique_filename)
# 2. Asynchronously read content
content = await upload.read()
# 3. Use anyio to safely run the blocking file write operation on a thread pool
def write_file_sync():
with open(save_path_full, "wb") as f:
f.write(content)
await anyio.to_thread.run_sync(write_file_sync)
# 4. Return the web-accessible path
return f"/{save_path_full}"
def detect_file_type(filename: str) -> str:
"""Utility to determine file category based on extension."""
ext = filename.lower().split(".")[-1]
if ext in ["jpg", "jpeg", "png", "gif", "webp"]:
return "image"
if ext in ["mp4", "mov", "mkv", "avi"]:
return "video"
if ext in ["mp3", "wav", "ogg"]:
return "audio"
return "unknown"
# ==============================================================
# πŸ”‘ AUTHENTICATION BACKEND
# ==============================================================
class AdminAuth(AuthenticationBackend):
async def login(self, request: Request) -> bool:
form = await request.form()
username = form.get("username")
password = form.get("password")
if username == settings.ADMIN_USER and password == settings.ADMIN_PASS:
request.session["authenticated"] = True
return True
return False
async def logout(self, request: Request) -> bool:
request.session.clear()
return True
async def authenticate(self, request: Request) -> bool:
return request.session.get("authenticated") is True
# ---
# ==============================================================
# πŸ“Š MODEL VIEWS - STATS & GLOBAL SETTINGS
# ==============================================================
class UsageStatAdmin(ModelView, model=UsageStat):
column_list = [
"id", "tool_name", "usage_count", "last_used_at",
"open_count", "process_count", "download_count",
]
# ==============================================================
# ⭐ USER RATINGS ADMIN
# ==============================================================
class RatingAdmin(ModelView, model=Rating):
name = "Rating"
name_plural = "Ratings"
icon = "fa-solid fa-star"
column_list = [
"id",
"tool",
"rating",
"created_at",
]
column_searchable_list = ["tool"]
column_sortable_list = ["created_at", "rating"]
class ToolRatingAggregateAdmin(ModelView, model=ToolRatingAggregate):
name = "Rating Aggregate"
name_plural = "Rating Aggregates"
icon = "fa-solid fa-chart-simple"
column_list = [
"tool",
"average_rating",
"rating_count",
"updated_at",
]
column_sortable_list = [
"average_rating",
"rating_count",
"updated_at",
]
can_create = False
can_edit = False
can_delete = False
class AdGlobalSettingsAdmin(ModelView, model=AdGlobalSettings):
column_list = [
"id",
"all_ads_enabled", "banners_enabled", "popups_enabled",
"predownload_enabled", "sidebar_enabled", "mobile_enabled",
"audio_enabled", "rotation_enabled", "updated_at",
]
# ---
# ==============================================================
# 🎯 AD UNIT ADMIN (Final Logic for File Upload)
# ==============================================================
# ==============================================================
# 🎯 AD UNIT ADMIN (Final Logic for File Upload)
# ==============================================================
class AdUnitAdmin(ModelView, model=AdUnit):
name = "Ad Unit"
name_plural = "Ad Units"
icon = "fa-solid fa-ad"
delete_redirect_url = "/admin/ad-unit/list" # <-- πŸ”₯ ADD THIS LINE
column_list = [
"id", "name", "placement", "ad_type",
"file_path", "priority", "enabled", "created_at", "vast_url",
]
column_formatters = {
"file_path": lambda obj, _: (
Markup(f"<img src='{obj.file_path}' width='120'>") if getattr(obj, "file_type", None) == "image"
else Markup(f"<video src='{obj.file_path}' width='160' controls></video>") if getattr(obj, "file_type", None) == "video"
else Markup(f"<audio src='{obj.file_path}' controls></audio>") if getattr(obj, "file_type", None) == "audio"
else "-"
)
}
# ... (Keep form_columns, form_overrides, form_args as they are) ...
form_columns = [
"name",
"placement",
"ad_type",
"file_path",
"preset_size",
"custom_width",
"custom_height",
"priority",
"enabled",
"target_devices",
"target_categories",
"target_countries",
"vast_url",
"html_code",
"duration_seconds",
"skippable_after",
]
form_overrides = {
"file_path": FileField,
"target_devices": SelectMultipleField, "target_categories": SelectMultipleField,
"target_countries": SelectMultipleField, "placement": SelectField,
"ad_type": SelectField, "preset_size": SelectField,
"html_code": TextAreaField, "vast_url": StringField,
}
form_args = {
"target_devices": {
"choices": [("all", "All Devices"), ("mobile", "Mobile"), ("desktop", "Desktop"),
("tablet", "Tablet")],
},
"target_categories": {
"choices": [("all", "All Categories"), ("finance", "Finance"), ("photo", "Photo"),
("pdf", "PDF Tools"), ("developer", "Developer Tools"), ("games", "Games"),
("education", "Education"), ("shopping", "Shopping"),
("entertainment", "Entertainment"), ("fitness", "Fitness"), ("news", "News")],
},
"target_countries": {
"choices": [("all", "All Countries"), ("US", "United States"), ("IN", "India"),
("UK", "United Kingdom"), ("AE", "UAE"), ("CA", "Canada")],
},
"placement": {
"choices": [("landing_top", "Landing Top"), ("landing_bottom", "Landing Bottom"),
("tools_top", "Tools Top"), ("tools_bottom", "Tools Bottom"),
("tool_popup", "Tool Popup"), ("predownload_video", "Pre-download Video"),
("download_page_banner", "Download Page Banner")],
},
"ad_type": {
"choices": [("image_banner", "Image Banner"), ("video_ad", "Video Ad"),
("audio_ad", "Audio Ad"), ("popup", "Popup Ad"),
("vast_url", "VAST URL"), ("html_snippet", "Custom HTML Snippet")],
},
"preset_size": {
"choices": [
("none", "Custom Size"),
("300x250", "300 Γ— 250 (Medium Rectangle)"),
("336x280", "336 Γ— 280 (Large Rectangle)"),
("728x90", "728 Γ— 90 (Leaderboard)"),
("970x90", "970 Γ— 90 (Large Leaderboard)"),
("970x250", "970 Γ— 250 (Billboard)"),
("468x60", "468 Γ— 60 (Banner)"),
("234x60", "234 Γ— 60 (Half Banner)"),
("320x50", "320 Γ— 50 (Mobile Banner)"),
("320x100", "320 Γ— 100 (Large Mobile Banner)"),
("250x250", "250 Γ— 250 (Square)"),
("200x200", "200 Γ— 200 (Small Square)"),
("180x150", "180 Γ— 150 (Small Rectangle)"),
("120x600", "120 Γ— 600 (Skyscraper)"),
("160x600", "160 Γ— 600 (Wide Skyscraper)"),
("300x600", "300 Γ— 600 (Half Page)"),
],
},
}
# ===========================
# 🎯 CORRECTED LOGIC: on_model_change (The Final Edit Fix)
# ===========================
async def on_model_change(self, data: dict, model: AdUnit, is_created: bool, request: Request):
"""
Handles file uploads and multi-select fields safely before database commit.
This hook fixes the AttributeError when editing without changing the file.
"""
upload_value = data.get("file_path")
if isinstance(upload_value, UploadFile) and upload_value.filename:
# Case 1: NEW file uploaded and it is not empty.
try:
# Save the new file using your existing function
data["file_path"] = await save_ad_file(upload_value)
data["file_type"] = detect_file_type(upload_value.filename)
except Exception:
# Fallback on failure (retain existing path on update, clear on create)
data["file_path"] = model.file_path if not is_created else None
data["file_type"] = model.file_type if not is_created else None
elif not is_created:
# Case 2: EDIT operation and NO new file was provided.
# This is the essential fix: explicitly retain the existing file path/type
# if the form element was present but no new file was attached.
data["file_path"] = model.file_path
data["file_type"] = model.file_type
else:
# Case 3: Create operation with no file, or explicitly removed file.
data["file_path"] = None
data["file_type"] = None
# 2. MULTI-SELECT FIELDS HANDLING (Required for your setup)
# Ensure list of choices is converted to a CSV string.
data["target_devices"] = ",".join(data.get("target_devices") or [])
data["target_categories"] = ",".join(data.get("target_categories") or [])
data["target_countries"] = ",".join(data.get("target_countries") or [])
# Call the parent method
# Note: The original logic for insert_model and update_model is now gone,
# and all necessary pre-save modifications are in this single hook.
# super().on_model_change() is technically not needed here unless the parent
# class has custom logic you need to run, but keeping it is harmless.
# ---
# ==============================================================
# 🎯 AD PLACEMENT & STATS
# ==============================================================
class AdPlacementAdmin(ModelView, model=AdPlacement):
column_list = [
"id", "ad_unit_id", "placement", "priority", "enabled",
"custom_width", "custom_height", "created_at", "updated_at",
]
form_columns = ["ad_unit_id", "placement", "priority", "enabled", "custom_width", "custom_height"]
class AdStatAdmin(ModelView, model=AdStat):
column_list = [
"id", "ad_unit_id", "placement", "impressions", "clicks",
"last_served_at", "updated_at",
]
# ---
# ==============================================================
# πŸš€ SETUP FUNCTION
# ==============================================================
def setup_admin(app):
"""Initializes and configures the SQLAdmin panel."""
admin = Admin(
app=app,
engine=engine,
authentication_backend=AdminAuth(secret_key=settings.SECRET_KEY),
)
admin.add_view(UsageStatAdmin)
admin.add_view(AdUnitAdmin)
admin.add_view(AdPlacementAdmin)
admin.add_view(AdStatAdmin)
admin.add_view(AdGlobalSettingsAdmin)
admin.add_view(RatingAdmin) # ⭐ ADD THIS
admin.add_view(ToolRatingAggregateAdmin)