Monteeq CI factory-droid[bot] commited on
Commit
8ad8368
·
1 Parent(s): f1accec

🚀 Deploy from GitHub @ f2ad8585d6099ec7f0ee8232853264b5389c693d

Browse files

Triggered by: Smasduq
Message: feat(mobile): add Flutter app with full native UI

- Add Flutter project in mobile/ (Android-first, cross-platform ready)
- Implement auth, home/feed, flash, upload, profile, notifications, search, watch screens
- Add Riverpod + go_router, media_kit playback, Dio API client, secure storage
- Configure Android/iOS manifests, permissions, and app identity (com.monteeq.app)
- Add Outfit fonts, theming, and core networking/storage
- Add Next.js native bridge files and related tweaks

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>

.env.example CHANGED
@@ -27,6 +27,27 @@ RUST_SERVICE_URL=http://127.0.0.1:7860
27
  # CORS
28
  CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  # Email
31
  SMTP_HOST=smtp.example.com
32
  SMTP_PORT=587
 
27
  # CORS
28
  CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173
29
 
30
+ # ── Monteeq Clips (free asset library) ──────────────────────────────────
31
+ # HMAC secret for local-mode download tokens. Empty = fall back to SECRET_KEY.
32
+ ASSETS_DOWNLOAD_SECRET=
33
+ # Short-lived download URL/token lifetime, in seconds.
34
+ ASSETS_DOWNLOAD_EXPIRES_SECONDS=300
35
+ # Local-mode private file dir (downloadable clips/files/ live here, NEVER
36
+ # under the statically served directory). S3 mode ignores this.
37
+ PRIVATE_STORAGE_DIR=
38
+ # Upload limits (bytes).
39
+ ASSETS_MAX_FILE_BYTES=524288000
40
+ ASSETS_MAX_PREVIEW_BYTES=104857600
41
+ # Allowed downloadable extensions per category (comma-separated, dotted).
42
+ ASSETS_ALLOWED_EXTENSIONS_PRESETS=.xmp,.lrtemplate,.dng,.zip
43
+ ASSETS_ALLOWED_EXTENSIONS_LUTS=.cube,.3dl,.look,.zip
44
+ ASSETS_ALLOWED_EXTENSIONS_TRANSITIONS=.prproj,.mogrt,.mp4,.mov,.zip
45
+ ASSETS_ALLOWED_EXTENSIONS_OVERLAYS=.mp4,.mov,.png,.jpg,.jpeg,.zip
46
+ ASSETS_ALLOWED_EXTENSIONS_SFX=.wav,.mp3,.ogg,.zip
47
+ ASSETS_ALLOWED_EXTENSIONS_PROJECT_FILES=.prproj,.aep,.psd,.drp,.zip
48
+ # Allowed preview extensions (shared across categories).
49
+ ASSETS_ALLOWED_PREVIEW_EXTENSIONS=.png,.jpg,.jpeg,.gif,.webp,.mp4,.mov,.webm,.wav,.mp3,.ogg
50
+
51
  # Email
52
  SMTP_HOST=smtp.example.com
53
  SMTP_PORT=587
