summaryrefslogtreecommitdiffstats
path: root/combo/apps/assets/views.py
blob: b261672252006cba08e17e83bb5421a1c5cfc2d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# 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 tarfile
import os

from django.conf import settings
from django.contrib import messages
from django.core.exceptions import PermissionDenied
from django.core.files.storage import default_storage
from django.core.urlresolvers import reverse, reverse_lazy
from django.http import Http404, HttpResponse
from django.shortcuts import redirect
from django.utils.six import BytesIO
from django.utils.translation import ugettext_lazy as _
from django.views.generic import TemplateView, ListView, FormView

import ckeditor
from sorl.thumbnail.shortcuts import get_thumbnail

from combo.data.models import CellBase

from .forms import AssetUploadForm, AssetsImportForm
from .models import Asset


class CkEditorAsset(object):
    def __init__(self, filepath):
        self.filepath = filepath
        self.name = os.path.basename(filepath)
        self.src = ckeditor.utils.get_media_url(filepath)

    @classmethod
    def get_assets(cls, request):
        return [cls(x) for x in ckeditor.views.get_image_files(request.user)]

    def css_classes(self):
        extension = os.path.splitext(self.filepath)[-1].strip('.')
        if extension:
            return 'asset-ext-%s' % extension
        return ''

    def size(self):
        return os.stat(default_storage.path(self.filepath)).st_size

    def thumb(self):
        if getattr(settings, 'CKEDITOR_IMAGE_BACKEND', None):
            thumb = ckeditor.utils.get_media_url(
                    ckeditor.utils.get_thumb_filename(self.filepath))
        else:
            thumb = self.src
        return thumb

    def is_image(self):
        return ckeditor.views.is_image(self.src)


class SlotAsset(object):
    def __init__(self, key=None, name=None, asset_type='image', asset=None):
        self.key = key
        self.name = name
        self.asset_type = asset_type
        self.asset = asset

    def is_image(self):
        return self.asset_type == 'image' and bool(self.asset)

    def size(self):
        if self.asset:
            try:
                return os.stat(self.asset.asset.path).st_size
            except OSError:
                pass
        return None

    def src(self):
        return self.asset.asset.url if self.asset else ''

    def thumb(self):
        if self.asset.asset.path.lower().endswith('.svg'):
            return self.asset.asset.url
        else:
            return get_thumbnail(self.asset.asset, '75x75').url

    @classmethod
    def get_assets(cls):
        assets = dict([(x.key, x) for x in Asset.objects.all()])
        uniq_slots = {}
        uniq_slots.update(settings.COMBO_ASSET_SLOTS)
        for cell in CellBase.get_cells(
                cell_filter=lambda x: bool(x.get_asset_slots)):
            uniq_slots.update(cell.get_asset_slots())
        for key, value in uniq_slots.items():
            yield cls(key,
                      name=value.get('label'),
                      asset_type=value.get('asset-type', 'image'),
                      asset=assets.get(key))


