102 lines
2.8 KiB
Python
102 lines
2.8 KiB
Python
# combo - content management system
|
|
# Copyright (C) 2017-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/>.
|
|
|
|
import os
|
|
|
|
from django import template
|
|
from django.db.models.fields.files import ImageFieldFile
|
|
from django.utils import six
|
|
from sorl.thumbnail.shortcuts import get_thumbnail
|
|
|
|
from ..models import Asset
|
|
|
|
register = template.Library()
|
|
|
|
|
|
@register.simple_tag
|
|
def asset_url(*args, **kwargs):
|
|
asset = None
|
|
for asset_object in args:
|
|
if isinstance(asset_object, ImageFieldFile):
|
|
try:
|
|
asset_object.url
|
|
except ValueError: # no associated file
|
|
continue
|
|
asset = asset_object
|
|
break
|
|
|
|
if isinstance(asset_object, six.string_types):
|
|
try:
|
|
asset = Asset.objects.get(key=asset_object).asset
|
|
break
|
|
except Asset.DoesNotExist:
|
|
continue
|
|
|
|
if isinstance(asset_object, Asset):
|
|
asset = asset_object.asset
|
|
break
|
|
|
|
if not asset:
|
|
return ''
|
|
|
|
if not os.path.exists(asset.path):
|
|
return asset.url
|
|
|
|
geometry_string = kwargs.pop('size', None)
|
|
if not geometry_string or asset.name.endswith('svg'):
|
|
return asset.url
|
|
|
|
return get_thumbnail(asset, geometry_string, **kwargs).url
|
|
|
|
|
|
@register.simple_tag
|
|
def asset_css_url(*args, **kwargs):
|
|
url = asset_url(*args, **kwargs)
|
|
if url:
|
|
return 'url(%s)' % url
|
|
else:
|
|
return 'none'
|
|
|
|
|
|
@register.simple_tag(takes_context=True)
|
|
def get_asset(context, *args, **kwargs):
|
|
if context.get('traverse_cells'):
|
|
# assets are not required when we are just searching for page placeholders
|
|
return None
|
|
|
|
key = None
|
|
if 'cell' in kwargs and 'type' in kwargs:
|
|
cell = kwargs['cell']
|
|
cell_type = kwargs['type']
|
|
try:
|
|
if not cell.can_have_assets():
|
|
return None
|
|
key = cell.get_asset_slot_key(cell_type)
|
|
except AttributeError:
|
|
return None
|
|
if hasattr(cell, '_assets'):
|
|
return cell._assets.get(key)
|
|
elif len(args) == 1:
|
|
key = args[0]
|
|
|
|
if not key:
|
|
return None
|
|
|
|
try:
|
|
return Asset.objects.get(key=key)
|
|
except Asset.DoesNotExist:
|
|
return None
|