alembic/versions/a55e4d1c9b02_add_assets_tables.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Add assets tables (Monteeq Assets free asset library).
2
+
3
+ Revision ID: a55e4d1c9b02
4
+ Revises: d1e2f3a4b5c6
5
+ Create Date: 2026-10-01
6
+
7
+ NOTE: applying this migration also applies the still-unapplied
8
+ d1e2f3a4b5c6 (edit_feedback) migration, because this revision branches off
9
+ that head. Run `alembic upgrade head` once to apply both, in order.
10
+
11
+ The upgrade is tolerant of tables created by the app's startup
12
+ Base.metadata.create_all: if a table already exists it is left alone and only
13
+ missing indexes are added. Required order therefore does not matter —
14
+ migration-first and create_all-first both converge.
15
+ """
16
+
17
+ from typing import Sequence, Union
18
+
19
+ from alembic import op
20
+ import sqlalchemy as sa
21
+
22
+
23
+ # revision identifiers, used by Alembic.
24
+ revision: str = "a55e4d1c9b02"
25
+ down_revision: Union[str, None] = "d1e2f3a4b5c6"
26
+ branch_labels: Union[str, Sequence[str], None] = None
27
+ depends_on: Union[str, Sequence[str], None] = None
28
+
29
+
30
+ def _existing_tables(conn) -> set:
31
+ try:
32
+ return set(sa.inspect(conn).get_table_names())
33
+ except Exception:
34
+ # Offline (--sql) mode has no inspectable connection: emit DDL.
35
+ return set()
36
+
37
+
38
+ def _existing_indexes(conn, table: str) -> set:
39
+ try:
40
+ return {ix["name"] for ix in sa.inspect(conn).get_indexes(table)}
41
+ except Exception:
42
+ # Offline (--sql) mode, or a table that does not exist yet.
43
+ return set()
44
+
45
+
46
+ def _ensure_index(conn, table: str, name: str, columns: list, unique: bool = False) -> None:
47
+ if name not in _existing_indexes(conn, table):
48
+ op.create_index(name, table, columns, unique=unique)
49
+
50
+
51
+ def upgrade() -> None:
52
+ conn = op.get_bind()
53
+ existing = _existing_tables(conn)
54
+
55
+ if "assets" not in existing:
56
+ op.create_table(
57
+ "assets",
58
+ sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
59
+ sa.Column("title", sa.String(200), nullable=False),
60
+ sa.Column("description", sa.Text(), nullable=True),
61
+ sa.Column("category", sa.String(50), nullable=False),
62
+ sa.Column("owner_id", sa.Integer(), nullable=True),
63
+ sa.Column("file_key", sa.String(500), nullable=False),
64
+ sa.Column("preview_key", sa.String(500), nullable=True),
65
+ sa.Column("preview_type", sa.String(50), nullable=True),
66
+ sa.Column("format", sa.String(50), nullable=True),
67
+ sa.Column("size_bytes", sa.Integer(), nullable=True),
68
+ sa.Column("license_note", sa.Text(), nullable=True),
69
+ sa.Column("is_free", sa.Boolean(), server_default="true", nullable=False),
70
+ sa.Column("price", sa.Numeric(12, 2), nullable=True),
71
+ sa.Column("download_count", sa.Integer(), server_default="0", nullable=False),
72
+ sa.Column("is_published", sa.Boolean(), server_default="true", nullable=False),
73
+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
74
+ sa.ForeignKeyConstraint(["owner_id"], ["users.id"], ondelete="SET NULL"),
75
+ sa.PrimaryKeyConstraint("id"),
76
+ sa.CheckConstraint(
77
+ "category IN ('presets', 'luts', 'transitions', 'overlays', 'sfx', 'project_files')",
78
+ name="ck_assets_category",
79
+ ),
80
+ sa.CheckConstraint(
81
+ "preview_type IS NULL OR preview_type IN ('before_after', 'video', 'audio', 'image')",
82
+ name="ck_assets_preview_type",
83
+ ),
84
+ sa.CheckConstraint("download_count >= 0", name="ck_assets_download_count"),
85
+ )
86
+ _ensure_index(conn, "assets", "ix_assets_category", ["category"])
87
+ _ensure_index(conn, "assets", "ix_assets_owner_id", ["owner_id"])
88
+ _ensure_index(conn, "assets", "ix_assets_is_published", ["is_published"])
89
+ _ensure_index(conn, "assets", "ix_assets_created_at", ["created_at"])
90
+ _ensure_index(
91
+ conn, "assets", "ix_assets_published_category", ["is_published", "category"]
92
+ )
93
+
94
+ if "asset_downloads" not in existing:
95
+ op.create_table(
96
+ "asset_downloads",
97
+ sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
98
+ sa.Column("user_id", sa.Integer(), nullable=False),
99
+ sa.Column("asset_id", sa.Integer(), nullable=False),
100
+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
101
+ sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
102
+ sa.ForeignKeyConstraint(["asset_id"], ["assets.id"], ondelete="CASCADE"),
103
+ sa.PrimaryKeyConstraint("id"),
104
+ )
105
+ _ensure_index(conn, "asset_downloads", "ix_asset_downloads_user_asset", ["user_id", "asset_id"])
106
+ _ensure_index(conn, "asset_downloads", "ix_asset_downloads_created_at", ["created_at"])
107
+ _ensure_index(conn, "asset_downloads", "ix_asset_downloads_asset_id", ["asset_id"])
108
+
109
+
110
+ def downgrade() -> None:
111
+ conn = op.get_bind()
112
+ existing = _existing_tables(conn)
113
+ if "asset_downloads" in existing:
114
+ for name in (
115
+ "ix_asset_downloads_asset_id",
116
+ "ix_asset_downloads_created_at",
117
+ "ix_asset_downloads_user_asset",
118
+ ):
119
+ if name in _existing_indexes(conn, "asset_downloads"):
120
+ op.drop_index(name, table_name="asset_downloads")
121
+ op.drop_table("asset_downloads")
122
+ if "assets" in existing:
123
+ for name in (
124
+ "ix_assets_published_category",
125
+ "ix_assets_created_at",
126
+ "ix_assets_is_published",
127
+ "ix_assets_owner_id",
128
+ "ix_assets_category",
129
+ ):
130
+ if name in _existing_indexes(conn, "assets"):
131
+ op.drop_index(name, table_name="assets")
132
+ op.drop_table("assets")
app/api/v1/api.py CHANGED
@@ -1,5 +1,5 @@
1
  from fastapi import APIRouter
2
- from app.api.v1.endpoints import auth, videos, admin, users, posts, achievements, notifications, ads, chat, challenges, monetization, video_views, seo, recommendations, partners, categories, library, history, watch_later, liked, following, metrics, email, reports, comments, events
3
 
4
 
5
  api_router = APIRouter()
@@ -29,6 +29,7 @@ api_router.include_router(email.router, prefix="/email", tags=["email"])
29
  api_router.include_router(reports.router, prefix="/reports", tags=["reports"])
30
  api_router.include_router(comments.router, prefix="/comments", tags=["comments"])
31
  api_router.include_router(events.router, prefix="/events", tags=["events"])
 
32
 
33
 
34
 
 
1
  from fastapi import APIRouter
2
+ from app.api.v1.endpoints import auth, videos, admin, users, posts, achievements, notifications, ads, chat, challenges, monetization, video_views, seo, recommendations, partners, categories, library, history, watch_later, liked, following, metrics, email, reports, comments, events, assets
3
 
4
 
5
  api_router = APIRouter()
 
29
  api_router.include_router(reports.router, prefix="/reports", tags=["reports"])
30
  api_router.include_router(comments.router, prefix="/comments", tags=["comments"])
31
  api_router.include_router(events.router, prefix="/events", tags=["events"])
32
+ api_router.include_router(assets.router, prefix="/assets", tags=["assets"])
33
 
34
 
35
 
app/api/v1/endpoints/assets.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Monteeq Clips — free asset library for editors.
2
+
3
+ Public:
4
+ GET /assets list (filters, search, sort, pagination)
5
+ GET /assets/{id} detail (preview URLs only, never file_key)
6
+ POST /assets/{id}/download auth required; counts the download, returns a
7
+ short-lived download URL
8
+ GET /assets/download/{token} streams the private file (local mode) after
9
+ HMAC token validation; redirects to a presigned
10
+ URL in s3 mode
11
+
12
+ Admin (existing admin_only check):
13
+ POST /assets multipart upload (file + optional preview)
14
+ PATCH /assets/{id} metadata update
15
+ DELETE /assets/{id} soft delete (is_published = false)
16
+ """
17
+
18
+ import mimetypes
19
+ import os
20
+ import re
21
+ import unicodedata
22
+ import uuid
23
+ from typing import Optional
24
+
25
+ from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
26
+ from fastapi.responses import FileResponse, RedirectResponse
27
+ from sqlalchemy import func, or_
28
+ from sqlalchemy.orm import Session
29
+
30
+ from app.core import config
31
+ from app.core.asset_tokens import verify_download_token
32
+ from app.core.dependencies import admin_only, get_current_user
33
+ from app.core.storage import storage
34
+ from app.db.session import get_db
35
+ from app.models.assets import Asset, AssetDownload
36
+ from app.models.models import User
37
+ from app.schemas.assets import (
38
+ AssetDownloadResponse,
39
+ AssetListResponse,
40
+ AssetPublic,
41
+ AssetUpdate,
42
+ _norm_category,
43
+ _norm_preview_type,
44
+ )
45
+
46
+ router = APIRouter()
47
+
48
+
49
+ # ── Helpers ───────────────────────────────────────────────────────────────────
50
+
51
+ def _to_public(asset: Asset) -> dict:
52
+ """Serialise an asset for public responses. NEVER includes file_key."""
53
+ preview_url = None
54
+ if asset.preview_key:
55
+ try:
56
+ preview_url = storage.get_url(asset.preview_key)
57
+ except Exception:
58
+ preview_url = None
59
+ created = asset.created_at.isoformat() if asset.created_at else None
60
+ return {
61
+ "id": asset.id,
62
+ "title": asset.title,
63
+ "description": asset.description,
64
+ "category": asset.category,
65
+ "owner_id": asset.owner_id,
66
+ "preview_url": preview_url,
67
+ "preview_type": asset.preview_type,
68
+ "format": asset.format,
69
+ "size_bytes": asset.size_bytes,
70
+ "license_note": asset.license_note,
71
+ "is_free": asset.is_free,
72
+ "price": asset.price,
73
+ "download_count": asset.download_count or 0,
74
+ "created_at": created,
75
+ }
76
+
77
+
78
+ def _get_published_or_404(db: Session, asset_id: int) -> Asset:
79
+ asset = (
80
+ db.query(Asset)
81
+ .filter(Asset.id == asset_id, Asset.is_published.is_(True))
82
+ .first()
83
+ )
84
+ if not asset:
85
+ raise HTTPException(status_code=404, detail="Asset not found")
86
+ return asset
87
+
88
+
89
+ def _safe_filename(filename: str, default_ext: str = "") -> str:
90
+ base, ext = os.path.splitext(filename or "")
91
+ safe = unicodedata.normalize("NFKD", base).encode("ascii", "ignore").decode("ascii")
92
+ safe = re.sub(r"[^\w\s-]", "", safe).strip().lower()
93
+ safe = re.sub(r"[-\s]+", "_", safe) or "file"
94
+ return f"{safe}{ext or default_ext}"
95
+
96
+
97
+ def _measure_size(upload: UploadFile) -> int:
98
+ upload.file.seek(0, os.SEEK_END)
99
+ size = upload.file.tell()
100
+ upload.file.seek(0)
101
+ return size
102
+
103
+
104
+ def _check_limits(category: str, upload: UploadFile, max_bytes: int, allowed: set) -> str:
105
+ ext = os.path.splitext(upload.filename or "")[1].lower()
106
+ if ext not in allowed:
107
+ raise HTTPException(
108
+ status_code=400,
109
+ detail=f"File type '{ext or '(none)'}' not allowed for this upload. "
110
+ f"Allowed: {sorted(allowed)}",
111
+ )
112
+ size = _measure_size(upload)
113
+ if size > max_bytes:
114
+ raise HTTPException(
115
+ status_code=413,
116
+ detail=f"File too large ({size} bytes). Maximum is {max_bytes} bytes.",
117
+ )
118
+ return ext
119
+
120
+
121
+ # ── Token download (defined BEFORE /{asset_id} so "download" never collides) ─
122
+
123
+ @router.get("/download/{token}")
124
+ def download_by_token(token: str, db: Session = Depends(get_db)):
125
+ """Validate the HMAC token and serve the private file.
126
+
127
+ Local mode streams the file with Content-Disposition: attachment.
128
+ S3 mode redirects to a short-lived presigned URL.
129
+ No login required — the signed token is the credential.
130
+ """
131
+ asset_id = verify_download_token(token)
132
+ asset = _get_published_or_404(db, asset_id)
133
+
134
+ if storage.mode == "local":
135
+ try:
136
+ path = storage._local_private_path(asset.file_key)
137
+ except ValueError:
138
+ raise HTTPException(status_code=404, detail="File not found")
139
+ if not os.path.isfile(path):
140
+ raise HTTPException(status_code=404, detail="File not found")
141
+ ext = os.path.splitext(asset.file_key)[1]
142
+ media_type, _ = mimetypes.guess_type("file" + ext)
143
+ return FileResponse(
144
+ path,
145
+ media_type=media_type or "application/octet-stream",
146
+ filename=f"asset-{asset.id}{ext}",
147
+ content_disposition_type="attachment",
148
+ )
149
+
150
+ # S3 mode (any S3-compatible endpoint): redirect to a fresh presigned URL.
151
+ try:
152
+ url = storage.generate_presigned_download_url(
153
+ asset.file_key, config.ASSETS_DOWNLOAD_EXPIRES_SECONDS
154
+ )
155
+ except Exception:
156
+ raise HTTPException(status_code=500, detail="Could not generate download URL")
157
+ return RedirectResponse(url=url, status_code=302)
158
+
159
+
160
+ # ── Public list / detail ──────────────────────────────────────────────────────
161
+
162
+ @router.get("/", response_model=AssetListResponse)
163
+ def list_assets(
164
+ category: Optional[str] = None,
165
+ search: Optional[str] = None,
166
+ sort: str = "newest",
167
+ page: int = 1,
168
+ limit: int = 20,
169
+ db: Session = Depends(get_db),
170
+ ):
171
+ if page < 1:
172
+ raise HTTPException(status_code=422, detail="page must be >= 1")
173
+ limit = min(max(limit, 1), 50)
174
+ if sort not in ("popular", "newest"):
175
+ raise HTTPException(status_code=422, detail="sort must be 'popular' or 'newest'")
176
+ if category is not None:
177
+ try:
178
+ category = _norm_category(category)
179
+ except ValueError as e:
180
+ raise HTTPException(status_code=422, detail=str(e))
181
+
182
+ query = db.query(Asset).filter(Asset.is_published.is_(True))
183
+ if category:
184
+ query = query.filter(Asset.category == category)
185
+ if search:
186
+ like = f"%{search}%"
187
+ query = query.filter(or_(Asset.title.ilike(like), Asset.description.ilike(like)))
188
+
189
+ total = query.with_entities(func.count(Asset.id)).scalar() or 0
190
+
191
+ if sort == "popular":
192
+ query = query.order_by(Asset.download_count.desc(), Asset.id.desc())
193
+ else:
194
+ query = query.order_by(Asset.created_at.desc(), Asset.id.desc())
195
+
196
+ offset = (page - 1) * limit
197
+ rows = query.offset(offset).limit(limit).all()
198
+
199
+ return {
200
+ "items": [_to_public(a) for a in rows],
201
+ "page": page,
202
+ "limit": limit,
203
+ "total": total,
204
+ "has_more": offset + limit < total,
205
+ }
206
+
207
+
208
+ @router.get("/{asset_id}", response_model=AssetPublic)
209
+ def get_asset(asset_id: int, db: Session = Depends(get_db)):
210
+ asset = _get_published_or_404(db, asset_id)
211
+ return _to_public(asset)
212
+
213
+
214
+ # ── Authenticated download ────────────────────────────────────────────────────
215
+
216
+ @router.post("/{asset_id}/download", response_model=AssetDownloadResponse)
217
+ def download_asset(
218
+ asset_id: int,
219
+ db: Session = Depends(get_db),
220
+ current_user: User = Depends(get_current_user),
221
+ ):
222
+ asset = _get_published_or_404(db, asset_id)
223
+
224
+ # One transaction: record the event + atomically bump the counter.
225
+ db.add(AssetDownload(user_id=current_user.id, asset_id=asset.id))
226
+ (
227
+ db.query(Asset)
228
+ .filter(Asset.id == asset.id)
229
+ .update({Asset.download_count: Asset.download_count + 1}, synchronize_session=False)
230
+ )
231
+ db.commit()
232
+
233
+ expires = config.ASSETS_DOWNLOAD_EXPIRES_SECONDS
234
+ try:
235
+ url = storage.get_asset_download_url(asset.id, asset.file_key, expires)
236
+ except ValueError as e:
237
+ raise HTTPException(status_code=500, detail=f"Could not generate download URL: {e}")
238
+ except Exception:
239
+ raise HTTPException(status_code=500, detail="Could not generate download URL")
240
+ return {"download_url": url, "expires_in": expires}
241
+
242
+
243
+ # ── Admin ─────────────────────────────────────────────────────────────────────
244
+
245
+ @router.post("/", response_model=AssetPublic)
246
+ def create_asset(
247
+ title: str = Form(...),
248
+ category: str = Form(...),
249
+ file: UploadFile = File(...),
250
+ description: Optional[str] = Form(None),
251
+ preview_type: Optional[str] = Form(None),
252
+ preview: Optional[UploadFile] = File(None),
253
+ format: Optional[str] = Form(None),
254
+ license_note: Optional[str] = Form(None),
255
+ is_free: bool = Form(True),
256
+ price: Optional[float] = Form(None),
257
+ is_published: bool = Form(True),
258
+ db: Session = Depends(get_db),
259
+ current_user: User = Depends(admin_only),
260
+ ):
261
+ try:
262
+ category = _norm_category(category)
263
+ except ValueError as e:
264
+ raise HTTPException(status_code=422, detail=str(e))
265
+ try:
266
+ preview_type = _norm_preview_type(preview_type) if preview_type else None
267
+ except ValueError as e:
268
+ raise HTTPException(status_code=422, detail=str(e))
269
+
270
+ allowed = config.ASSETS_ALLOWED_EXTENSIONS.get(category, set())
271
+ ext = _check_limits(category, file, config.ASSETS_MAX_FILE_BYTES, allowed)
272
+ file_size = _measure_size(file)
273
+
274
+ preview_key = None
275
+ if preview and preview.filename:
276
+ _check_limits(
277
+ category, preview,
278
+ config.ASSETS_MAX_PREVIEW_BYTES,
279
+ config.ASSETS_ALLOWED_PREVIEW_EXTENSIONS,
280
+ )
281
+
282
+ task = uuid.uuid4().hex
283
+ file_key = f"{config.ASSETS_FILE_PREFIX}{task}_{_safe_filename(file.filename)}"
284
+
285
+ try:
286
+ storage.upload_private_file_obj(file.file, file_key)
287
+ except Exception:
288
+ raise HTTPException(status_code=500, detail="Failed to upload file to storage")
289
+
290
+ if preview and preview.filename:
291
+ preview_key = f"{config.ASSETS_PREVIEW_PREFIX}{task}_{_safe_filename(preview.filename)}"
292
+ try:
293
+ storage.upload_file_obj(preview.file, preview_key)
294
+ except Exception:
295
+ # Roll back the private file so we don't orphan it.
296
+ try:
297
+ if storage.mode == "local":
298
+ os.remove(storage._local_private_path(file_key))
299
+ else:
300
+ storage.delete_file(file_key)
301
+ except Exception:
302
+ pass
303
+ raise HTTPException(status_code=500, detail="Failed to upload preview to storage")
304
+
305
+ asset = Asset(
306
+ title=title,
307
+ description=description,
308
+ category=category,
309
+ owner_id=current_user.id,
310
+ file_key=file_key,
311
+ preview_key=preview_key,
312
+ preview_type=preview_type,
313
+ format=format or ext.lstrip("."),
314
+ size_bytes=file_size,
315
+ license_note=license_note,
316
+ is_free=is_free,
317
+ price=price,
318
+ is_published=is_published,
319
+ )
320
+ db.add(asset)
321
+ db.commit()
322
+ db.refresh(asset)
323
+ return _to_public(asset)
324
+
325
+
326
+ @router.patch("/{asset_id}", response_model=AssetPublic)
327
+ def update_asset(
328
+ asset_id: int,
329
+ payload: AssetUpdate,
330
+ db: Session = Depends(get_db),
331
+ current_user: User = Depends(admin_only),
332
+ ):
333
+ asset = db.query(Asset).filter(Asset.id == asset_id).first()
334
+ if not asset:
335
+ raise HTTPException(status_code=404, detail="Asset not found")
336
+ for field, value in payload.model_dump(exclude_none=True).items():
337
+ setattr(asset, field, value)
338
+ db.commit()
339
+ db.refresh(asset)
340
+ return _to_public(asset)
341
+
342
+
343
+ @router.delete("/{asset_id}")
344
+ def delete_asset(
345
+ asset_id: int,
346
+ db: Session = Depends(get_db),
347
+ current_user: User = Depends(admin_only),
348
+ ):
349
+ asset = db.query(Asset).filter(Asset.id == asset_id).first()
350
+ if not asset:
351
+ raise HTTPException(status_code=404, detail="Asset not found")
352
+ asset.is_published = False
353
+ db.commit()
354
+ return {"status": "success", "id": asset_id}
app/api/v1/endpoints/challenges.py CHANGED
@@ -76,6 +76,10 @@ async def enter_challenge(
76
  if existing_entry:
77
  raise HTTPException(status_code=400, detail="You have already entered this challenge")
78
 
 
 
 
 
79
  # Handle Video Upload
80
  import uuid
81
  task_id = str(uuid.uuid4())
@@ -99,10 +103,6 @@ async def enter_challenge(
99
  processing_key=task_id
100
  )
101
 
102
- # Update quota if applicable
103
- if current_user.home_uploads is not None:
104
- current_user.home_uploads += 1
105
-
106
  db_video = crud_video.create_video(db, video_create_data, user_id=current_user.id)
107
 
108
  # Create Challenge Entry
 
76
  if existing_entry:
77
  raise HTTPException(status_code=400, detail="You have already entered this challenge")
78
 
79
+ quota_error = crud_video.get_upload_quota_error(db, current_user, "home")
80
+ if quota_error:
81
+ raise HTTPException(status_code=403, detail=quota_error)
82
+
83
  # Handle Video Upload
84
  import uuid
85
  task_id = str(uuid.uuid4())
 
103
  processing_key=task_id
104
  )
