1
|
|
|
import hashlib |
2
|
|
|
import threading |
3
|
|
|
from os import path, name, stat |
4
|
|
|
from stat import S_ISDIR,ST_MODE |
5
|
|
|
from django import template |
6
|
|
|
|
7
|
|
|
from chat.settings import STATIC_URL, STATIC_ROOT, logging, DEBUG |
8
|
|
|
|
9
|
|
|
register = template.Library() |
10
|
|
|
logger = logging.getLogger(__name__) |
11
|
|
|
|
12
|
|
|
md5_cache = {} |
13
|
|
|
|
14
|
|
|
|
15
|
|
|
@register.simple_tag |
16
|
|
|
def md5url(file_name): |
17
|
|
|
value = md5_cache.get(file_name) |
18
|
|
|
if value is None or DEBUG: |
19
|
|
|
value = calculate_url(file_name) |
20
|
|
|
return value |
21
|
|
|
|
22
|
|
|
|
23
|
|
|
def calculate_url(file_name): |
24
|
|
|
entry_name = file_name |
25
|
|
|
file_path = None |
26
|
|
|
try: |
27
|
|
|
key = '#root#' |
28
|
|
|
if key in file_name: |
29
|
|
|
file_name = file_name.split(key, 1)[1] |
30
|
|
|
file_path = path.join(STATIC_ROOT, entry_name.replace(key, '')) |
31
|
|
|
prefix = '' |
32
|
|
|
else: |
33
|
|
|
file_path = path.join(STATIC_ROOT, file_name) |
34
|
|
|
prefix = STATIC_URL |
35
|
|
|
|
36
|
|
|
md5 = calculate_file_md5(path.join(STATIC_ROOT, file_path))[:8] |
37
|
|
|
value = '%s%s?v=%s' % (prefix, file_name, md5) |
38
|
|
|
logger.info("Caching url '%s' for file '%s'", value, file_name) |
39
|
|
|
except Exception as e: |
40
|
|
|
mode = stat(file_path)[ST_MODE] |
41
|
|
|
if file_path and S_ISDIR(mode): |
42
|
|
|
value = STATIC_URL + file_name |
43
|
|
|
logger.warning("Caching url '%s' for directory %s", value, file_name) |
44
|
|
|
else: |
45
|
|
|
raise Exception('Unable to calculate md5 for {} because {}', file_name, e) |
46
|
|
|
md5_cache[entry_name] = value |
47
|
|
|
return value |
48
|
|
|
|
49
|
|
|
|
50
|
|
|
def calculate_file_md5(file_path): |
51
|
|
|
with open(file_path, 'rb') as fh: |
52
|
|
|
m = hashlib.md5() |
53
|
|
|
while True: |
54
|
|
|
data = fh.read(8192) |
55
|
|
|
if not data: |
56
|
|
|
break |
57
|
|
|
m.update(data) |
58
|
|
|
return m.hexdigest() |
59
|
|
|
|