2022-12-12 14:22:11 +00:00
|
|
|
from urllib.parse import urljoin
|
|
|
|
|
|
|
|
from django.conf import settings
|
2022-12-15 07:35:04 +00:00
|
|
|
from django.contrib.staticfiles.storage import staticfiles_storage
|
2022-12-12 14:22:11 +00:00
|
|
|
|
|
|
|
|
|
|
|
class RelativeAbsoluteUrl:
|
|
|
|
"""
|
|
|
|
Represents a URL that can have both "relative" and "absolute" forms
|
|
|
|
for various use either locally or remotely.
|
|
|
|
"""
|
|
|
|
|
|
|
|
absolute: str
|
|
|
|
relative: str
|
|
|
|
|
|
|
|
def __init__(self, absolute: str, relative: str | None = None):
|
|
|
|
if "://" not in absolute:
|
|
|
|
raise ValueError(f"Absolute URL {absolute!r} is not absolute!")
|
|
|
|
self.absolute = absolute
|
|
|
|
self.relative = relative or absolute
|
|
|
|
|
|
|
|
|
|
|
|
class AutoAbsoluteUrl(RelativeAbsoluteUrl):
|
|
|
|
"""
|
|
|
|
Automatically makes the absolute variant by using either settings.MAIN_DOMAIN
|
|
|
|
or a passed identity's URI domain.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, relative: str, identity=None):
|
|
|
|
self.relative = relative
|
|
|
|
if identity:
|
|
|
|
absolute_prefix = f"https://{identity.domain.uri_domain}/"
|
|
|
|
else:
|
|
|
|
absolute_prefix = f"https://{settings.MAIN_DOMAIN}/"
|
|
|
|
self.absolute = urljoin(absolute_prefix, self.relative)
|
2022-12-12 14:32:35 +00:00
|
|
|
|
|
|
|
|
|
|
|
class StaticAbsoluteUrl(RelativeAbsoluteUrl):
|
|
|
|
"""
|
|
|
|
Creates static URLs given only the static-relative path
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, path: str):
|
2022-12-15 07:35:04 +00:00
|
|
|
static_url = staticfiles_storage.url(path)
|
2022-12-12 14:32:35 +00:00
|
|
|
if "://" in static_url:
|
|
|
|
super().__init__(static_url)
|
|
|
|
else:
|
|
|
|
super().__init__(
|
|
|
|
urljoin(f"https://{settings.MAIN_DOMAIN}/", static_url), static_url
|
|
|
|
)
|