105
 
 
 
 
 
106
  db_video = crud_video.create_video(db, video_create_data, user_id=current_user.id)
107
 
108
  # Create Challenge Entry
app/api/v1/endpoints/seo.py CHANGED
@@ -29,14 +29,7 @@ _VIDEOS_SQL = text("""
29
 
30
  def _resolve_url(url):
31
  """Inline CDN resolver — avoids loading the full Video ORM (which may have columns not yet migrated)."""
32
- if not url:
33
- return url
34
- if "amazonaws.com" in url or "monteeq.s3" in url or "cdn.monteeq.com" in url:
35
- if ".com/" in url:
36
- parts = url.split(".com/")
37
- if len(parts) > 1:
38
- return storage.get_url(parts[1])
39
- return url
40
 
41
 
42
  def _to_xml(root):
 
29
 
30
  def _resolve_url(url):
31
  """Inline CDN resolver — avoids loading the full Video ORM (which may have columns not yet migrated)."""
32
+ return storage.resolve_cdn_url(url)
 
 
 
 
 
 
 
33
 
34
 
35
  def _to_xml(root):
app/api/v1/endpoints/users.py CHANGED
@@ -16,6 +16,7 @@ from fastapi import Body
16
 
17
  from app.db.session import get_db, SessionLocal
18
  from app.crud import user as crud_user
 
19
  from app.schemas import schemas
20
  from app.core.dependencies import get_current_user, get_current_user_optional
21
  from app.core import config
@@ -27,9 +28,20 @@ from google.auth.transport import requests as google_requests
27
 
28
  router = APIRouter()
29
 
 
 
 
 
 
 
 
 
30
  @router.get("/me", response_model=schemas.User)
31
- def read_users_me(current_user: schemas.User = Depends(get_current_user)):
32
- return current_user
 
 
 
33
 
34
  @router.put("/me", response_model=schemas.UserUpdateResponse)
35
  def update_user_me(
@@ -59,7 +71,10 @@ def update_user_me(
59
  data={"sub": user_in.username}, expires_delta=access_token_expires
60
  )
61
 
62
- return {"user": updated_user, "access_token": access_token}
 
 
 
63
 
64
  @router.put("/me/password")
65
  def update_user_password(
@@ -688,7 +703,7 @@ def update_onboarding(
688
  # Ensure it only updates relevant fields and sets is_onboarded
689
  onboarding_data.is_onboarded = True
690
  updated_user = crud_user.update_user(db, user_id=current_user.id, user_update=onboarding_data)
691
- return updated_user
692
 
693
  @router.post("/me/2fa/setup")
694
  def setup_totp(
@@ -944,5 +959,3 @@ def get_user_following(
944
  if not user:
945
  raise HTTPException(status_code=404, detail="User not found")
946
  return crud_user.get_following(db, user_id=user.id, skip=skip, limit=limit)
947
-
948
-
 
16
 
17
  from app.db.session import get_db, SessionLocal
18
  from app.crud import user as crud_user
19
+ from app.crud import video as crud_video
20
  from app.schemas import schemas
21
  from app.core.dependencies import get_current_user, get_current_user_optional
22
  from app.core import config
 
28
 
29
  router = APIRouter()
30
 
31
+ def _user_with_upload_counts(db: Session, user: User) -> dict:
32
+ user_data = schemas.User.model_validate(user).model_dump()
33
+ upload_counts = crud_video.get_user_upload_counts(db, user.id)
34
+ user_data["home_uploads"] = upload_counts["home"]
35
+ user_data["flash_uploads"] = upload_counts["flash"]
36
+ return user_data
37
+
38
+
39
  @router.get("/me", response_model=schemas.User)
40
+ def read_users_me(
41
+ db: Session = Depends(get_db),
42
+ current_user: User = Depends(get_current_user),
43
+ ):
44
+ return _user_with_upload_counts(db, current_user)
45
 
46
  @router.put("/me", response_model=schemas.UserUpdateResponse)
47
  def update_user_me(
 
71
  data={"sub": user_in.username}, expires_delta=access_token_expires
72
  )
73
 
74
+ return {
75
+ "user": _user_with_upload_counts(db, updated_user),
76
+ "access_token": access_token,
77
+ }
78
 
79
  @router.put("/me/password")
80
  def update_user_password(
 
703
  # Ensure it only updates relevant fields and sets is_onboarded
704
  onboarding_data.is_onboarded = True
705
  updated_user = crud_user.update_user(db, user_id=current_user.id, user_update=onboarding_data)
706
+ return _user_with_upload_counts(db, updated_user)
707
 
708
  @router.post("/me/2fa/setup")
709
  def setup_totp(
 
959
  if not user:
960
  raise HTTPException(status_code=404, detail="User not found")
961
  return crud_user.get_following(db, user_id=user.id, skip=skip, limit=limit)
 
 
app/api/v1/endpoints/videos.py CHANGED
@@ -19,7 +19,6 @@ from app.core.dependencies import get_current_user, get_current_user_optional
19
  from app.core import config
20
  from app.utils.push import notify_user_push
21
  from app.core.storage import storage
22
- from app.core.config import FLASH_QUOTA_LIMIT, HOME_QUOTA_LIMIT
23
  from app.models.models import (
24
  Video, User, View, WatchLater, Repost, VideoInteraction, UploadJob, UploadJobStatus,
25
  )
@@ -189,15 +188,8 @@ async def get_stream_url(video_id: str, request: Request, db: Session = Depends(
189
  if not base_url:
190
  raise HTTPException(status_code=400, detail="Video has no URL")
191
 
192
- # Resolve to CDN URL if stored as S3/HF path
193
- if "amazonaws.com" in base_url or "monteeq.s3" in base_url or "cdn.monteeq.com" in base_url:
194
- try:
195
- if ".com/" in base_url:
196
- parts = base_url.split(".com/")
197
- if len(parts) > 1:
198
- base_url = storage.get_url(parts[1])
199
- except Exception as e:
200
- logger.warning(f"Failed to resolve CDN URL for stream-url: {e}")
201
 
202
  # If CloudFront signing is not configured, return the raw URL
203
  # (the old proxy endpoint is still available as fallback)
@@ -239,16 +231,8 @@ async def stream_video(video_id: str, request: Request, db: Session = Depends(ge
239
  if not base_url:
240
  raise HTTPException(status_code=400, detail="Video has no URL")
241
 
242
- # Resolve to CDN URL if applicable to avoid S3 DNS timeouts
243
- if "amazonaws.com" in base_url or "monteeq.s3" in base_url or "cdn.monteeq.com" in base_url:
244
- try:
245
- from app.core.storage import storage
246
- if ".com/" in base_url:
247
- parts = base_url.split(".com/")
248
- if len(parts) > 1:
249
- base_url = storage.get_url(parts[1])
250
- except Exception as e:
251
- logger.warning(f"Failed to resolve CDN URL for streaming: {e}")
252
 
253
  # Construct the proxy target URL
254
  target_url = base_url
@@ -343,16 +327,8 @@ async def stream_video_resolution(
343
  if not target_url:
344
  raise HTTPException(status_code=404, detail=f"No {quality} stream available for this video")
345
 
346
- # Resolve CDN URL if needed
347
- if "amazonaws.com" in target_url or "monteeq.s3" in target_url or "cdn.monteeq.com" in target_url:
348
- try:
349
- from app.core.storage import storage
350
- if ".com/" in target_url:
351
- parts = target_url.split(".com/")
352
- if len(parts) > 1:
353
- target_url = storage.get_url(parts[1])
354
- except Exception as e:
355
- logger.warning(f"Failed to resolve CDN URL for resolution stream: {e}")
356
 
357
  async def get_res_stream():
358
  # read_timeout=None: no upper bound on read — video files can be large.
@@ -523,10 +499,8 @@ def delete_video_files(video: Video):
523
  s3_key = None
524
  if current_mode == "local" and url.startswith(f"{config.BASE_URL}/static/"):
525
  s3_key = url.replace(f"{config.BASE_URL}/static/", "")
526
- elif current_mode in ("s3", "gcs") and ("amazonaws.com" in url or "cdn.monteeq.com" in url):
527
- # Extract key after .com/
528
- if ".com/" in url:
529
- s3_key = url.split(".com/")[1]
530
 
531
  if s3_key:
532
  storage.delete_file(s3_key)
@@ -615,11 +589,9 @@ async def initiate_upload(
615
  ):
616
  logger.info(f"Chunked Upload initiated: title='{title}', type='{video_type}', filename='{filename}', user_id={current_user.id}")
617
 
618
- if not current_user.is_premium:
619
- if video_type == "flash" and current_user.flash_uploads >= FLASH_QUOTA_LIMIT:
620
- raise HTTPException(status_code=403, detail=f"Flash quota exceeded ({FLASH_QUOTA_LIMIT} max)")
621
- if video_type == "home" and current_user.home_uploads >= HOME_QUOTA_LIMIT:
622
- raise HTTPException(status_code=403, detail=f"Home quota exceeded ({HOME_QUOTA_LIMIT} max)")
623
 
624
  import uuid
625
  import time
@@ -656,14 +628,6 @@ async def initiate_upload(
656
  except Exception as e:
657
  logger.error(f"Failed to upload thumbnail to storage: {str(e)}")
658
 
659
- # Update quota
660
- if video_type == "flash":
661
- current_user.flash_uploads = (current_user.flash_uploads or 0) + 1
662
- else:
663
- current_user.home_uploads = (current_user.home_uploads or 0) + 1
664
-
665
- db.commit() # Save user updates
666
-
667
  # Create the Video database record
668
  db_video = crud_video.create_video(db, video_create_data, user_id=current_user.id)
669
  # Set status as uploading initially
@@ -997,11 +961,9 @@ async def _direct_upload_one(
997
  "cover_s3_key": None,
998
  }
999
 
1000
- if not current_user.is_premium:
1001
- if video_type == "flash" and (current_user.flash_uploads or 0) >= FLASH_QUOTA_LIMIT:
1002
- return _fail(f"Flash quota exceeded ({FLASH_QUOTA_LIMIT} max)", status_code=403)
1003
- if video_type == "home" and (current_user.home_uploads or 0) >= HOME_QUOTA_LIMIT:
1004
- return _fail(f"Home quota exceeded ({HOME_QUOTA_LIMIT} max)", status_code=403)
1005
 
1006
  task_id = str(uuid.uuid4())
1007
 
@@ -1031,13 +993,6 @@ async def _direct_upload_one(
1031
  processing_key=task_id,
1032
  )
1033
 
1034
- if video_type == "flash":
1035
- current_user.flash_uploads = (current_user.flash_uploads or 0) + 1
1036
- else:
1037
- current_user.home_uploads = (current_user.home_uploads or 0) + 1
1038
-
1039
- db.commit()
1040
-
1041
  db_video = crud_video.create_video(db, video_create_data, user_id=current_user.id)
1042
  db_video.status = "pending"
1043
  logger.info(f"Video record created in DB: id={db_video.id}")
@@ -1512,47 +1467,15 @@ def delete_comment(
1512
  return {"status": "success", "message": "Comment deleted successfully"}
1513
 
1514
 
1515
- # ── Media Analysis ────────────────────────────────────────────────────────────
1516
 
1517
  @router.get("/{video_id}/analysis")
1518
  def get_media_analysis(video_id: str, db: Session = Depends(get_db)):
1519
- """Return the media_analysis row for a video (frames, scene cuts, beats, embedding)."""
1520
- from sqlalchemy import text
1521
- row = db.execute(
1522
- text("SELECT * FROM media_analysis WHERE video_id = :vid"),
1523
- {"vid": video_id},
1524
- ).mappings().first()
1525
 
1526
- if not row:
1527
- raise HTTPException(status_code=404, detail="No analysis found for this video")
1528
-
1529
- return dict(row)
1530
-
1531
-
1532
- # ── Editing Feedback ──────────────────────────────────────────────────────────
1533
-
1534
- RATE_LIMIT_KEY_PREFIX = "rate_limit:feedback:"
1535
- RATE_LIMIT_MAX = 10 # requests per window
1536
- RATE_LIMIT_WINDOW = 3600 # 1 hour in seconds
1537
-
1538
-
1539
- def _check_feedback_rate_limit(user_id: int) -> None:
1540
- """Raise 429 if the user has exceeded the feedback request limit."""
1541
- key = f"{RATE_LIMIT_KEY_PREFIX}{user_id}"
1542
- try:
1543
- current = redis_client.get(key)
1544
- if current is not None and int(current) >= RATE_LIMIT_MAX:
1545
- raise HTTPException(
1546
- status_code=429,
1547
- detail="Rate limit exceeded. You can request feedback up to 10 times per hour.",
1548
- )
1549
- redis_client.incr(key)
1550
- redis_client.expire(key, RATE_LIMIT_WINDOW, nx=True)
1551
- except HTTPException:
1552
- raise
1553
- except Exception:
1554
- pass # Redis down — allow request rather than blocking users
1555
 
 
1556
 
1557
  @router.post("/{video_id}/feedback")
1558
  def post_edit_feedback(
@@ -1560,63 +1483,8 @@ def post_edit_feedback(
1560
  db: Session = Depends(get_db),
1561
  current_user: schemas.User = Depends(get_current_user),
1562
  ):
1563
- """Generate AI editing feedback for a video based on its scene_cuts and beat_timestamps.
1564
-
1565
- Returns the feedback text plus the raw metrics dict. Rate-limited to 10
1566
- requests per hour per user.
1567
- """
1568
- video = get_video_db(db, video_id)
1569
- if not video:
1570
- raise HTTPException(status_code=404, detail="Video not found")
1571
-
1572
- _check_feedback_rate_limit(current_user.id)
1573
-
1574
- from sqlalchemy import text as sql_text
1575
-
1576
- # 1. Fetch media_analysis row
1577
- row = db.execute(
1578
- sql_text("SELECT * FROM media_analysis WHERE video_id = :vid"),
1579
- {"vid": video.id},
1580
- ).mappings().first()
1581
-
1582
- if not row:
1583
- raise HTTPException(status_code=404, detail="No media analysis found for this video")
1584
-
1585
- if not row.get("scene_cuts") or not row.get("beat_timestamps"):
1586
- raise HTTPException(
1587
- status_code=409,
1588
- detail="Editing feedback is not available yet — scene cut or beat detection has not finished. "
1589
- "Wait for media analysis to complete and try again.",
1590
- )
1591
-
1592
- # 2. Compute metrics
1593
- from app.services.editing_feedback import compute_edit_metrics, generate_feedback
1594
-
1595
- metrics = compute_edit_metrics(
1596
- scene_cuts=list(row["scene_cuts"]),
1597
- beat_timestamps=list(row["beat_timestamps"]),
1598
- )
1599
-
1600
- # 3. Generate AI feedback
1601
- feedback_text = generate_feedback(metrics, video.title or "Untitled")
1602
-
1603
- # 4. Persist to edit_feedback table
1604
- from app.models.edit_feedback import EditFeedback
1605
-
1606
- feedback_record = EditFeedback(
1607
- video_id=video.id,
1608
- feedback_text=feedback_text,
1609
- metrics_snapshot=metrics,
1610
- )
1611
- db.add(feedback_record)
1612
- db.commit()
1613
-
1614
- return {
1615
- "feedback_id": feedback_record.id,
1616
- "feedback_text": feedback_text,
1617
- "metrics": metrics,
1618
- "created_at": feedback_record.created_at.isoformat() if feedback_record.created_at else None,
1619
- }
1620
 
1621
 
1622
  @router.get("/{video_id}/feedback")
 
19
  from app.core import config
20
  from app.utils.push import notify_user_push
21
  from app.core.storage import storage
 
22
  from app.models.models import (
23
  Video, User, View, WatchLater, Repost, VideoInteraction, UploadJob, UploadJobStatus,
24
  )
 
188
  if not base_url:
189
  raise HTTPException(status_code=400, detail="Video has no URL")
190
 
191
+ # Resolve to the currently configured CDN (handles legacy S3/CloudFront hosts)
192
+ base_url = storage.resolve_cdn_url(base_url)
 
 
 
 
 
 
 
193
 
194
  # If CloudFront signing is not configured, return the raw URL
195
  # (the old proxy endpoint is still available as fallback)
 
231
  if not base_url:
232
  raise HTTPException(status_code=400, detail="Video has no URL")
233
 
234
+ # Resolve to the currently configured CDN (handles legacy S3/CloudFront hosts)
235
+ base_url = storage.resolve_cdn_url(base_url)
 
 
 
 
 
 
 
 
236
 
237
  # Construct the proxy target URL
238
  target_url = base_url
 
327
  if not target_url:
328
  raise HTTPException(status_code=404, detail=f"No {quality} stream available for this video")
329
 
330
+ # Resolve to the currently configured CDN (handles legacy S3/CloudFront hosts)
331
+ target_url = storage.resolve_cdn_url(target_url)
 
 
 
 
 
 
 
 
332
 
333
  async def get_res_stream():
334
  # read_timeout=None: no upper bound on read — video files can be large.
 
499
  s3_key = None
500
  if current_mode == "local" and url.startswith(f"{config.BASE_URL}/static/"):
501
  s3_key = url.replace(f"{config.BASE_URL}/static/", "")
502
+ elif current_mode in ("s3", "gcs"):
503
+ s3_key = storage.key_from_url(url)
 
 
504
 
505
  if s3_key:
506
  storage.delete_file(s3_key)
 
589
  ):
590
  logger.info(f"Chunked Upload initiated: title='{title}', type='{video_type}', filename='{filename}', user_id={current_user.id}")
591
 
592
+ quota_error = crud_video.get_upload_quota_error(db, current_user, video_type)
593
+ if quota_error:
594
+ raise HTTPException(status_code=403, detail=quota_error)
 
 
595
 
596
  import uuid
597
  import time
 
628
  except Exception as e:
629
  logger.error(f"Failed to upload thumbnail to storage: {str(e)}")
630
 
 
 
 
 
 
 
 
 
631
  # Create the Video database record
632
  db_video = crud_video.create_video(db, video_create_data, user_id=current_user.id)
633
  # Set status as uploading initially
 
961
  "cover_s3_key": None,
962
  }
963
 
964
+ quota_error = crud_video.get_upload_quota_error(db, current_user, video_type)
965
+ if quota_error:
966
+ return _fail(quota_error, status_code=403)
 
 
967
 
968
  task_id = str(uuid.uuid4())
969
 
 
993
  processing_key=task_id,
994
  )
995
 
 
 
 
 
 
 
 
996
  db_video = crud_video.create_video(db, video_create_data, user_id=current_user.id)
997
  db_video.status = "pending"
998
  logger.info(f"Video record created in DB: id={db_video.id}")
 
1467
  return {"status": "success", "message": "Comment deleted successfully"}
1468
 
1469
 
1470
+ # ── Media Analysis (Disabled for now) ─────────────────────────────────────────
1471
 
1472
  @router.get("/{video_id}/analysis")
1473
  def get_media_analysis(video_id: str, db: Session = Depends(get_db)):
1474
+ """Return the media_analysis row for a video (disabled)."""
1475
+ raise HTTPException(status_code=404, detail="Media analysis is currently disabled")
 
 
 
 
1476
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1477
 
1478
+ # ── Editing Feedback (Disabled for now) ───────────────────────────────────────
1479
 
1480
  @router.post("/{video_id}/feedback")
1481
  def post_edit_feedback(
 
1483
  db: Session = Depends(get_db),
1484
  current_user: schemas.User = Depends(get_current_user),
1485
  ):
1486
+ """Generate AI editing feedback (disabled)."""
1487
+ raise HTTPException(status_code=503, detail="AI editing feedback is currently disabled")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1488
 
1489
 
1490
  @router.get("/{video_id}/feedback")
app/core/asset_tokens.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HMAC-signed, expiring download tokens for Monteeq Assets (local mode).
2
+
3
+ Token format: <payload_b64>.<signature_hex>
4
+ where payload is "<asset_id>:<expires_at_unix>" and the signature is
5
+ HMAC-SHA256(secret, payload_b64).
6
+
7
+ The token binds only the asset id and expiry — never a storage key. Keys are
8
+ generated by the backend and resolved server-side after validation, so there
9
+ is no path-traversal surface.
10
+ """
11
+
12
+ import base64
13
+ import hashlib
14
+ import hmac
15
+ import time
16
+
17
+ from app.core import config
18
+
19
+
20
+ def _secret() -> bytes:
21
+ return (config.ASSETS_DOWNLOAD_SECRET or config.SECRET_KEY).encode()
22
+
23
+
24
+ def create_download_token(asset_id: int, expires_seconds: int | None = None) -> str:
25
+ if expires_seconds is None:
26
+ expires_seconds = config.ASSETS_DOWNLOAD_EXPIRES_SECONDS
27
+ expires_at = int(time.time()) + int(expires_seconds)
28
+ payload = f"{int(asset_id)}:{expires_at}".encode()
29
+ payload_b64 = base64.urlsafe_b64encode(payload).decode().rstrip("=")
30
+ sig = hmac.new(_secret(), payload_b64.encode(), hashlib.sha256).hexdigest()
31
+ return f"{payload_b64}.{sig}"
32
+
33
+
34
+ def verify_download_token(token: str) -> int:
35
+ """Return the asset id if the token is valid and unexpired, else raise."""
36
+ from fastapi import HTTPException
37
+
38
+ try:
39
+ payload_b64, sig = token.split(".", 1)
40
+ except ValueError:
41
+ raise HTTPException(status_code=403, detail="Invalid download token")
42
+
43
+ expected = hmac.new(_secret(), payload_b64.encode(), hashlib.sha256).hexdigest()
44
+ if not hmac.compare_digest(expected, sig):
45
+ raise HTTPException(status_code=403, detail="Invalid download token")
46
+
47
+ # Restore base64 padding before decoding.
48
+ padded = payload_b64 + "=" * (-len(payload_b64) % 4)
49
+ try:
50
+ raw = base64.urlsafe_b64decode(padded.encode()).decode()
51
+ asset_id_s, exp_s = raw.split(":", 1)
52
+ asset_id, exp = int(asset_id_s), int(exp_s)
53
+ except Exception:
54
+ raise HTTPException(status_code=403, detail="Invalid download token")
55
+
56
+ if exp < int(time.time()):
57
+ raise HTTPException(status_code=403, detail="Download link has expired")
58
+ return asset_id
app/core/config.py CHANGED
@@ -84,3 +84,52 @@ EMAIL_PROVIDER = os.getenv("EMAIL_PROVIDER", "").strip().lower() # e.g. "resend
84
  # Redis Configuration (Live Cloud)
85
  REDIS_URL = os.getenv("REDIS_URL")
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  # Redis Configuration (Live Cloud)
85
  REDIS_URL = os.getenv("REDIS_URL")
86
 
87
+ # ── Monteeq Clips (free asset library) ──────────────────────────────────────
88
+ # Private files live under clips/files/ and previews under clips/previews/.
89
+ # In local mode the private prefix is stored OUTSIDE the statically served
90
+ # directory and is only reachable via signed download-token URLs — get_url()
91
+ # must never be used for file_key values.
92
+ ASSETS_FILE_PREFIX = "clips/files/"
93
+ ASSETS_PREVIEW_PREFIX = "clips/previews/"
94
+ PRIVATE_STORAGE_DIR = os.getenv(
95
+ "PRIVATE_STORAGE_DIR",
96
+ os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "private_storage"),
97
+ )
98
+
99
+ # HMAC secret for local-mode download tokens. Falls back to SECRET_KEY so the
100
+ # default local setup works with no extra configuration.
101
+ ASSETS_DOWNLOAD_SECRET = os.getenv("ASSETS_DOWNLOAD_SECRET", "") or SECRET_KEY
102
+ # Short-lived download URL/token lifetime, in seconds.
103
+ ASSETS_DOWNLOAD_EXPIRES_SECONDS = int(os.getenv("ASSETS_DOWNLOAD_EXPIRES_SECONDS", "300"))
104
+
105
+ # Upload limits (bytes). Previews are smaller by default.
106
+ ASSETS_MAX_FILE_BYTES = int(os.getenv("ASSETS_MAX_FILE_BYTES", str(500 * 1024 * 1024)))
107
+ ASSETS_MAX_PREVIEW_BYTES = int(os.getenv("ASSETS_MAX_PREVIEW_BYTES", str(100 * 1024 * 1024)))
108
+
109
+
110
+ def _parse_ext_list(raw: str) -> set[str]:
111
+ return {e.strip().lower() if e.strip().startswith(".") else f".{e.strip().lower()}"
112
+ for e in (raw or "").split(",") if e.strip()}
113
+
114
+
115
+ # Allowed downloadable extensions per asset category (lowercase, dotted).
116
+ ASSETS_ALLOWED_EXTENSIONS = {
117
+ "presets": _parse_ext_list(os.getenv(
118
+ "ASSETS_ALLOWED_EXTENSIONS_PRESETS", ".xmp,.lrtemplate,.dng,.zip")),
119
+ "luts": _parse_ext_list(os.getenv(
120
+ "ASSETS_ALLOWED_EXTENSIONS_LUTS", ".cube,.3dl,.look,.zip")),
121
+ "transitions": _parse_ext_list(os.getenv(
122
+ "ASSETS_ALLOWED_EXTENSIONS_TRANSITIONS", ".prproj,.mogrt,.mp4,.mov,.zip")),
123
+ "overlays": _parse_ext_list(os.getenv(
124
+ "ASSETS_ALLOWED_EXTENSIONS_OVERLAYS", ".mp4,.mov,.png,.jpg,.jpeg,.zip")),
125
+ "sfx": _parse_ext_list(os.getenv(
126
+ "ASSETS_ALLOWED_EXTENSIONS_SFX", ".wav,.mp3,.ogg,.zip")),
127
+ "project_files": _parse_ext_list(os.getenv(
128
+ "ASSETS_ALLOWED_EXTENSIONS_PROJECT_FILES", ".prproj,.aep,.psd,.drp,.zip")),
129
+ }
130
+ # Allowed preview extensions (shared across categories).
131
+ ASSETS_ALLOWED_PREVIEW_EXTENSIONS = _parse_ext_list(os.getenv(
132
+ "ASSETS_ALLOWED_PREVIEW_EXTENSIONS",
133
+ ".png,.jpg,.jpeg,.gif,.webp,.mp4,.mov,.webm,.wav,.mp3,.ogg",
134
+ ))
135
+
app/core/storage.py CHANGED
@@ -2,7 +2,8 @@ import os
2
  import logging
