##// END OF EJS Templates
Removed old websocket related code (since websockets are no longer supported
neko259 -
r1948:be2714ff default
parent child Browse files
Show More
@@ -1,161 +1,145 b''
1 1 """
2 2 This module contains helper functions and helper classes.
3 3 """
4 import hashlib
4 import time
5 5 import uuid
6 6
7 from boards.abstracts.constants import FILE_DIRECTORY
8 from random import random
9 import time
7 import hashlib
10 8 import hmac
11
9 import magic
10 import os
11 from django import forms
12 12 from django.core.cache import cache
13 13 from django.db.models import Model
14 from django import forms
15 14 from django.template.defaultfilters import filesizeformat
16 15 from django.utils import timezone
17 16 from django.utils.translation import ugettext_lazy as _
18 import magic
19 import os
20 17
21 18 import boards
19 from boards.abstracts.constants import FILE_DIRECTORY
22 20 from boards.settings import get_bool
23 21 from neboard import settings
24 22
25 23 CACHE_KEY_DELIMITER = '_'
26 24
27 25 HTTP_FORWARDED = 'HTTP_X_FORWARDED_FOR'
28 26 META_REMOTE_ADDR = 'REMOTE_ADDR'
29 27
30 28 SETTING_MESSAGES = 'Messages'
31 29 SETTING_ANON_MODE = 'AnonymousMode'
32 30
33 31 ANON_IP = '127.0.0.1'
34 32
35 33 FILE_EXTENSION_DELIMITER = '.'
36 34
37 35
38 36 def is_anonymous_mode():
39 37 return get_bool(SETTING_MESSAGES, SETTING_ANON_MODE)
40 38
41 39
42 40 def get_client_ip(request):
43 41 if is_anonymous_mode():
44 42 ip = ANON_IP
45 43 else:
46 44 x_forwarded_for = request.META.get(HTTP_FORWARDED)
47 45 if x_forwarded_for:
48 46 ip = x_forwarded_for.split(',')[-1].strip()
49 47 else:
50 48 ip = request.META.get(META_REMOTE_ADDR)
51 49 return ip
52 50
53 51
54 52 # TODO The output format is not epoch because it includes microseconds
55 53 def datetime_to_epoch(datetime):
56 54 return int(time.mktime(timezone.localtime(
57 55 datetime,timezone.get_current_timezone()).timetuple())
58 56 * 1000000 + datetime.microsecond)
59 57
60 58
61 def get_websocket_token(user_id='', timestamp=''):
62 """
63 Create token to validate information provided by new connection.
64 """
65
66 sign = hmac.new(settings.CENTRIFUGE_PROJECT_SECRET.encode())
67 sign.update(settings.CENTRIFUGE_PROJECT_ID.encode())
68 sign.update(user_id.encode())
69 sign.update(timestamp.encode())
70 token = sign.hexdigest()
71
72 return token
73
74
75 59 # TODO Test this carefully
76 60 def cached_result(key_method=None):
77 61 """
78 62 Caches method result in the Django's cache system, persisted by object name,
79 63 object name, model id if object is a Django model, args and kwargs if any.
80 64 """
81 65 def _cached_result(function):
82 66 def inner_func(obj, *args, **kwargs):
83 67 cache_key_params = [obj.__class__.__name__, function.__name__]
84 68
85 69 cache_key_params += args
86 70 for key, value in kwargs:
87 71 cache_key_params.append(key + ':' + value)
88 72
89 73 if isinstance(obj, Model):
90 74 cache_key_params.append(str(obj.id))
91 75
92 76 if key_method is not None:
93 77 cache_key_params += [str(arg) for arg in key_method(obj)]
94 78
95 79 cache_key = CACHE_KEY_DELIMITER.join(cache_key_params)
96 80
97 81 persisted_result = cache.get(cache_key)
98 82 if persisted_result is not None:
99 83 result = persisted_result
100 84 else:
101 85 result = function(obj, *args, **kwargs)
102 86 if result is not None:
103 87 cache.set(cache_key, result)
104 88
105 89 return result
106 90
107 91 return inner_func
108 92 return _cached_result
109 93
110 94
111 95 def get_file_hash(file) -> str:
112 96 md5 = hashlib.md5()
113 97 for chunk in file.chunks():
114 98 md5.update(chunk)
115 99 return md5.hexdigest()
116 100
117 101
118 102 def validate_file_size(size: int):
119 103 max_size = boards.settings.get_int('Forms', 'MaxFileSize')
120 if max_size > 0 and size > max_size:
104 if 0 < max_size < size:
121 105 raise forms.ValidationError(
122 106 _('File must be less than %s but is %s.')
123 107 % (filesizeformat(max_size), filesizeformat(size)))
124 108
125 109
126 110 def get_extension(filename):
127 111 return filename.split(FILE_EXTENSION_DELIMITER)[-1:][0]
128 112
129 113
130 114 def get_upload_filename(model_instance, old_filename):
131 115 extension = get_extension(old_filename)
132 116 new_name = '{}.{}'.format(uuid.uuid4(), extension)
133 117
134 118 return os.path.join(FILE_DIRECTORY, new_name)
135 119
136 120
137 121 def get_file_mimetype(file) -> str:
138 122 buf = b''
139 123 for chunk in file.chunks():
140 124 buf += chunk
141 125
142 126 file_type = magic.from_buffer(buf, mime=True)
143 127 if file_type is None:
144 128 file_type = 'application/octet-stream'
145 129 elif type(file_type) == bytes:
146 130 file_type = file_type.decode()
147 131 return file_type
148 132
149 133
150 134 def get_domain(url: str) -> str:
151 135 """
152 136 Gets domain from an URL with random number of domain levels.
153 137 """
154 138 domain_parts = url.split('/')
155 139 if len(domain_parts) >= 2:
156 140 full_domain = domain_parts[2]
157 141 else:
158 142 full_domain = ''
159 143
160 144 return full_domain
161 145
General Comments 0
You need to be logged in to leave comments. Login now