2022-06-25 08:23:28 +02:00
|
|
|
import base64
|
2022-11-04 09:59:40 +01:00
|
|
|
import time
|
2022-06-25 08:23:28 +02:00
|
|
|
|
|
|
|
from app.config import BASE_URL
|
2022-11-04 09:59:40 +01:00
|
|
|
from app.config import hmac_sha256
|
2022-06-25 08:23:28 +02:00
|
|
|
|
|
|
|
SUPPORTED_RESIZE = [50, 740]
|
2022-11-04 09:59:40 +01:00
|
|
|
EXPIRY_PERIOD = 86400
|
|
|
|
EXPIRY_LENGTH = 7
|
|
|
|
|
|
|
|
|
|
|
|
class InvalidProxySignatureError(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def proxied_media_sig(expires: int, url: str) -> str:
|
|
|
|
hm = hmac_sha256()
|
2022-11-06 16:57:04 +01:00
|
|
|
hm.update(f"{expires}".encode())
|
|
|
|
hm.update(b"|")
|
2022-11-04 09:59:40 +01:00
|
|
|
hm.update(url.encode())
|
|
|
|
return base64.urlsafe_b64encode(hm.digest()).decode()
|
|
|
|
|
|
|
|
|
|
|
|
def verify_proxied_media_sig(expires: int, url: str, sig: str) -> None:
|
|
|
|
now = int(time.time() / EXPIRY_PERIOD)
|
|
|
|
expected = proxied_media_sig(expires, url)
|
|
|
|
if now > expires or sig != expected:
|
|
|
|
raise InvalidProxySignatureError("invalid or expired media")
|
2022-06-25 08:23:28 +02:00
|
|
|
|
|
|
|
|
|
|
|
def proxied_media_url(url: str) -> str:
|
|
|
|
if url.startswith(BASE_URL):
|
|
|
|
return url
|
2022-11-04 09:59:40 +01:00
|
|
|
expires = int(time.time() / EXPIRY_PERIOD) + EXPIRY_LENGTH
|
|
|
|
sig = proxied_media_sig(expires, url)
|
2022-06-25 08:23:28 +02:00
|
|
|
|
2022-11-06 16:57:04 +01:00
|
|
|
return (
|
|
|
|
BASE_URL
|
|
|
|
+ f"/proxy/media/{expires}/{sig}/"
|
|
|
|
+ base64.urlsafe_b64encode(url.encode()).decode()
|
|
|
|
)
|
2022-06-25 08:23:28 +02:00
|
|
|
|
|
|
|
|
|
|
|
def resized_media_url(url: str, size: int) -> str:
|
|
|
|
if size not in SUPPORTED_RESIZE:
|
|
|
|
raise ValueError(f"Unsupported resize {size}")
|
|
|
|
if url.startswith(BASE_URL):
|
|
|
|
return url
|
|
|
|
return proxied_media_url(url) + f"/{size}"
|