3
  import time
4
  import asyncio
5
- from typing import Optional
 
6
  import shutil
7
  import boto3
8
  from botocore.exceptions import ClientError
@@ -204,6 +205,51 @@ class Storage:
204
  # Fallback to direct AWS S3
205
  return f"https://{config.AWS_STORAGE_BUCKET_NAME}.s3.{config.AWS_S3_REGION_NAME}.amazonaws.com/{url_key}"
206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  def delete_file(self, s3_key: str) -> None:
208
  """
209
  Deletes a file from storage.
@@ -270,4 +316,88 @@ class Storage:
270
  except Exception as e:
271
  logger.error(f"Failed to delete S3 prefix {prefix}: {e}", exc_info=True)
272
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
  storage = Storage()
 
2
  import logging
3
  import time
4
  import asyncio
5
+ from typing import Optional, Set
6
+ from urllib.parse import urlsplit
7
  import shutil
8
  import boto3
9
  from botocore.exceptions import ClientError
 
205
  # Fallback to direct AWS S3
206
  return f"https://{config.AWS_STORAGE_BUCKET_NAME}.s3.{config.AWS_S3_REGION_NAME}.amazonaws.com/{url_key}"
207
 
208
+ def _storage_hosts(self) -> Set[str]:
209
+ """Hostnames that may appear in URLs we own (current + legacy).
210
+
211
+ The current CDN host comes from AWS_CLOUDFRONT_DOMAIN, so changing the
212
+ distribution/domain is an env change, not a code change.
213
+ """
214
+ hosts = {"amazonaws.com", "cloudfront.net", "cdn.monteeq.com"}
215
+ if config.AWS_CLOUDFRONT_DOMAIN:
216
+ hosts.add(config.AWS_CLOUDFRONT_DOMAIN.strip().lower())
217
+ if config.S3_ENDPOINT:
218
+ endpoint_host = urlsplit(config.S3_ENDPOINT).hostname
219
+ if endpoint_host:
220
+ hosts.add(endpoint_host.lower())
221
+ if config.AWS_STORAGE_BUCKET_NAME:
222
+ hosts.add(
223
+ f"{config.AWS_STORAGE_BUCKET_NAME}.s3.{config.AWS_S3_REGION_NAME}.amazonaws.com".lower()
224
+ )
225
+ return {h for h in hosts if h}
226
+
227
+ def key_from_url(self, url: Optional[str]) -> Optional[str]:
228
+ """Return the object key if `url` points at our storage/CDN, else None."""
229
+ if not url or not isinstance(url, str):
230
+ return None
231
+ parsed = urlsplit(url)
232
+ if parsed.scheme not in ("http", "https"):
233
+ return None
234
+ host = (parsed.hostname or "").lower()
235
+ if not any(host == h or host.endswith("." + h) for h in self._storage_hosts()):
236
+ return None
237
+ key = parsed.path.lstrip("/")
238
+ return key or None
239
+
240
+ def resolve_cdn_url(self, url: Optional[str]) -> Optional[str]:
241
+ """Rewrite a stored storage/CDN URL to the currently configured CDN URL.
242
+
243
+ Handles legacy hosts (cdn.monteeq.com, old CloudFront distributions, raw
244
+ S3 endpoints). URLs that do not point at our storage are returned as-is.
245
+ """
246
+ if not url or not isinstance(url, str):
247
+ return url
248
+ key = self.key_from_url(url)
249
+ if not key:
250
+ return url
251
+ return self.get_url(key)
252
+
253
  def delete_file(self, s3_key: str) -> None:
254
  """
