summaryrefslogtreecommitdiff
path: root/chimere/admin.py
blob: 03ed60dbbbd0dd92c15747217ed48bcb8298c306 (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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2016  Étienne Loks  <etienne.loks_AT_peacefrogsDOTnet>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# See the file COPYING for details.

"""
Settings for administration pages
"""

from copy import deepcopy

from django.conf import settings
from django.contrib import admin, messages
from django.contrib.admin import SimpleListFilter
from django.contrib.admin.utils import flatten_fieldsets
from django.contrib.auth.admin import UserAdmin as VanillaUserAdmin
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
try:
    from chimere import tasks
except ImportError:
    pass

from chimere.forms import MarkerAdminForm, RouteAdminForm, AreaAdminForm,\
    NewsAdminForm, CategoryAdminForm, ImporterAdminForm, OSMForm, \
    PageAdminForm, PictureFileAdminForm, MultimediaFileAdminForm, \
    PolygonAdminForm
from chimere import models
from chimere.models import Category, Icon, SubCategory, Marker, \
    PropertyModel, News, Route, Area, ColorTheme, Color, \
    MultimediaFile, PictureFile, Importer, Layer, AreaLayers,\
    PropertyModelChoice, Page, get_areas_for_user, Overlay, \
    ImporterKeyCategories, SubCategoryUserLimit, AreaOverlays
from chimere.utils import ShapefileManager, KMLManager, CSVManager


def disable(modeladmin, request, queryset):
    for item in queryset:
        item.status = 'D'
        item.save()
disable.short_description = _("Disable")


def validate(modeladmin, request, queryset):
    for item in queryset:
        item.status = 'A'
        item.save()
validate.short_description = _("Validate")


def export_to_kml(modeladmin, request, queryset):
    """
    Export data to KML
    """
    filename, result = KMLManager.export(queryset)
    response = HttpResponse(result,
                            mimetype='application/vnd.google-earth.kml+xml')
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    return response
export_to_kml.short_description = _("Export to KML")


def export_to_shapefile(modeladmin, request, queryset):
    """
    Export data to Shapefile
    """
    filename, zip_stream = ShapefileManager.export(queryset)
    # Stick it all in a django HttpResponse
    response = HttpResponse()
    response['Content-Disposition'] = 'attachment; filename=%s.zip' % filename
    response['Content-length'] = str(len(zip_stream))
    response['Content-Type'] = 'application/zip'
    response.write(zip_stream)
    return response
export_to_shapefile.short_description = _("Export to Shapefile")


def export_to_csv(modeladmin, request, queryset):
    """
    Export data to CSV
    """
    filename, result = CSVManager.export(queryset)
    response = HttpResponse(result, mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    return response
export_to_csv.short_description = _("Export to CSV")


def managed_modified(modeladmin, request, queryset):
    # not very clean... There is must be a better way to do that
    redirect_url = request.get_full_path().split('admin-')[0]
    if queryset.count() != 1 and len(set([i.ref_item or i
                                         for i in queryset.all()])) != 1:
        messages.error(request, _("Only one item can be managed at a "
                                  "time."))
        return HttpResponseRedirect(redirect_url)

    item = queryset.all()[0]
    if not item.ref_item or item.ref_item == item:
        try:
            item = modeladmin.model.objects.filter(ref_item=item)\
                                           .exclude(pk=item.pk).all()[0]
        except IndexError:
            messages.error(request, _("No modified item associated "
                                      "to the selected item."))
            return HttpResponseRedirect(redirect_url)
    item_ref = item.ref_item
    if request.POST.get('rapprochement'):
        couple = [(item, item_ref)]
        updated = dict(request.POST)
        # clean
        for k in ('action', 'rapprochement', 'index', '_selected_action'):
            if k in updated:
                updated.pop(k)
        for idx, cpl in enumerate(couple):
            it, it_ref = cpl
            updated_keys = list(updated.keys())
            if it.status == 'I':
                updated_keys.append('import_version')
            for k in updated_keys:
                if k != 'import_version' and not request.POST[k]:
                    continue
                if hasattr(it_ref, k):
                    c_value = getattr(it_ref, k)
                    if hasattr(c_value, 'select_related'):
                        c_value.clear()
                        for val in getattr(it, k).all():
                            c_value.add(val)
                    else:
                        setattr(it_ref, k, getattr(it, k))
                        it_ref.save()
                elif k.startswith('property_'):
                    try:
                        pm = PropertyModel.get(pk=int(k[len('property_'):]))
                        it_ref.setProperty(pm, it.getProperty(pm))
                    except (ValueError, ObjectDoesNotExist):
                        pass
        item.delete()
        messages.success(request, _("Modified item traited."))
        return HttpResponseRedirect(redirect_url)
    return render_to_response('admin/chimere/managed_modified.html',
                              {'item': item, 'item_ref': item_ref},
                              context_instance=RequestContext(request))
managed_modified.short_description = _("Managed modified items")


class CatLimitInline(admin.TabularInline):
    model = SubCategoryUserLimit
    extra = 5


class UserAdmin(VanillaUserAdmin):
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
    inlines = (CatLimitInline,)

admin.site.unregister(User)
admin.site.register(User, UserAdmin)


class PictureMarkerInline(admin.TabularInline):
    model = PictureFile
    extra = 1
    ordering = ('order',)
    form = PictureFileAdminForm
    readonly_fields = ('height', 'width')
    exclude = ('thumbnailfile', 'thumbnailfile_height', 'thumbnailfile_width',
               'polygon', 'route')


class MultimediaMarkerInline(admin.TabularInline):
    model = MultimediaFile
    extra = 1
    ordering = ('order',)
    form = MultimediaFileAdminForm
    exclude = ('polygon', 'route')


class AreaMarkerListFilter(admin.SimpleListFilter):
    title = _('area')
    parameter_name = 'area'

    def lookups(self, request, model_admin):
        return [(area.urn, area.name) for area in models.Area.objects.all()]

    def queryset(self, request, queryset):
        try:
            area = models.Area.objects.get(urn=self.value())
        except models.Area.DoesNotExist:
            return queryset
        return queryset.filter(area.getIncludeMarker())


class AreaRouteListFilter(AreaMarkerListFilter):
    def queryset(self, request, queryset):
        try:
            area = models.Area.objects.get(urn=self.value())
        except models.Area.DoesNotExist:
            return queryset
        return queryset.filter(area.getIncludeRoute())


class AreaPolygonListFilter(AreaMarkerListFilter):
    def queryset(self, request, queryset):
        try:
            area = models.Area.objects.get(urn=self.value())
        except models.Area.DoesNotExist:
            return queryset
        return queryset.filter(area.getIncludePolygon())


class HasCategoriesListFilter(SimpleListFilter):
    title = _('Has categories')
    parameter_name = 'has_category'

    def lookups(self, request, model_admin):
        return (
            ('true', _('Yes')),
            ('false', _('No')),
        )

    def queryset(self, request, queryset):
        if self.value() == 'false':
            return queryset.filter(categories__isnull=True)
        elif self.value() == 'true':
            return queryset.exclude(categories__isnull=True)
        return queryset


class CategoriesListFilter(SimpleListFilter):
    title = _('categories')
    parameter_name = 'category'

    def lookups(self, request, model_admin):
        if request.user.subcategory_limit_to.count():
            q = request.user.subcategory_limit_to
            return [(l.subcategory.pk, str(l.subcategory))
                    for l in q.all()]
        q = SubCategory.objects
        return [(cat.pk, str(cat)) for cat in q.all()]

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(categories__pk=self.value())
        return queryset


def moderator_right(user, qs, geo_type='marker'):
    if user.is_superuser:
        return qs
    areas = get_areas_for_user(user)
    if areas:
        contained = Q()
        for area in areas:
            if geo_type == 'marker':
                contained = contained | area.getIncludeMarker()
            elif geo_type == 'route':
                contained = contained | area.getIncludeRoute()
            elif geo_type == 'polygon':
                contained = contained | area.getIncludePolygon()
        qs = qs.filter(contained)
    if user.subcategory_limit_to.count():
        qs = qs.filter(categories__in=SubCategory.objects.filter(
            limited_for_user__user=user).all())
    return qs

MARKER_FIELDSETS = [
    [None, {
        'fields': ['point', 'name', 'status', 'categories', 'description',
                   'keywords', 'start_date', 'end_date']
    }],
    [_("Submitter"), {
        'classes': ('collapse',),
        'fields': ('submiter_name', 'submiter_email', 'submiter_comment')
    }],
    [_("Import"), {
        'classes': ('collapse',),
        'fields': ('not_for_osm', 'modified_since_import', 'import_source',
                   'origin', 'license')
    }],
    [_("Associated items"), {
        'classes': ('collapse',),
        'fields': ['ref_item', ]
    }]
]

ROUTE_FIELDSETS = deepcopy(MARKER_FIELDSETS)
ROUTE_FIELDSETS[0][1]['fields'][0] = 'route'
ROUTE_FIELDSETS[0][1]['fields'].pop(ROUTE_FIELDSETS[0][1]['fields'].index(
    'description'))
ROUTE_FIELDSETS[3][1]['fields'] = ('ref_item', 'associated_file',)
POLYGON_FIELDSETS = deepcopy(MARKER_FIELDSETS)
POLYGON_FIELDSETS[0][1]['fields'][0] = 'polygon'
POLYGON_FIELDSETS[0][1]['fields'].pop(POLYGON_FIELDSETS[0][1]['fields'].index(
    'description'))


class MarkerAdmin(admin.ModelAdmin):
    """
    Specialized the Point field.
    """
    search_fields = ("name",)
    list_display = ('name', 'status', 'start_date', 'end_date')
    list_filter = ('status', AreaMarkerListFilter, CategoriesListFilter,
                   HasCategoriesListFilter, 'start_date', 'end_date')
    actions = [validate, disable, managed_modified, export_to_kml,
               export_to_shapefile, export_to_csv]
    exclude = ['submiter_session_key', 'import_key', 'import_version',
               'available_date', 'ref_item']
    readonly_fields = [
        'submiter_email', 'submiter_comment', 'import_source',
        'submiter_name', 'ref_item', 'modified_since_import', ]
    form = MarkerAdminForm
    fieldsets = MARKER_FIELDSETS
    inlines = [MultimediaMarkerInline, PictureMarkerInline]
    has_properties = True
    geo_type = 'marker'

    def get_fieldsets(self, request, obj=None):
        """
        Manage properties in fieldsets.
        """
        fieldsets = super(MarkerAdmin, self).get_fieldsets(request, obj)
        newfieldsets = list(fieldsets)
        if self.has_properties:
            main_fields = newfieldsets[0][1]['fields']
            for pm in PropertyModel.objects.filter(available=True)\
                                           .order_by('order').all():
                pm_name = pm.getNamedId()
                if pm_name not in main_fields:
                    main_fields.append(pm_name)
        return newfieldsets

    def get_queryset(self, request):
        """
        Filter queryset with specific rights
        """
        qs = super().get_queryset(request)
        qs = moderator_right(request.user, qs, geo_type=self.geo_type)
        ordering = self.ordering or ()
        if ordering:
            qs = qs.order_by(*ordering)
        return qs.distinct()

    def admin_modification(self, request, item_id):
        """
        Redirect to the marker modification form
        """
        return managed_modified(
            self, request, Marker.objects.filter(pk=item_id))

    def get_urls(self):
        from django.conf.urls import patterns, url
        urls = super(MarkerAdmin, self).get_urls()
        model_name = self.model.__name__.lower()
        my_urls = patterns(
            '',
            url(r'^admin-{}-modification/(?P<item_id>\d+)/$'.format(model_name),
                self.admin_site.admin_view(self.admin_modification),
                name='admin-{}-modification'.format(model_name)),
        )
        return my_urls + urls

    def get_form(self, request, obj=None, **kwargs):
        # remove dynamic field to prevent admin check
        kwargs['fields'] = [
            field for field in flatten_fieldsets(
                self.get_fieldsets(request, obj))
            if not field.startswith("property_")]
        form = super(MarkerAdmin, self).get_form(request, obj, **kwargs)
        q = request.user.subcategory_limit_to
        if not q.count():
            return form
        form = type('MarkerAdminLimit', (form,),
                    {'categories_choices': [
                        (l.subcategory.pk, str(l.subcategory))
                        for l in q.all()]})
        return form


class PictureRouteInline(PictureMarkerInline):
    exclude = ('thumbnailfile', 'thumbnailfile_height', 'thumbnailfile_width',
               'polygon', 'marker')


class MultimediaRouteInline(MultimediaMarkerInline):
    exclude = ('polygon', 'marker')


class RouteAdmin(MarkerAdmin):
    """
    Specialized the Route field.
    """
    search_fields = ("name",)
    list_display = ('name', 'status')
    list_filter = ('status', AreaRouteListFilter, 'categories')
    exclude = ['height', 'width']
    form = RouteAdminForm
    readonly_fields = ('associated_file', 'ref_item')
    actions = [validate, disable, managed_modified, export_to_kml,
               export_to_shapefile, export_to_csv]
    fieldsets = ROUTE_FIELDSETS
    inlines = [MultimediaRouteInline, PictureRouteInline]
    has_properties = False
    geo_type = 'route'

    def queryset(self, request):
        qs = self.model._default_manager.get_query_set()
        qs = moderator_right(request.user, qs, geo_type='route')
        ordering = self.ordering or ()
        if ordering:
            qs = qs.order_by(*ordering)
        return qs

    def admin_modification(self, request, item_id):
        """
        Redirect to the route modification form
        """
        return managed_modified(self, request,
                                Route.objects.filter(pk=item_id))


class PicturePolygonInline(PictureMarkerInline):
    exclude = ('thumbnailfile', 'thumbnailfile_height', 'thumbnailfile_width',
               'route', 'marker')


class MultimediaPolygonInline(MultimediaMarkerInline):
    exclude = ('route', 'marker')


class PolygonAdmin(MarkerAdmin):
    """
    Specialized the Polygon field.
    """
    list_filter = ('status', AreaPolygonListFilter, 'categories')
    form = PolygonAdminForm
    actions = [validate, disable, managed_modified, export_to_kml,
               export_to_shapefile, export_to_csv]
    readonly_fields = [
        'submiter_email', 'submiter_comment', 'import_source',
        'submiter_name', 'ref_item', 'modified_since_import']
    exclude = ['submiter_session_key', 'import_key', 'import_version',
               'ref_item']
    inlines = [MultimediaPolygonInline, PicturePolygonInline]
    fieldsets = POLYGON_FIELDSETS
    geo_type = 'polygon'

    def admin_modification(self, request, item_id):
        """
        Redirect to the polygon modification form
        """
        return managed_modified(self, request,
                                models.Polygon.objects.filter(pk=item_id))


class LayerInline(admin.TabularInline):
    model = AreaLayers
    extra = 1


class OverlayInline(admin.TabularInline):
    model = AreaOverlays
    extra = 1


class AreaAdmin(admin.ModelAdmin):
    """
    Specialized the area field.
    """
    form = AreaAdminForm
    exclude = ['upper_left_corner', 'lower_right_corner']
    inlines = [LayerInline, OverlayInline]
    list_display = ['name', 'order', 'available', 'default']


def importing(modeladmin, request, queryset):
    for importer in queryset:
        importer.state = str(tasks.IMPORT_MESSAGES['import_pending'][0])
        importer.save()
        tasks.importing(importer.pk)
importing.short_description = _("Import")


def cancel_import(modeladmin, request, queryset):
    for importer in queryset:
        importer.state = tasks.IMPORT_MESSAGES['import_cancel'][0]
        importer.save()
cancel_import.short_description = _("Cancel import")


def cancel_export(modeladmin, request, queryset):
    for importer in queryset:
        importer.state = tasks.IMPORT_MESSAGES['export_cancel'][0]
        importer.save()
cancel_export.short_description = _("Cancel export")


def export_to_osm(modeladmin, request, queryset):
    if queryset.count() > 1:
        messages.error(request,
                       _("Can manage only one OSM export at a time."))
        return HttpResponseRedirect(request.get_full_path())
    importer = queryset.all()[0]
    if Marker.objects.filter(categories__in=importer.categories.all(),
                             status='I').count():
        messages.error(request, _("You must treat all item with the status "
                                  "\"imported\" before exporting to OSM."))
        return HttpResponseRedirect(request.get_full_path())
    if importer.importer_type != 'OSM':
        messages.error(request,
                       _("Only OSM importer are managed for export."))
        return HttpResponseRedirect(request.get_full_path())
    item_nb = Marker.objects.filter(
        status='A', categories=importer.categories.all(), not_for_osm=False,
        modified_since_import=True, route=None).count()
    if not item_nb:
        messages.error(request,
                       _("No point of interest are concerned by this "
                         "export."))
        return HttpResponseRedirect(request.get_full_path())
    form = None
    if request.method == 'POST' and (
       'email' in request.POST or 'api' in request.POST
       or 'password' in request.POST):
        form = OSMForm(request.POST)
        if form.is_valid():
            importer.state = str(
                tasks.IMPORT_MESSAGES['export_pending'][0])
            importer.save()
            tasks.exporting(importer.pk, form.cleaned_data)
            messages.success(request, _("Export launched."))
            return HttpResponseRedirect(request.get_full_path())
    else:
        form = OSMForm()
    msg_item = _("%s point(s) of interest concerned by this export before "
                 "bounding box filter.") % item_nb
    return render_to_response('admin/chimere/osm_export.html',
                              {'item': importer, 'form': form,
                               'msg_item': msg_item},
                              context_instance=RequestContext(request))
export_to_osm.short_description = _("Export to osm")


class ImporterKeyInline(admin.TabularInline):
    model = ImporterKeyCategories
    extra = 1


class ImporterAdmin(admin.ModelAdmin):
    form = ImporterAdminForm
    list_display = ('importer_type', 'display_categories', 'default_name',
                    'source', 'state', 'filtr')
    list_filter = ('importer_type', 'categories')
    readonly_fields = ('state',)
    actions = [importing, cancel_import, export_to_osm, cancel_export]
    inlines = [ImporterKeyInline]
admin.site.register(Importer, ImporterAdmin)


class PageAdmin(admin.ModelAdmin):
    """
    Use the TinyMCE widget for the page content
    """
    form = PageAdminForm


class NewsAdmin(admin.ModelAdmin):
    """
    Use the TinyMCE widget for the news content
    """
    form = NewsAdminForm


class SubcatInline(admin.TabularInline):
    model = SubCategory
    extra = 1


class CategoryAdmin(admin.ModelAdmin):
    """
    Use the TinyMCE widget for categories
    """
    form = CategoryAdminForm
    inlines = [SubcatInline]
    list_display = ['name', 'order']


class ColorInline(admin.TabularInline):
    model = Color


class ColorThemeAdmin(admin.ModelAdmin):
    inlines = [ColorInline]


class IconAdmin(admin.ModelAdmin):
    exclude = ['height', 'width']
    list_display = ['name']


class PropertyModelChoiceInline(admin.TabularInline):
    model = PropertyModelChoice
    extra = 1


class PropertyModelAdmin(admin.ModelAdmin):
    list_display = ('name', 'order', 'available')
    inlines = [PropertyModelChoiceInline]

# register of differents database fields
admin.site.register(Page, PageAdmin)
admin.site.register(News, NewsAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Icon, IconAdmin)
admin.site.register(Marker, MarkerAdmin)
admin.site.register(models.Route, RouteAdmin)
admin.site.register(models.Polygon, PolygonAdmin)
if not settings.CHIMERE_HIDE_PROPERTYMODEL:
    admin.site.register(PropertyModel, PropertyModelAdmin)
admin.site.register(Area, AreaAdmin)
admin.site.register(ColorTheme, ColorThemeAdmin)
admin.site.register(Layer)
admin.site.register(Overlay)