diff options
Diffstat (limited to 'core')
-rw-r--r-- | core/files.py | 28 | ||||
-rw-r--r-- | core/models/config.py | 2 | ||||
-rw-r--r-- | core/uploads.py | 16 |
3 files changed, 46 insertions, 0 deletions
diff --git a/core/files.py b/core/files.py index a04cef9..3ef79aa 100644 --- a/core/files.py +++ b/core/files.py @@ -1,7 +1,10 @@ import io import blurhash +import httpx +from django.conf import settings from django.core.files import File +from django.core.files.base import ContentFile from PIL import Image, ImageOps @@ -37,3 +40,28 @@ def blurhash_image(file) -> str: Returns the blurhash for an image """ return blurhash.encode(file, 4, 4) + + +async def get_remote_file( + url: str, + *, + timeout: float = settings.SETUP.REMOTE_TIMEOUT, + max_size: int | None = None, +) -> tuple[File | None, str | None]: + """ + Download a URL and return the File and content-type. + """ + async with httpx.AsyncClient() as client: + async with client.stream("GET", url, timeout=timeout) as stream: + allow_download = max_size is None + if max_size: + try: + content_length = int(stream.headers["content-length"]) + allow_download = content_length <= max_size + except TypeError: + pass + if allow_download: + file = ContentFile(await stream.aread(), name=url) + return file, stream.headers["content-type"] + + return None, None diff --git a/core/models/config.py b/core/models/config.py index 8f5dc31..9670c11 100644 --- a/core/models/config.py +++ b/core/models/config.py @@ -224,6 +224,8 @@ class Config(models.Model): hashtag_unreviewed_are_public: bool = True hashtag_stats_max_age: int = 60 * 60 + emoji_unreviewed_are_public: bool = False + cache_timeout_page_default: int = 60 cache_timeout_page_timeline: int = 60 * 3 cache_timeout_page_post: int = 60 * 2 diff --git a/core/uploads.py b/core/uploads.py index 41b6e94..f6c0e89 100644 --- a/core/uploads.py +++ b/core/uploads.py @@ -1,10 +1,14 @@ import os import secrets +from typing import TYPE_CHECKING from django.utils import timezone from storages.backends.gcloud import GoogleCloudStorage from storages.backends.s3boto3 import S3Boto3Storage +if TYPE_CHECKING: + from activities.models import Emoji + def upload_namer(prefix, instance, filename): """ @@ -16,6 +20,18 @@ def upload_namer(prefix, instance, filename): return f"{prefix}/{now.year}/{now.month}/{now.day}/{new_filename}{old_extension}" +def upload_emoji_namer(prefix, instance: "Emoji", filename): + """ + Names uploaded emoji per domain + """ + _, old_extension = os.path.splitext(filename) + if instance.domain is None: + domain = "_default" + else: + domain = instance.domain.domain + return f"{prefix}/{domain}/{instance.shortcode}{old_extension}" + + class TakaheS3Storage(S3Boto3Storage): """ Custom override backend that makes webp files store correctly |