255
  Deletes a file from storage.
 
316
  except Exception as e:
317
  logger.error(f"Failed to delete S3 prefix {prefix}: {e}", exc_info=True)
318
 
319
+ # ── Monteeq Assets: private files + short-lived download URLs ─────────────
320
+ # Previews (clips/previews/) are public and served through get_url().
321
+ # Downloadable files (clips/files/) are private: in local mode they live
322
+ # OUTSIDE the statically served directory and are only reachable via
323
+ # HMAC-signed download-token URLs; get_url() must never be used for them.
324
+ # In s3 mode they live in the same bucket and are served via presigned URLs.
325
+
326
+ @staticmethod
327
+ def _validate_key(s3_key: str) -> str:
328
+ """Reject path traversal. Keys are generated by the backend, never user input."""
329
+ if not s3_key or not isinstance(s3_key, str):
330
+ raise ValueError("Invalid storage key")
331
+ if s3_key.startswith("/") or "\\" in s3_key:
332
+ raise ValueError("Invalid storage key")
333
+ parts = s3_key.split("/")
334
+ if not all(parts) or ".." in parts or "." in parts:
335
+ raise ValueError("Invalid storage key")
336
+ normalized = os.path.normpath(s3_key).replace(os.sep, "/")
337
+ if normalized != s3_key:
338
+ raise ValueError("Invalid storage key")
339
+ return s3_key
340
+
341
+ def _local_private_path(self, s3_key: str) -> str:
342
+ self._validate_key(s3_key)
343
+ return os.path.join(config.PRIVATE_STORAGE_DIR, s3_key.replace("/", os.sep))
344
+
345
+ def upload_private_file_obj(self, file_obj, s3_key: str) -> str:
346
+ """Store a private (downloadable) object. Returns the key in local mode."""
347
+ self._validate_key(s3_key)
348
+ if self.mode == "local":
349
+ dest_path = self._local_private_path(s3_key)
350
+ os.makedirs(os.path.dirname(dest_path), exist_ok=True)
351
+ with open(dest_path, "wb") as buffer:
352
+ shutil.copyfileobj(file_obj, buffer)
353
+ return s3_key
354
+ return self.upload_file_obj(file_obj, s3_key)
355
+
356
+ def upload_private_file(self, local_path: str, s3_key: str) -> str:
357
+ """Path-based variant of upload_private_file_obj."""
358
+ self._validate_key(s3_key)
359
+ if self.mode == "local":
360
+ dest_path = self._local_private_path(s3_key)
361
+ os.makedirs(os.path.dirname(dest_path), exist_ok=True)
362
+ shutil.copy2(local_path, dest_path)
363
+ return s3_key
364
+ return self.upload_file(local_path, s3_key)
365
+
366
+ def local_private_exists(self, s3_key: str) -> bool:
367
+ try:
368
+ return os.path.isfile(self._local_private_path(s3_key))
369
+ except ValueError:
370
+ return False
371
+
372
+ def generate_presigned_download_url(self, s3_key: str, expires_seconds: int = 300) -> str:
373
+ """Short-lived GET URL for a private object (s3 mode, any S3-compatible endpoint)."""
374
+ self._validate_key(s3_key)
375
+ if not self.s3_client:
376
+ raise ValueError("S3 client is not initialized.")
377
+ return self.s3_client.generate_presigned_url(
378
+ "get_object",
379
+ Params={"Bucket": config.AWS_STORAGE_BUCKET_NAME, "Key": s3_key},
380
+ ExpiresIn=int(expires_seconds),
381
+ )
382
+
383
+ def get_asset_download_url(
384
+ self, asset_id: int, file_key: str, expires_seconds: int | None = None
385
+ ) -> str:
386
+ """Short-lived download URL for an asset's private file.
387
+
388
+ Local mode → URL to GET /api/v1/assets/download/{token} (HMAC-signed,
389
+ expiring; the token encodes only the asset id). S3 mode → presigned GET.
390
+ """
391
+ from app.core.asset_tokens import create_download_token
392
+
393
+ if expires_seconds is None:
394
+ expires_seconds = config.ASSETS_DOWNLOAD_EXPIRES_SECONDS
395
+ self._validate_key(file_key)
396
+ if self.mode == "local":
397
+ token = create_download_token(asset_id, expires_seconds)
398
+ base = (config.BASE_URL or "").rstrip("/")
399
+ return f"{base}/api/v1/assets/download/{token}"
400
+ return self.generate_presigned_download_url(file_key, expires_seconds)
401
+
402
+
403
  storage = Storage()
