File size: 12,587 Bytes
99fdb5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346


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)