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