app/crud/user.py CHANGED
@@ -3,6 +3,7 @@ from sqlalchemy import func
3
  from app.schemas import schemas
4
  from app.core import security
5
  from app.models.models import User, Follow, Video, Like, Post, VerificationCode, ChallengeEntry, Challenge
 
6
  from datetime import datetime, timedelta
7
  from typing import Optional
8
  import random
@@ -163,6 +164,7 @@ def get_user_profile(db: Session, username: str, current_user_id: int = None):
163
  all_videos = db.query(Video).filter(Video.owner_id == user_id, Video.status == "approved").all()
164
  videos = [v for v in all_videos if v.video_type == "home"]
165
  flash_videos = [v for v in all_videos if v.video_type == "flash"]
 
166
 
167
  # Sort videos to find most popular
168
  sorted_videos = sorted(all_videos, key=lambda x: x.views or 0, reverse=True)
@@ -195,8 +197,8 @@ def get_user_profile(db: Session, username: str, current_user_id: int = None):
195
  "is_premium": db_user.is_premium,
196
  "is_verified": db_user.is_verified,
197
  "is_onboarded": db_user.is_onboarded,
198
- "flash_uploads": db_user.flash_uploads,
199
- "home_uploads": db_user.home_uploads,
200
  "bio": db_user.bio,
201
  "role": db_user.role,
202
  "google_id": db_user.google_id,
 
3
  from app.schemas import schemas
4
  from app.core import security
5
  from app.models.models import User, Follow, Video, Like, Post, VerificationCode, ChallengeEntry, Challenge
6
+ from app.crud import video as crud_video
7
  from datetime import datetime, timedelta
8
  from typing import Optional
9
  import random
 
164
  all_videos = db.query(Video).filter(Video.owner_id == user_id, Video.status == "approved").all()
165
  videos = [v for v in all_videos if v.video_type == "home"]
166
  flash_videos = [v for v in all_videos if v.video_type == "flash"]
167
+ upload_counts = crud_video.get_user_upload_counts(db, user_id)
168
 
169
  # Sort videos to find most popular
170
  sorted_videos = sorted(all_videos, key=lambda x: x.views or 0, reverse=True)
 
197
  "is_premium": db_user.is_premium,
198
  "is_verified": db_user.is_verified,
199
  "is_onboarded": db_user.is_onboarded,
200
+ "flash_uploads": upload_counts["flash"],
201
+ "home_uploads": upload_counts["home"],
202
  "bio": db_user.bio,
203
  "role": db_user.role,
204
  "google_id": db_user.google_id,
app/crud/video.py CHANGED
@@ -2,6 +2,7 @@ from sqlalchemy.orm import Session, joinedload
2
  from sqlalchemy import func, desc, text, or_
3
  from app.models.models import Video, Like, Comment, View, User, Post, SponsoredAd
4
  from app.schemas import schemas
 
5
  from datetime import datetime, timedelta
6
  from typing import Optional, Union
7
  import logging
@@ -14,6 +15,37 @@ INTEREST_BOOST_PER_TAG = 0.2
14
  TRENDING_WINDOW_DAYS = 7
15
  FAILED_VIDEO_VISIBILITY_HOURS = 24
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  def get_videos(db: Session, video_type: Optional[str] = None, filter_status: str = "approved", current_user_id: Optional[int] = None, skip: int = 0, limit: int = 100, mood: Optional[str] = None, feed_mode: Optional[str] = None):
18
  from app.models.models import Follow
19
  query = db.query(Video).options(joinedload(Video.owner))
 
2
  from sqlalchemy import func, desc, text, or_
3
  from app.models.models import Video, Like, Comment, View, User, Post, SponsoredAd
4
  from app.schemas import schemas
5
+ from app.core.config import FLASH_QUOTA_LIMIT, HOME_QUOTA_LIMIT
6
  from datetime import datetime, timedelta
7
  from typing import Optional, Union
8
  import logging
 
15
  TRENDING_WINDOW_DAYS = 7
16
  FAILED_VIDEO_VISIBILITY_HOURS = 24
17
 
18
+ def get_user_upload_counts(db: Session, user_id: int) -> dict[str, int]:
19
+ """Count quota-eligible videos from records instead of stale user counters."""
20
+ counts = dict(
21
+ db.query(Video.video_type, func.count(Video.id))
22
+ .filter(
23
+ Video.owner_id == user_id,
24
+ or_(Video.status.is_(None), Video.status != "failed"),
25
+ )
26
+ .group_by(Video.video_type)
27
+ .all()
28
+ )
29
+ return {
30
+ "home": counts.get("home", 0),
31
+ "flash": counts.get("flash", 0),
32
+ }
33
+
34
+
35
+ def get_upload_quota_error(db: Session, user: User, video_type: str) -> Optional[str]:
36
+ """Lock the uploader and enforce quota using their current video records."""
37
+ if user.is_premium:
38
+ return None
39
+
40
+ # Serialize concurrent uploads for a user until their video row is committed.
41
+ db.query(User.id).filter(User.id == user.id).with_for_update().first()
42
+ counts = get_user_upload_counts(db, user.id)
43
+ if video_type == "flash" and counts["flash"] >= FLASH_QUOTA_LIMIT:
44
+ return f"Flash quota exceeded ({FLASH_QUOTA_LIMIT} max)"
45
+ if video_type == "home" and counts["home"] >= HOME_QUOTA_LIMIT:
46
+ return f"Home quota exceeded ({HOME_QUOTA_LIMIT} max)"
47
+ return None
48
+
49
  def get_videos(db: Session, video_type: Optional[str] = None, filter_status: str = "approved", current_user_id: Optional[int] = None, skip: int = 0, limit: int = 100, mood: Optional[str] = None, feed_mode: Optional[str] = None):
50
  from app.models.models import Follow
51
  query = db.query(Video).options(joinedload(Video.owner))
