-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcamo.py
More file actions
53 lines (42 loc) · 1.43 KB
/
camo.py
File metadata and controls
53 lines (42 loc) · 1.43 KB
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
51
52
53
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):
return self.server + Image(url, self.key).path
def _rewrite_url(self, url):
if url.startswith(self.server):
return url
elif not any(map(url.startswith, ["http://", "https://"])):
return url
else:
return self.image_url(url)
def _rewrite_image_urls(self, node):
for img in node.xpath('.//img'):
if img.get('src'):
img.set('src', self._rewrite_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 ''.join(map(html.tostring, doc)) or string
class Image(object):
def __init__(self, url, key):
self.url = url
self.key = key
@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.encode("hex")