From b8b491bbf2d488655f83263b7b3bb4096a72180a Mon Sep 17 00:00:00 2001 From: Joachim Date: Wed, 4 Aug 2021 16:55:12 +0200 Subject: [PATCH] Add get_absolute_url to ImageField --- bookwyrm/models/fields.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/bookwyrm/models/fields.py b/bookwyrm/models/fields.py index 3b369e84..e57374d5 100644 --- a/bookwyrm/models/fields.py +++ b/bookwyrm/models/fields.py @@ -3,6 +3,7 @@ from dataclasses import MISSING import imghdr import re from uuid import uuid4 +from urllib.parse import urljoin import dateutil.parser from dateutil.parser import ParserError @@ -13,11 +14,12 @@ from django.db import models from django.forms import ClearableFileInput, ImageField as DjangoImageField from django.utils import timezone from django.utils.translation import gettext_lazy as _ +from django.utils.encoding import filepath_to_uri from bookwyrm import activitypub from bookwyrm.connectors import get_image from bookwyrm.sanitize_html import InputHtmlParser -from bookwyrm.settings import DOMAIN +from bookwyrm.settings import MEDIA_FULL_URL def validate_remote_id(value): @@ -355,8 +357,6 @@ def image_serializer(value, alt): url = value.url else: return None - if not url[:4] == "http": - url = "https://{:s}{:s}".format(DOMAIN, url) return activitypub.Document(url=url, name=alt) @@ -423,6 +423,19 @@ class ImageField(ActivitypubFieldMixin, models.ImageField): } ) + def get_absolute_url(self, instance): + """returns an absolute URL for the image""" + value = getattr(instance, self.name) + if value is None: + return + + url = filepath_to_uri(value) + if url is not None: + url = url.lstrip('/') + url = urljoin(MEDIA_FULL_URL, url) + + return url + class DateTimeField(ActivitypubFieldMixin, models.DateTimeField): """activitypub-aware datetime field"""