combo/combo/utils/misc.py

54 lines
1.9 KiB
Python

# combo - content management system
# Copyright (C) 2015-2018 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.utils.six.moves.html_parser import HTMLParser
from django.utils.six.moves.urllib import parse as urlparse
from django.conf import settings
from django.template.context import BaseContext
from django.utils.html import strip_tags
def ellipsize(text, length=50):
text = HTMLParser().unescape(strip_tags(text))
if len(text) < length:
return text
return text[:(length-10)] + '...'
def flatten_context(context):
# flatten a context to a dictionary, with full support for embedded Context
# objects.
flat_context = {}
if isinstance(context, BaseContext):
for ctx in context.dicts:
flat_context.update(flatten_context(ctx))
else:
flat_context.update(context)
return flat_context
def is_url_from_known_service(url):
netloc = urlparse.urlparse(url).netloc
if not netloc:
return True
for service_id in settings.KNOWN_SERVICES or {}:
for service_key in settings.KNOWN_SERVICES[service_id]:
service = settings.KNOWN_SERVICES[service_id][service_key]
if urlparse.urlparse(service.get('url')).netloc == netloc:
return True
return False