app/models/assets.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+
3
+ from sqlalchemy import (
4
+ Boolean,
5
+ CheckConstraint,
6
+ Column,
7
+ DateTime,
8
+ ForeignKey,
9
+ Index,
10
+ Integer,
11
+ Numeric,
12
+ String,
13
+ Text,
14
+ func,
15
+ )
16
+ from sqlalchemy.orm import backref, relationship
17
+
18
+ from app.db.base import Base
19
+
20
+
21
+ class AssetCategory(str, enum.Enum):
22
+ PRESETS = "presets"
23
+ LUTS = "luts"
24
+ TRANSITIONS = "transitions"
25
+ OVERLAYS = "overlays"
26
+ SFX = "sfx"
27
+ PROJECT_FILES = "project_files"
28
+
29
+
30
+ class AssetPreviewType(str, enum.Enum):
31
+ BEFORE_AFTER = "before_after"
32
+ VIDEO = "video"
33
+ AUDIO = "audio"
34
+ IMAGE = "image"
35
+
36
+
37
+ class Asset(Base):
38
+ """
39
+ A downloadable file in the free asset library (presets, LUTs, transitions,
40
+ overlays, SFX, project files).
41
+
42
+ `file_key` is the S3 key of the downloadable file and is NEVER exposed on a
43
+ public response — clients must go through POST /assets/{id}/download to get a
44
+ short-lived signed URL. `preview_key` is safe to sign publicly.
45
+ """
46
+
47
+ __tablename__ = "assets"
48
+
49
+ id = Column(Integer, primary_key=True, autoincrement=True)
50
+ title = Column(String(200), nullable=False)
51
+ description = Column(Text, nullable=True)
52
+ category = Column(String(50), nullable=False, index=True)
53
+ owner_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True)
54
+
55
+ # Downloadable object — private, never returned by public endpoints.
56
+ file_key = Column(String(500), nullable=False)
57
+ # Public-facing sample (image/video/audio/before-after strip).
58
+ preview_key = Column(String(500), nullable=True)
59
+ preview_type = Column(String(50), nullable=True)
60
+
61
+ format = Column(String(50), nullable=True) # e.g. "cube", "zip", "wav", "prproj"
62
+ size_bytes = Column(Integer, nullable=True)
63
+ license_note = Column(Text, nullable=True)
64
+
65
+ # Kept so paid/seller uploads can ship later without reshaping the table.
66
+ is_free = Column(Boolean, default=True, nullable=False, server_default="true")
67
+ price = Column(Numeric(12, 2), nullable=True)
68
+
69
+ download_count = Column(Integer, default=0, nullable=False, server_default="0")
70
+ is_published = Column(Boolean, default=True, nullable=False, server_default="true", index=True)
71
+ created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, index=True)
72
+
73
+ owner = relationship("User", backref=backref("assets", lazy="dynamic"))
74
+ downloads = relationship(
75
+ "AssetDownload",
76
+ back_populates="asset",
77
+ cascade="all, delete-orphan",
78
+ )
79
+
80
+ __table_args__ = (
81
+ CheckConstraint(
82
+ "category IN ('presets', 'luts', 'transitions', 'overlays', 'sfx', 'project_files')",
83
+ name="ck_assets_category",
84
+ ),
85
+ CheckConstraint(
86
+ "preview_type IS NULL OR preview_type IN ('before_after', 'video', 'audio', 'image')",
87
+ name="ck_assets_preview_type",
88
+ ),
89
+ CheckConstraint("download_count >= 0", name="ck_assets_download_count"),
90
+ Index("ix_assets_published_category", "is_published", "category"),
91
+ )
92
+
93
+
94
+ class AssetDownload(Base):
95
+ """
96
+ One row per download event. Feeds repeat-downloader and
97
+ download-then-upload metrics.
98
+ """
99
+
100
+ __tablename__ = "asset_downloads"
101
+
102
+ id = Column(Integer, primary_key=True, autoincrement=True)
103
+ user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
104
+ asset_id = Column(Integer, ForeignKey("assets.id", ondelete="CASCADE"), nullable=False)
105
+ created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
106
+
107
+ user = relationship("User", backref=backref("asset_downloads", lazy="dynamic"))
108
+ asset = relationship("Asset", back_populates="downloads")
109
+
110
+ __table_args__ = (
111
+ Index("ix_asset_downloads_user_asset", "user_id", "asset_id"),
112
+ Index("ix_asset_downloads_created_at", "created_at"),
113
+ Index("ix_asset_downloads_asset_id", "asset_id"),
114
+ )
app/models/models.py CHANGED
@@ -30,6 +30,7 @@ class UploadJobStatus(str, enum.Enum):
30
 
31
  from app.models.library import WatchHistory, LibraryWatchLater, LikedVideo
32
  from app.models.edit_feedback import EditFeedback
 
33
 
34
  class User(Base):
35
 
@@ -199,19 +200,9 @@ class Video(Base):
199
  return self.owner.username if self.owner else "Unknown"
200
 
201
  def _resolve_url(self, url: str) -> str:
202
- """Helper to convert stored S3 URLs to current CDN/CloudFront URLs."""
203
- if not url:
204
- return url
205
- # If it's already a full URL that doesn't match our current domain, we extract the path
206
- if "amazonaws.com" in url or "monteeq.s3" in url or "cdn.monteeq.com" in url:
207
- from app.core.storage import storage
208
- # Extract the key part (everything after the domain)
209
- # Both S3 and CDN URLs follow the pattern [domain]/[key]
210
- if ".com/" in url:
211
- parts = url.split(".com/")
212
- if len(parts) > 1:
213
- return storage.get_url(parts[1])
214
- return url
215
 
216
  @property
217
  def dynamic_video_url(self):
 
30
 
31
  from app.models.library import WatchHistory, LibraryWatchLater, LikedVideo
32
  from app.models.edit_feedback import EditFeedback
33
+ from app.models.assets import Asset, AssetDownload # noqa: F401 — registers tables on Base
34
 
35
  class User(Base):
36
 
 
200
  return self.owner.username if self.owner else "Unknown"
201
 
202
  def _resolve_url(self, url: str) -> str:
203
+ """Rewrite stored S3/legacy-CDN URLs to the currently configured CDN."""
204
+ from app.core.storage import storage
205
+ return storage.resolve_cdn_url(url)
 
 
 
 
 
 
 
 
 
 
206
 
207
  @property
208
  def dynamic_video_url(self):
app/schemas/assets.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from decimal import Decimal
2
+ from typing import List, Literal, Optional
3
+
4
+ from pydantic import BaseModel, ConfigDict, field_validator
5
+
6
+ from app.models.assets import AssetCategory, AssetPreviewType
7
+
8
+ AssetSort = Literal["popular", "newest"]
9
+
10
+ _CATEGORY_VALUES = sorted(c.value for c in AssetCategory)
11
+ _PREVIEW_VALUES = sorted(p.value for p in AssetPreviewType)
12
+
13
+
14
+ def _norm_category(v: str) -> str:
15
+ v = (v or "").strip().lower()
16
+ if v not in _CATEGORY_VALUES:
17
+ raise ValueError(f"category must be one of: {_CATEGORY_VALUES}")
18
+ return v
19
+
20
+
21
+ def _norm_preview_type(v: Optional[str]) -> Optional[str]:
22
+ if v is None:
23
+ return None
24
+ v = v.strip().lower()
25
+ if not v:
26
+ return None
27
+ if v not in _PREVIEW_VALUES:
28
+ raise ValueError(f"preview_type must be one of: {_PREVIEW_VALUES}")
29
+ return v
30
+
31
+
32
+ # ── Public ────────────────────────────────────────────────────────────────────
33
+ class AssetPublic(BaseModel):
34
+ """Public asset shape. NEVER contains file_key (the downloadable object)."""
35
+
36
+ id: int
37
+ title: str
38
+ description: Optional[str] = None
39
+ category: str
40
+ owner_id: Optional[int] = None
41
+ preview_url: Optional[str] = None
42
+ preview_type: Optional[str] = None
43
+ format: Optional[str] = None
44
+ size_bytes: Optional[int] = None
45
+ license_note: Optional[str] = None
46
+ is_free: bool = True
47
+ price: Optional[Decimal] = None
48
+ download_count: int = 0
49
+ created_at: Optional[str] = None
50
+
51
+ model_config = ConfigDict(from_attributes=True)
52
+
53
+
54
+ class AssetListResponse(BaseModel):
55
+ items: List[AssetPublic]
56
+ page: int
57
+ limit: int
58
+ total: int
59
+ has_more: bool
60
+
61
+
62
+ class AssetDownloadResponse(BaseModel):
63
+ download_url: str
64
+ expires_in: int
65
+
66
+
67
+ # ── Admin ─────────────────────────────────────────────────────────────────────
68
+ class AssetCreate(BaseModel):
69
+ title: str
70
+ description: Optional[str] = None
71
+ category: str
72
+ preview_type: Optional[str] = None
73
+ format: Optional[str] = None
74
+ license_note: Optional[str] = None
75
+ is_free: bool = True
76
+ price: Optional[Decimal] = None
77
+ is_published: bool = True
78
+
79
+ @field_validator("category")
80
+ @classmethod
81
+ def check_category(cls, v: str) -> str:
82
+ return _norm_category(v)
83
+
84
+ @field_validator("preview_type")
85
+ @classmethod
86
+ def check_preview(cls, v: Optional[str]) -> Optional[str]:
87
+ return _norm_preview_type(v)
88
+
89
+
90
+ class AssetUpdate(BaseModel):
91
+ title: Optional[str] = None
92
+ description: Optional[str] = None
93
+ category: Optional[str] = None
94
+ preview_type: Optional[str] = None
95
+ format: Optional[str] = None
96
+ license_note: Optional[str] = None
97
+ is_free: Optional[bool] = None
98
+ price: Optional[Decimal] = None
99
+ is_published: Optional[bool] = None
100
+
101
+ @field_validator("category")
102
+ @classmethod
103
+ def check_category(cls, v: Optional[str]) -> Optional[str]:
104
+ return _norm_category(v) if v is not None else v
105
+
106
+ @field_validator("preview_type")
107
+ @classmethod
108
+ def check_preview(cls, v: Optional[str]) -> Optional[str]:
109
+ return _norm_preview_type(v) if v is not None else v
app/schemas/schemas.py CHANGED
@@ -17,16 +17,11 @@ class UserBase(BaseModel):
17
  def resolve_user_cdn_url(cls, v):
18
  if not v or not isinstance(v, str):
19
  return v
20
- if "amazonaws.com" in v or "monteeq.s3" in v or "cdn.monteeq.com" in v:
21
- try:
22
- from app.core.storage import storage
23
- if ".com/" in v:
24
- parts = v.split(".com/")
25
- if len(parts) > 1:
26
- return storage.get_url(parts[1])
27
- except Exception:
28
- return v
29
- return v
30
 
31
  model_config = ConfigDict(from_attributes=True)
32
 
@@ -224,16 +219,11 @@ class Video(VideoBase):
224
  def resolve_cdn_url(cls, v):
225
  if not v or not isinstance(v, str):
226
  return v
227
- if "amazonaws.com" in v or "monteeq.s3" in v or "cdn.monteeq.com" in v:
228
- try:
229
- from app.core.storage import storage
230
- if ".com/" in v:
231
- parts = v.split(".com/")
232
- if len(parts) > 1:
233
- return storage.get_url(parts[1])
234
- except Exception:
235
- return v
236
- return v
237
 
238
  @field_serializer('id')
239
  def serialize_id(self, v: int) -> Union[int, str]:
@@ -272,16 +262,11 @@ class Post(PostBase):
272
  def resolve_post_cdn_url(cls, v):
273
  if not v or not isinstance(v, str):
274
  return v
275
- if "amazonaws.com" in v or "monteeq.s3" in v or "cdn.monteeq.com" in v:
276
- try:
277
- from app.core.storage import storage
278
- if ".com/" in v:
279
- parts = v.split(".com/")
280
- if len(parts) > 1:
281
- return storage.get_url(parts[1])
282
- except Exception:
283
- return v
284
- return v
285
 
286
  model_config = ConfigDict(from_attributes=True)
287
 
 
17
  def resolve_user_cdn_url(cls, v):
18
  if not v or not isinstance(v, str):
19
  return v
20
+ try:
21
+ from app.core.storage import storage
22
+ return storage.resolve_cdn_url(v)
23
+ except Exception:
24
+ return v
 
 
 
 
 
25
 
26
  model_config = ConfigDict(from_attributes=True)
27
 
 
219
  def resolve_cdn_url(cls, v):
220
  if not v or not isinstance(v, str):
221
  return v
222
+ try:
223
+ from app.core.storage import storage
224
+ return storage.resolve_cdn_url(v)
225
+ except Exception:
226
+ return v
 
 
 
 
 
227
 
228
  @field_serializer('id')
229
  def serialize_id(self, v: int) -> Union[int, str]:
 
262
  def resolve_post_cdn_url(cls, v):
