forked from sionide21/camo-client
-
Notifications
You must be signed in to change notification settings - Fork 4
/
camo.py
50 lines (40 loc) · 1.39 KB
/
camo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import hashlib
import hmac
import re
from memoize import mproperty
from lxml import html
class CamoClient(object):
def __init__(self, server, key):
self.server = re.sub('/+$', '', server)
self.key = key
def image_url(self, url):
# skip images that have already been proxied and
# images with data URIs
if url.startswith(self.server):
return url
else:
return self.server + Image(url, self.key).path
def _rewrite_image_urls(self, node):
for img in node.xpath('.//img'):
if img.get('src'):
img.set('src', self.image_url(img.get('src')))
return node
def parse_html(self, string):
doc = html.fromstring(string.join(['<div>', '</div>']))
doc = self._rewrite_image_urls(doc)
# iterating over a node returns all the tags within that node
# ..if there are none, return the original string
return b''.join(map(html.tostring, doc)).decode() or string
class Image(object):
def __init__(self, url, key):
self.url = url.encode('utf-8')
self.key = key.encode('utf-8')
@mproperty
def path(self):
return "/%s/%s" % (self.digest, self.encoded_url)
@mproperty
def digest(self):
return hmac.new(self.key, self.url, hashlib.sha1).hexdigest()
@mproperty
def encoded_url(self):
return self.url.hex()