class Assets(ListView):
    template_name = 'combo/manager_assets.html'
    paginate_by = 10

    def get_queryset(self):
        files = list(SlotAsset.get_assets()) + CkEditorAsset.get_assets(self.request)
        q = self.request.GET.get('q')
        if q:
            files = [x for x in files if q.lower() in x.name.lower()]
        files.sort(key=lambda x: getattr(x, 'name'))
        return files

    def get_context_data(self, **kwargs):
        context = super(Assets, self).get_context_data(**kwargs)
        context['query'] = self.request.GET.get('q') or ''
        return context

    def get_anchored_url(self, key=None, name=None):
        url = reverse('combo-manager-assets')
        for i, asset in enumerate(self.get_queryset()):
            if key and key != getattr(asset, 'key', None):
                continue
            if name and name > getattr(asset, 'name', None):
                continue
            return url + '?page=%s' % ((i // self.paginate_by) + 1)
        return url

assets = Assets.as_view()


class AssetUpload(FormView):
    form_class = AssetUploadForm
    template_name = 'combo/manager_asset_upload.html'

    def form_valid(self, form):
        # use native ckeditor view so it's available from ckeditor file/image
        # dialogs.
        ckeditor_upload_view = ckeditor.views.ImageUploadView()
        self.request.GET = {'CKEditorFuncNum': '-'} # hack
        ckeditor_upload_view.post(self.request)
        return super(AssetUpload, self).form_valid(form)

    def get_success_url(self):
        return Assets(request=self.request).get_anchored_url(name=self.request.FILES['upload'].name)

asset_upload = AssetUpload.as_view()


class AssetOverwrite(FormView):
    form_class = AssetUploadForm
    template_name = 'combo/manager_asset_overwrite.html'
    success_url = reverse_lazy('combo-manager-assets')

    def form_valid(self, form):
        img_orig = self.request.GET['img']
        if '..' in img_orig:
            raise PermissionDenied() # better safe than sorry
        base_path = settings.CKEDITOR_UPLOAD_PATH
        if getattr(settings, 'CKEDITOR_RESTRICT_BY_USER', False):
            base_path = os.path.join(base_path, self.request.user.username)
        if not img_orig.startswith(base_path):
            raise PermissionDenied()

        upload = self.request.FILES['upload']

        # check that the new file and the original have the same extension
        ext_orig = os.path.splitext(img_orig)[1].lower()
        ext_upload = os.path.splitext(upload.name)[1].lower()
        if ext_orig != ext_upload:
            messages.error(
                self.request,
                _('You have to upload a file with the same extension (%(ext)s).')
                % {'ext': ext_orig})
            return super(AssetOverwrite, self).form_valid(form)

        default_storage.delete(img_orig)
        if getattr(settings, 'CKEDITOR_IMAGE_BACKEND', None):
            thumb = ckeditor.utils.get_thumb_filename(img_orig)
            default_storage.delete(thumb)
        saved_path = default_storage.save(img_orig, upload)
        backend = ckeditor.image_processing.get_backend()
        upload.seek(0) # rewind file to be sure
        try:
            backend.image_verify(upload)
        except ckeditor.utils.NotAnImageException:
            pass
        else:
            if backend.should_create_thumbnail(saved_path):
                backend.create_thumbnail(saved_path)
        return super(AssetOverwrite, self).form_valid(form)

    def get_success_url(self):
        img_orig = self.request.GET['img']
        return Assets(request=self.request).get_anchored_url(name=os.path.basename(img_orig))

asset_overwrite = AssetOverwrite.as_view()


class AssetDelete(TemplateView):
    template_name = 'combo/manager_asset_confirm_delete.html'

    def post(self, request):
        img_orig = request.GET['img']
        if '..' in img_orig:
            raise PermissionDenied() # better safe than sorry
        base_path = settings.CKEDITOR_UPLOAD_PATH
        if getattr(settings, 'CKEDITOR_RESTRICT_BY_USER', False):
            base_path = os.path.join(base_path, request.user.username)
        if not img_orig.startswith(base_path):
            raise PermissionDenied()
        default_storage.delete(img_orig)
        return redirect(
                Assets(request=self.request).get_anchored_url(
                    name=os.path.basename(img_orig)))

asset_delete = AssetDelete.as_view()


class SlotAssetUpload(FormView):
    form_class = AssetUploadForm
    template_name = 'combo/manager_asset_upload.html'
    success_url = reverse_lazy('combo-manager-assets')

    def form_valid(self, form):
        try:
            self.asset = Asset.objects.get(key=self.kwargs['key'])
        except Asset.DoesNotExist:
            self.asset = Asset(key=self.kwargs['key'])
        self.asset.asset = self.request.FILES['upload']
        self.asset.save()
        return super(SlotAssetUpload, self).form_valid(form)

    def get_success_url(self):
        return Assets(request=self.request).get_anchored_url(key=self.kwargs['key'])

slot_asset_upload = SlotAssetUpload.as_view()


class SlotAssetDelete(TemplateView):
    template_name = 'combo/manager_asset_confirm_delete.html'

    def post(self, request, *args, **kwargs):
        Asset.objects.filter(key=kwargs['key']).delete()
        return redirect(Assets(request=self.request).get_anchored_url(key=kwargs['key']))

slot_asset_delete = SlotAssetDelete.as_view()


class AssetsImport(FormView):
    form_class = AssetsImportForm
    template_name = 'combo/manager_assets_import.html'
    success_url = reverse_lazy('combo-manager-assets')

    def form_valid(self, form):
        overwrite = form.cleaned_data.get('overwrite')
        try:
            assets = tarfile.open(fileobj=form.cleaned_data['assets_file'])
        except tarfile.TarError:
            messages.error(self.request, _('The assets file is not valid.'))
            return super(AssetsImport, self).form_valid(form)
        media_prefix = default_storage.path('')
        for tarinfo in assets.getmembers():
            filepath = default_storage.path(tarinfo.name)
            if not overwrite and os.path.exists(filepath):
                continue
            assets.extract(tarinfo, path=media_prefix)
        messages.success(self.request, _('The assets file has been imported.'))
        return super(AssetsImport, self).form_valid(form)

assets_import = AssetsImport.as_view()


def assets_export(request, *args, **kwargs):
    fd = BytesIO()
    assets_file = tarfile.open('assets.tar', 'w', fileobj=fd)
    media_prefix = default_storage.path('')
    for basedir, dirnames, filenames in os.walk(media_prefix):
        for filename in filenames:
            assets_file.add(
                    os.path.join(basedir, filename),
                    os.path.join(basedir, filename)[len(media_prefix):])
    assets_file.close()
    return HttpResponse(fd.getvalue(), content_type='application/x-tar')


def serve_asset(request, key):
    try:
        asset = Asset.objects.get(key=key)
        return redirect(asset.asset.url)
    except (Asset.DoesNotExist, AttributeError):
        raise Http404()