2016-04-28 05:40:58 +02:00
|
|
|
from django.conf import settings
|
2019-08-10 00:30:33 +02:00
|
|
|
import binascii
|
2016-04-28 05:40:58 +02:00
|
|
|
import hashlib
|
|
|
|
import hmac
|
|
|
|
|
2018-10-25 01:13:35 +02:00
|
|
|
def generate_camo_url(url: str) -> str:
|
|
|
|
encoded_url = url.encode("utf-8")
|
|
|
|
encoded_camo_key = settings.CAMO_KEY.encode("utf-8")
|
|
|
|
digest = hmac.new(encoded_camo_key, encoded_url, hashlib.sha1).hexdigest()
|
2019-08-10 00:30:33 +02:00
|
|
|
hex_encoded_url = binascii.b2a_hex(encoded_url)
|
2018-10-25 01:13:35 +02:00
|
|
|
return "%s/%s" % (digest, hex_encoded_url.decode("utf-8"))
|
|
|
|
|
2016-04-28 05:40:58 +02:00
|
|
|
# Encodes the provided URL using the same algorithm used by the camo
|
|
|
|
# caching https image proxy
|
2018-05-10 19:13:36 +02:00
|
|
|
def get_camo_url(url: str) -> str:
|
2016-04-28 05:40:58 +02:00
|
|
|
# Only encode the url if Camo is enabled
|
|
|
|
if settings.CAMO_URI == '':
|
|
|
|
return url
|
2018-10-25 01:13:35 +02:00
|
|
|
return "%s%s" % (settings.CAMO_URI, generate_camo_url(url))
|
2018-12-17 17:27:05 +01:00
|
|
|
|
|
|
|
def is_camo_url_valid(digest: str, url: str) -> bool:
|
|
|
|
camo_url = generate_camo_url(url)
|
|
|
|
camo_url_digest = camo_url.split('/')[0]
|
|
|
|
return camo_url_digest == digest
|