263
  if not v or not isinstance(v, str):
264
  return v
265
+ try:
266
+ from app.core.storage import storage
267
+ return storage.resolve_cdn_url(v)
268
+ except Exception:
269
+ return v
 
 
 
 
 
270
 
271
  model_config = ConfigDict(from_attributes=True)
272
 
app/services/email_service.py CHANGED
@@ -140,6 +140,7 @@ def _send_via_resend(
140
  headers={
141
  "Authorization": f"Bearer {api_key}",
142
  "Content-Type": "application/json",
 
143
  },
144
  json=payload,
145
  timeout=20,
 
140
  headers={
141
  "Authorization": f"Bearer {api_key}",
142
  "Content-Type": "application/json",
143
+ "User-Agent": "MonteeqBackend/1.0",
144
  },
145
  json=payload,
146
  timeout=20,
app/tasks/email_tasks.py CHANGED
@@ -5,6 +5,7 @@ Registered in worker.py beat_schedule.
5
  import logging
6
  from datetime import datetime, timedelta, timezone
7
  from celery import shared_task
 
8
 
9
  from app.db.session import SessionLocal
10
  from app.models.models import User, Challenge, Video
@@ -149,8 +150,10 @@ def check_onboarding_nudges():
149
  User.is_active == True,
150
  User.created_at >= window_start,
151
  User.created_at < window_end,
152
- User.home_uploads == 0,
153
- User.flash_uploads == 0,
 
 
154
  )
155
  .all()
156
  )
@@ -244,7 +247,10 @@ def send_monthly_stats_batch():
244
  creators = db.query(User).filter(
245
  User.is_active == True,
246
  User.email_weekly == True,
247
- User.home_uploads + User.flash_uploads > 0,
 
 
 
248
  ).all()
249
 
250
  trigger = EmailTrigger(db)
@@ -309,7 +315,10 @@ def send_growth_drip():
309
  users = db.query(User).filter(
310
  User.is_active == True,
311
  User.email_marketing == True,
312
- User.home_uploads + User.flash_uploads > 0,
 
 
 
313
  ).all()
314
 
315
  sent = 0
@@ -389,4 +398,3 @@ def flush_social_batch():
389
  logger.error("flush_social_batch failed: %s", e)
390
  finally:
391
  db.close()
392
-
 
5
  import logging
6
  from datetime import datetime, timedelta, timezone
7
  from celery import shared_task
8
+ from sqlalchemy import or_
9
 
10
  from app.db.session import SessionLocal
11
  from app.models.models import User, Challenge, Video
 
150
  User.is_active == True,
151
  User.created_at >= window_start,
152
  User.created_at < window_end,
153
+ ~db.query(Video.id).filter(
154
+ Video.owner_id == User.id,
155
+ or_(Video.status.is_(None), Video.status != "failed"),
156
+ ).exists(),
157
  )
158
  .all()
159
  )
 
247
  creators = db.query(User).filter(
248
  User.is_active == True,
249
  User.email_weekly == True,
250
+ db.query(Video.id).filter(
251
+ Video.owner_id == User.id,
252
+ or_(Video.status.is_(None), Video.status != "failed"),
253
+ ).exists(),
254
  ).all()
255
 
256
  trigger = EmailTrigger(db)
 
315
  users = db.query(User).filter(
316
  User.is_active == True,
317
  User.email_marketing == True,
318
+ db.query(Video.id).filter(
319
+ Video.owner_id == User.id,
320
+ or_(Video.status.is_(None), Video.status != "failed"),
321
+ ).exists(),
322
  ).all()
323
 
324
  sent = 0
 
398
  logger.error("flush_social_batch failed: %s", e)
399
  finally:
400
  db.close()
 
app/tasks/media_tasks.py CHANGED
@@ -23,12 +23,9 @@ logger = logging.getLogger(__name__)
23
 
24
  @shared_task(name="tasks.media.analyze_media", max_retries=2, default_retry_delay=120)
25
  def analyze_media(video_id: int):
26
- """Download transcoded video, run frame extraction, scene detection,
27
- beat tracking, and caption embedding, then write results to media_analysis.
28
-
29
- After completion, fires ``generate_visual_embedding`` as a follow-up task
30
- so the heavier CLIP work is retryable independently.
31
- """
32
 
33
  db = SessionLocal()
34
  video = None
@@ -160,12 +157,10 @@ def analyze_media(video_id: int):
160
  retry_jitter=True,
161
  )
162
  def generate_visual_embedding(video_id: int):
163
- """Download representative frames from S3, encode with CLIP ViT-B/32,
164
- and write the averaged L2-normalized vector to visual_embedding.
 
165
 
166
- This task is decoupled from ``analyze_media`` so transient S3 or model
167
- failures can retry without re-running the full analysis pipeline.
168
- """
169
  db = SessionLocal()
170
  try:
171
  from sqlalchemy import text as sa_text
 
23
 
24
  @shared_task(name="tasks.media.analyze_media", max_retries=2, default_retry_delay=120)
25
  def analyze_media(video_id: int):
26
+ """Media analysis is disabled for now."""
27
+ logger.info("analyze_media is currently disabled; skipping video %s", video_id)
28
+ return {"status": "disabled", "video_id": video_id}
 
 
 
29
 
30
  db = SessionLocal()
31
  video = None
 
157
  retry_jitter=True,
158
  )
159
  def generate_visual_embedding(video_id: int):
160
+ """Visual embedding is disabled for now."""
161
+ logger.info("generate_visual_embedding is currently disabled; skipping video %s", video_id)
162
+ return {"status": "disabled", "video_id": video_id}
163
 
 
 
 
164
  db = SessionLocal()
165
  try:
166
  from sqlalchemy import text as sa_text
app/tasks/video_tasks.py CHANGED
@@ -60,12 +60,6 @@ def _mark_video_failed(db, video_id: int, title: str, task_id: str, upload_job_i
60
  video.status = "failed"
61
  video.failed_at = func.now()
62
  video.processing_message = error_message[:500] if error_message else "Failed"
63
- owner = db.query(User).filter(User.id == video.owner_id).first()
64
- if owner:
65
- if video.video_type == "flash":
66
- owner.flash_uploads = max(0, (owner.flash_uploads or 1) - 1)
67
- else:
68
- owner.home_uploads = max(0, (owner.home_uploads or 1) - 1)
69
  db.commit()
70
  try:
71
  notify_user_push(
@@ -197,12 +191,12 @@ def _finalize_transcode_success(
197
  except Exception as e:
198
  logger.warning(f"Failed to delete source directory uploads/{task_id}/: {e}")
199
 
200
- # Fire-and-forget: run media analysis pipeline asynchronously
201
- try:
202
- from app.tasks.media_tasks import analyze_media
203
- analyze_media.delay(video_id)
204
- except Exception as e:
205
- logger.warning(f"Failed to enqueue media analysis for video {video_id}: {e}")
206
 
207
  return {"status": "success", "video_id": video_id}
208
 
 
60
  video.status = "failed"
61
  video.failed_at = func.now()
62
  video.processing_message = error_message[:500] if error_message else "Failed"
 
 
 
 
 
 
63
  db.commit()
64
  try:
65
  notify_user_push(
 
191
  except Exception as e:
192
  logger.warning(f"Failed to delete source directory uploads/{task_id}/: {e}")
193
 
194
+ # Media analysis pipeline disabled for now
195
+ # try:
196
+ # from app.tasks.media_tasks import analyze_media
197
+ # analyze_media.delay(video_id)
198
+ # except Exception as e:
199
+ # logger.warning(f"Failed to enqueue media analysis for video {video_id}: {e}")
200
 
201
  return {"status": "success", "video_id": video_id}
202
 
app/worker.py CHANGED
@@ -18,7 +18,6 @@ celery_app = Celery(
18
  "app.tasks.email_tasks",
19
  "app.tasks.morning_notifications",
20
  "app.tasks.event_tasks",
21
- "app.tasks.media_tasks",
22
  ]
23
  )
24
 
 
18
  "app.tasks.email_tasks",
19
  "app.tasks.morning_notifications",
20
  "app.tasks.event_tasks",
 
21
  ]
22
  )
23
 
tests/test_video_quota.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from sqlalchemy import create_engine
3
+ from sqlalchemy.orm import sessionmaker
4
+
5
+ from app.crud.video import get_upload_quota_error, get_user_upload_counts
6
+ from app.models.models import User, Video
7
+
8
+
9
+ @pytest.fixture
10
+ def db_session():
11
+ engine = create_engine("sqlite:///:memory:")
12
+ tables = [User.__table__, Video.__table__]
13
+ User.metadata.create_all(engine, tables=tables)
14
+ session = sessionmaker(bind=engine)()
15
+ try:
16
+ yield session
17
+ finally:
18
+ session.close()
19
+ engine.dispose()
20
+
21
+
22
+ def create_user(db_session, *, is_premium=False, home_uploads=0, flash_uploads=0):
23
+ user = User(
24
+ username="quota-test",
25
+ email="quota-test@example.com",
26
+ is_premium=is_premium,
27
+ home_uploads=home_uploads,
28
+ flash_uploads=flash_uploads,
29
+ )
30
+ db_session.add(user)
31
+ db_session.commit()
32
+ return user
33
+
34
+
35
+ def create_video(db_session, user_id, video_type="home", status="approved"):
36
+ db_session.add(
37
+ Video(
38
+ title="Quota test",
39
+ video_url="",
40
+ thumbnail_url="",
41
+ video_type=video_type,
42
+ status=status,
43
+ owner_id=user_id,
44
+ )
45
+ )
46
+ db_session.commit()
47
+
48
+
49
+ def test_upload_counts_come_from_non_failed_video_records(db_session):
50
+ user = create_user(db_session)
51
+ create_video(db_session, user.id, "home", "approved")
52
+ create_video(db_session, user.id, "flash", "uploading")
53
+ create_video(db_session, user.id, "home", "failed")
54
+
55
+ assert get_user_upload_counts(db_session, user.id) == {"home": 1, "flash": 1}
56
+
57
+
58
+ def test_stale_counters_do_not_use_quota_without_video_records(db_session):
59
+ user = create_user(db_session, home_uploads=20, flash_uploads=50)
60
+
61
+ assert get_upload_quota_error(db_session, user, "home") is None
62
+ assert get_upload_quota_error(db_session, user, "flash") is None
63
+
64
+
65
+ def test_failed_video_does_not_use_quota(db_session):
66
+ user = create_user(db_session)
67
+ create_video(db_session, user.id, "home", "failed")
68
+
69
+ assert get_upload_quota_error(db_session, user, "home") is None
70
+
71
+
72
+ def test_existing_videos_enforce_separate_type_quotas(db_session):
73
+ user = create_user(db_session)
74
+ for _ in range(20):
75
+ create_video(db_session, user.id, "home")
76
+ for _ in range(50):
77
+ create_video(db_session, user.id, "flash")
78
+
79
+ assert get_upload_quota_error(db_session, user, "home") == "Home quota exceeded (20 max)"
80
+ assert get_upload_quota_error(db_session, user, "flash") == "Flash quota exceeded (50 max)"
81
+
82
+
83
+ def test_premium_user_is_not_limited(db_session):
84
+ user = create_user(db_session, is_premium=True)
85
+ for _ in range(20):
86
+ create_video(db_session, user.id, "home")
87
+
88
+ assert get_upload_quota_error(db_session, user, "home") is None