# HG changeset patch # User neko259 # Date 2016-12-30 20:08:29 # Node ID 1342675d11e8ad3704795be4cf7b70b7ec85b61b # Parent 11a13b7c4f0aba5a27baf2e06acc187fe6f22459 Search for image for every domain level starting from the lowest one. Cache this into memcached diff --git a/boards/models/attachment/viewers.py b/boards/models/attachment/viewers.py --- a/boards/models/attachment/viewers.py +++ b/boards/models/attachment/viewers.py @@ -5,7 +5,7 @@ from django.contrib.staticfiles.template from django.core.files.images import get_image_dimensions from django.template.defaultfilters import filesizeformat -from boards.utils import get_domain +from boards.utils import get_domain, cached_result FILE_STUB_IMAGE = 'images/file.png' @@ -179,11 +179,7 @@ class UrlViewer(AbstractViewer): if protocol in URL_PROTOCOLS: url_image_name = URL_PROTOCOLS.get(protocol) elif domain: - filename = 'images/domains/{}.png'.format(domain) - if file_exists(filename): - url_image_name = 'domains/' + domain - else: - url_image_name = FILE_STUB_URL + url_image_name = self._find_image_for_domains(domain) or FILE_STUB_URL else: url_image_name = FILE_STUB_URL @@ -195,7 +191,20 @@ class UrlViewer(AbstractViewer): '' \ ''.format(self.url, image, w, h) + @cached_result() + def _find_image_for_domains(self, domain): + """ + Searches for the domain image for every domain level except top. + E.g. for l3.example.co.uk it will search for l3.example.co.uk, then + example.co.uk, then co.uk + """ + levels = domain.split('.') + while len(levels) > 1: + domain = '.'.join(levels) - def _get_protocol(self): - pass + filename = 'images/domains/{}.png'.format(domain) + if file_exists(filename): + return 'domains/' + domain + else: + del levels[0] diff --git a/boards/utils.py b/boards/utils.py --- a/boards/utils.py +++ b/boards/utils.py @@ -34,10 +34,6 @@ ANON_IP = '127.0.0.1' FILE_EXTENSION_DELIMITER = '.' -KNOWN_DOMAINS = ( - 'org.ru', -) - def is_anonymous_mode(): return get_bool(SETTING_MESSAGES, SETTING_ANON_MODE) @@ -157,21 +153,5 @@ def get_domain(url: str) -> str: else: full_domain = '' - result = full_domain - if full_domain: - levels = full_domain.split('.') - if len(levels) >= 2: - top = levels[-1] - second = levels[-2] + return full_domain - has_third_level = len(levels) > 2 - if has_third_level: - third = levels[-3] - - if has_third_level and ('{}.{}'.format(second, top) in KNOWN_DOMAINS): - result = '{}.{}.{}'.format(third, second, top) - else: - result = '{}.{}'.format(second, top) - - return result -