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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import os
import logging
import time
import asyncio
from typing import Optional, Set
from urllib.parse import urlsplit
import shutil
import boto3
from botocore.exceptions import ClientError
from sqlalchemy.orm import Session

from app.core import config
from app.db.session import SessionLocal
from app.models.models import Setting

logger = logging.getLogger(__name__)

class Storage:
    def __init__(self):
        self._mode: Optional[str] = None
        self._mode_cache_time: float = 0
        self._cache_ttl: int = 60  # Cache DB mode for 60 seconds

        self.s3_client = None
        if config.AWS_ACCESS_KEY_ID:
            self._init_s3_client()

    def _init_s3_client(self):
        try:
            from botocore.config import Config

            is_hf_bucket = config.S3_ENDPOINT and "s3.hf.co" in config.S3_ENDPOINT

            if is_hf_bucket:
                # HF Storage Buckets require path-style addressing and us-east-1 region
                s3_opts = {'region_name': 'us-east-1', 'addressing_style': 'path'}
                logger.info("Using Hugging Face Storage Bucket endpoint")
            else:
                s3_opts = {'region_name': config.AWS_S3_REGION_NAME}
                if config.AWS_S3_USE_ACCELERATE:
                    s3_opts['use_accelerate_endpoint'] = True
                    logger.info("Enabling S3 Transfer Acceleration")

            s3_config = Config(s3=s3_opts)
            self.s3_client = boto3.client(
                's3',
                aws_access_key_id=config.AWS_ACCESS_KEY_ID,
                aws_secret_access_key=config.AWS_SECRET_ACCESS_KEY,
                endpoint_url=config.S3_ENDPOINT,
                config=s3_config
            )
            logger.info("Successfully initialized S3-compatible client")
        except Exception as e:
            logger.error(f"Failed to initialize S3 client: {e}", exc_info=True)

    @property
    def mode(self) -> str:
        """
        Dynamically resolves the storage mode from the database with a TTL cache.
        Falls back to config.STORAGE_MODE if not set in DB.
        """
        current_time = time.time()
        if self._mode and (current_time - self._mode_cache_time) < self._cache_ttl:
            return self._mode

        db = SessionLocal()
        try:
            setting = db.query(Setting).filter(Setting.key == "storage_mode").first()
            if setting and setting.value:
                self._mode = setting.value
            else:
                self._mode = config.STORAGE_MODE
            # Legacy "gcs" label β†’ AWS S3 (credentials from .env)
            if self._mode == "gcs":
                self._mode = "s3"
            self._mode_cache_time = current_time
        except Exception as e:
            logger.error(f"Error fetching storage_mode from DB: {e}", exc_info=True)
            self._mode = config.STORAGE_MODE
        finally:
            db.close()
        
        return self._mode

    def upload_file(self, local_path: str, s3_key: str) -> str:
        """
        Uploads a file to the active storage provider and returns its URL.
        """
        current_mode = self.mode
        
        if current_mode == "local":
            return self._upload_local(local_path, s3_key)
        else:
            return self._upload_s3(local_path, s3_key)

    def _upload_local(self, local_path: str, s3_key: str) -> str:
        dest_path = os.path.join(config.STATIC_DIR, s3_key)
        os.makedirs(os.path.dirname(dest_path), exist_ok=True)
        shutil.copy2(local_path, dest_path)
        url_key = s3_key.replace(os.sep, "/")
        return f"{config.BASE_URL}/static/{url_key}"

    def _upload_s3(self, local_path: str, s3_key: str) -> str:
        if not self.s3_client:
            raise ValueError("AWS S3 client is not initialized.")
        try:
            # S3 upload_file handles chunking and multi-part automatically
            self.s3_client.upload_file(
                local_path, 
                config.AWS_STORAGE_BUCKET_NAME, 
                s3_key
            )
            return self.get_url(s3_key, mode="s3")
        except Exception as e:
            logger.error(f"S3 Upload failed for {s3_key}: {e}", exc_info=True)
            raise

    def upload_file_obj(self, file_obj, s3_key: str) -> str:
        """
        Uploads a file-like object directly to storage (avoids local disk).
        """
        current_mode = self.mode
        
        if current_mode == "local":
            dest_path = os.path.join(config.STATIC_DIR, s3_key)
            os.makedirs(os.path.dirname(dest_path), exist_ok=True)
            with open(dest_path, "wb") as buffer:
                shutil.copyfileobj(file_obj, buffer)
            url_key = s3_key.replace(os.sep, "/")
            return f"{config.BASE_URL}/static/{url_key}"
        else:
            if not self.s3_client:
                raise ValueError("AWS S3 client is not initialized.")
            try:
                # Detect content type from the key extension
                ext = os.path.splitext(s3_key)[1].lower()
                content_type_map = {
                    ".mp4": "video/mp4",
                    ".mov": "video/quicktime",
                    ".avi": "video/x-msvideo",
                    ".mkv": "video/x-matroska",
                    ".webm": "video/webm",
                    ".m3u8": "application/x-mpegURL",
                    ".ts": "video/MP2T",
                    ".jpg": "image/jpeg",
                    ".jpeg": "image/jpeg",
                    ".png": "image/png",
                }
                content_type = content_type_map.get(ext, "application/octet-stream")
                
                from boto3.s3.transfer import TransferConfig
                config_s3 = TransferConfig(
                    multipart_threshold=1024 * 25, # 25MB
                    max_concurrency=10,
                    multipart_chunksize=1024 * 25, # 25MB
                    use_threads=True
                )
                
                self.s3_client.upload_fileobj(
                    file_obj,
                    config.AWS_STORAGE_BUCKET_NAME,
                    s3_key,
                    ExtraArgs={
                        'ContentType': content_type
                    },
                    Config=config_s3
                )
                return self.get_url(s3_key, mode="s3")
            except Exception as e:
                logger.error(f"S3 Object Upload failed for {s3_key}: {e}", exc_info=True)
                raise

    async def async_upload_file_obj(self, file_obj, s3_key: str) -> str:
        """Non-blocking wrapper β€” runs sync boto3 upload off the event loop."""
        return await asyncio.to_thread(self.upload_file_obj, file_obj, s3_key)

    async def async_upload_file(self, local_path: str, s3_key: str) -> str:
        """Non-blocking wrapper for path-based uploads."""
        return await asyncio.to_thread(self.upload_file, local_path, s3_key)

    def get_url(self, s3_key: str, mode: Optional[str] = None) -> str:
        """
        Returns the public URL for a given key.
        Uses CloudFront if configured, otherwise falls back to the endpoint or S3.
        """
        current_mode = mode or self.mode
        url_key = s3_key.replace(os.sep, "/")

        if current_mode == "local":
            return f"{config.BASE_URL}/static/{url_key}"

        # CloudFront takes highest priority (fastest CDN delivery)
        if config.AWS_CLOUDFRONT_DOMAIN:
            return f"https://{config.AWS_CLOUDFRONT_DOMAIN}/{url_key}"

        # Hugging Face Storage Bucket β€” path-style URL
        if config.S3_ENDPOINT and "s3.hf.co" in config.S3_ENDPOINT:
            return f"{config.S3_ENDPOINT.rstrip('/')}/{config.AWS_STORAGE_BUCKET_NAME}/{url_key}"

        # Generic S3-compatible endpoint (e.g. Backblaze, MinIO)
        if config.S3_ENDPOINT:
            endpoint_host = config.S3_ENDPOINT.replace("https://", "").replace("http://", "")
            return f"https://{config.AWS_STORAGE_BUCKET_NAME}.{endpoint_host}/{url_key}"

        # Fallback to direct AWS S3
        return f"https://{config.AWS_STORAGE_BUCKET_NAME}.s3.{config.AWS_S3_REGION_NAME}.amazonaws.com/{url_key}"

    def _storage_hosts(self) -> Set[str]:
        """Hostnames that may appear in URLs we own (current + legacy).

        The current CDN host comes from AWS_CLOUDFRONT_DOMAIN, so changing the
        distribution/domain is an env change, not a code change.
        """
        hosts = {"amazonaws.com", "cloudfront.net", "cdn.monteeq.com"}
        if config.AWS_CLOUDFRONT_DOMAIN:
            hosts.add(config.AWS_CLOUDFRONT_DOMAIN.strip().lower())
        if config.S3_ENDPOINT:
            endpoint_host = urlsplit(config.S3_ENDPOINT).hostname
            if endpoint_host:
                hosts.add(endpoint_host.lower())
        if config.AWS_STORAGE_BUCKET_NAME:
            hosts.add(
                f"{config.AWS_STORAGE_BUCKET_NAME}.s3.{config.AWS_S3_REGION_NAME}.amazonaws.com".lower()
            )
        return {h for h in hosts if h}

    def key_from_url(self, url: Optional[str]) -> Optional[str]:
        """Return the object key if `url` points at our storage/CDN, else None."""
        if not url or not isinstance(url, str):
            return None
        parsed = urlsplit(url)
        if parsed.scheme not in ("http", "https"):
            return None
        host = (parsed.hostname or "").lower()
        if not any(host == h or host.endswith("." + h) for h in self._storage_hosts()):
            return None
        key = parsed.path.lstrip("/")
        return key or None

    def resolve_cdn_url(self, url: Optional[str]) -> Optional[str]:
        """Rewrite a stored storage/CDN URL to the currently configured CDN URL.

        Handles legacy hosts (cdn.monteeq.com, old CloudFront distributions, raw
        S3 endpoints). URLs that do not point at our storage are returned as-is.
        """
        if not url or not isinstance(url, str):
            return url
        key = self.key_from_url(url)
        if not key:
            return url
        return self.get_url(key)

    def delete_file(self, s3_key: str) -> None:
        """
        Deletes a file from storage.
        """
        current_mode = self.mode
        
        if current_mode == "local":
            local_path = os.path.join(config.STATIC_DIR, s3_key.replace("/", os.sep))
            if os.path.exists(local_path):
                try:
                    os.remove(local_path)
                    logger.info(f"Deleted local file: {local_path}")
                except Exception as e:
                    logger.error(f"Failed to delete local file {local_path}: {e}", exc_info=True)
        else:
            if not self.s3_client:
                logger.error("Cannot delete from S3: Client not initialized.")
                return
            try:
                self.s3_client.delete_object(
                    Bucket=config.AWS_STORAGE_BUCKET_NAME,
                    Key=s3_key
                )
                logger.info(f"Deleted S3 object: {s3_key}")
            except Exception as e:
                logger.error(f"Failed to delete S3 object {s3_key}: {e}", exc_info=True)
    def delete_prefix(self, prefix: str) -> None:
        """
        Deletes all objects with the given prefix (folder deletion).
        """
        current_mode = self.mode
        
        if current_mode == "local":
            local_dir = os.path.join(config.STATIC_DIR, prefix.replace("/", os.sep))
            if os.path.exists(local_dir) and os.path.isdir(local_dir):
                try:
                    shutil.rmtree(local_dir)
                    logger.info(f"Deleted local directory: {local_dir}")
                except Exception as e:
                    logger.error(f"Failed to delete local directory {local_dir}: {e}", exc_info=True)
        else:
            if not self.s3_client:
                logger.error("Cannot delete from S3: Client not initialized.")
                return
            try:
                # Paginate through objects with prefix and delete them
                paginator = self.s3_client.get_paginator('list_objects_v2')
                pages = paginator.paginate(Bucket=config.AWS_STORAGE_BUCKET_NAME, Prefix=prefix)

                delete_us = dict(Objects=[])
                for item in pages.search('Contents'):
                    if item:
                        delete_us['Objects'].append(dict(Key=item['Key']))

                        # S3 delete_objects has a limit of 1000 per call
                        if len(delete_us['Objects']) >= 1000:
                            self.s3_client.delete_objects(Bucket=config.AWS_STORAGE_BUCKET_NAME, Delete=delete_us)
                            delete_us = dict(Objects=[])

                if len(delete_us['Objects']):
                    self.s3_client.delete_objects(Bucket=config.AWS_STORAGE_BUCKET_NAME, Delete=delete_us)
                
                logger.info(f"Deleted S3 prefix: {prefix}")
            except Exception as e:
                logger.error(f"Failed to delete S3 prefix {prefix}: {e}", exc_info=True)

    # ── Monteeq Assets: private files + short-lived download URLs ─────────────
    # Previews (clips/previews/) are public and served through get_url().
    # Downloadable files (clips/files/) are private: in local mode they live
    # OUTSIDE the statically served directory and are only reachable via
    # HMAC-signed download-token URLs; get_url() must never be used for them.
    # In s3 mode they live in the same bucket and are served via presigned URLs.

    @staticmethod
    def _validate_key(s3_key: str) -> str:
        """Reject path traversal. Keys are generated by the backend, never user input."""
        if not s3_key or not isinstance(s3_key, str):
            raise ValueError("Invalid storage key")
        if s3_key.startswith("/") or "\\" in s3_key:
            raise ValueError("Invalid storage key")
        parts = s3_key.split("/")
        if not all(parts) or ".." in parts or "." in parts:
            raise ValueError("Invalid storage key")
        normalized = os.path.normpath(s3_key).replace(os.sep, "/")
        if normalized != s3_key:
            raise ValueError("Invalid storage key")
        return s3_key

    def _local_private_path(self, s3_key: str) -> str:
        self._validate_key(s3_key)
        return os.path.join(config.PRIVATE_STORAGE_DIR, s3_key.replace("/", os.sep))

    def upload_private_file_obj(self, file_obj, s3_key: str) -> str:
        """Store a private (downloadable) object. Returns the key in local mode."""
        self._validate_key(s3_key)
        if self.mode == "local":
            dest_path = self._local_private_path(s3_key)
            os.makedirs(os.path.dirname(dest_path), exist_ok=True)
            with open(dest_path, "wb") as buffer:
                shutil.copyfileobj(file_obj, buffer)
            return s3_key
        return self.upload_file_obj(file_obj, s3_key)

    def upload_private_file(self, local_path: str, s3_key: str) -> str:
        """Path-based variant of upload_private_file_obj."""
        self._validate_key(s3_key)
        if self.mode == "local":
            dest_path = self._local_private_path(s3_key)
            os.makedirs(os.path.dirname(dest_path), exist_ok=True)
            shutil.copy2(local_path, dest_path)
            return s3_key
        return self.upload_file(local_path, s3_key)

    def local_private_exists(self, s3_key: str) -> bool:
        try:
            return os.path.isfile(self._local_private_path(s3_key))
        except ValueError:
            return False

    def generate_presigned_download_url(self, s3_key: str, expires_seconds: int = 300) -> str:
        """Short-lived GET URL for a private object (s3 mode, any S3-compatible endpoint)."""
        self._validate_key(s3_key)
        if not self.s3_client:
            raise ValueError("S3 client is not initialized.")
        return self.s3_client.generate_presigned_url(
            "get_object",
            Params={"Bucket": config.AWS_STORAGE_BUCKET_NAME, "Key": s3_key},
            ExpiresIn=int(expires_seconds),
        )

    def get_asset_download_url(
        self, asset_id: int, file_key: str, expires_seconds: int | None = None
    ) -> str:
        """Short-lived download URL for an asset's private file.

        Local mode β†’ URL to GET /api/v1/assets/download/{token} (HMAC-signed,
        expiring; the token encodes only the asset id). S3 mode β†’ presigned GET.
        """
        from app.core.asset_tokens import create_download_token

        if expires_seconds is None:
            expires_seconds = config.ASSETS_DOWNLOAD_EXPIRES_SECONDS
        self._validate_key(file_key)
        if self.mode == "local":
            token = create_download_token(asset_id, expires_seconds)
            base = (config.BASE_URL or "").rstrip("/")
            return f"{base}/api/v1/assets/download/{token}"
        return self.generate_presigned_download_url(file_key, expires_seconds)


storage = Storage()