NDOJ/judge/utils/camo.py

54 lines
1.6 KiB
Python
Raw Permalink Normal View History

2020-01-21 06:35:58 +00:00
import hmac
from hashlib import sha1
from django.conf import settings
from judge.utils.unicode import utf8bytes
class CamoClient(object):
"""Based on https://github.com/sionide21/camo-client"""
def __init__(self, server, key, excluded=(), https=False):
2022-05-14 17:57:27 +00:00
self.server = server.rstrip("/")
2020-01-21 06:35:58 +00:00
self.key = key
self.https = https
self.excluded = excluded
def image_url(self, url):
2022-05-14 17:57:27 +00:00
return "%s/%s/%s" % (
self.server,
hmac.new(utf8bytes(self.key), utf8bytes(url), sha1).hexdigest(),
utf8bytes(url).hex(),
)
2020-01-21 06:35:58 +00:00
def rewrite_url(self, url):
if url.startswith(self.server) or url.startswith(self.excluded):
return url
2022-05-14 17:57:27 +00:00
elif url.startswith(("http://", "https://")):
2020-01-21 06:35:58 +00:00
return self.image_url(url)
2022-05-14 17:57:27 +00:00
elif url.startswith("//"):
return self.rewrite_url(("https:" if self.https else "http:") + url)
2020-01-21 06:35:58 +00:00
else:
return url
def update_tree(self, doc):
2022-05-14 17:57:27 +00:00
for img in doc.xpath(".//img"):
for attr in ("src", "data-src"):
2020-01-21 06:35:58 +00:00
if img.get(attr):
img.set(attr, self.rewrite_url(img.get(attr)))
2022-05-14 17:57:27 +00:00
for obj in doc.xpath(".//object"):
if obj.get("data"):
obj.set("data", self.rewrite_url(obj.get("data")))
2020-01-21 06:35:58 +00:00
if settings.DMOJ_CAMO_URL and settings.DMOJ_CAMO_KEY:
2022-05-14 17:57:27 +00:00
client = CamoClient(
settings.DMOJ_CAMO_URL,
key=settings.DMOJ_CAMO_KEY,
excluded=settings.DMOJ_CAMO_EXCLUDE,
https=settings.DMOJ_CAMO_HTTPS,
)
2020-01-21 06:35:58 +00:00
else:
client = None