summaryrefslogtreecommitdiff
path: root/main/views.py
blob: 9de8f4b7ca125e7a9d8c20d4ce652c53863bef1a (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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2010  É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.

"""
Views of the project
"""

import datetime

from django.utils.translation import ugettext as _
from django.shortcuts import render_to_response
from django.template import loader
from django.http import HttpResponseRedirect, HttpResponse
from django.core import serializers

from chimere import settings
from chimere.main.actions import actions
from chimere.main.models import Category, SubCategory, PropertyModel, Marker, \
                                Route, News, Area, Color

from chimere.main.widgets import getMapJS, PointChooserWidget, \
                           RouteChooserWidget, URL_OSM_JS, URL_OSM_CSS
from chimere.main.forms import MarkerForm, RouteForm, ContactForm, \
                               notifySubmission, notifyStaff

def index(request):
    """
    Main page
    """
    subcategories = SubCategory.getAvailable()
    for cat, sub_cats in subcategories:
        for sub_category in sub_cats:
            if sub_category.id in settings.DEFAULT_CATEGORIES:
                sub_category.selected = True
                cat.selected= True
    extra = ""
    tab = " "*4
    for url in URL_OSM_CSS:
        extra += tab + '<link rel="stylesheet" href="%s" />' % url
    for url in URL_OSM_JS + ["%sbase.js" % settings.MEDIA_URL,
                             "%smain_map.js" % settings.MEDIA_URL,]:
        extra += tab + '<script src="%s"></script>\n' % url
    extra += tab + '<script src="/' + settings.EXTRA_URL + 'jsi18n/"></script>\n'
    # show the welcome page
    today = datetime.date.today().strftime('%y-%m-%d')
    display_welcome = None
    if not 'last_visit' in request.session or \
       request.session['last_visit'] != today:
        request.session['last_visit'] = today
        display_welcome = True
    response_dct = {'actions':actions, 'action_selected':('view',),
                    'error_message':'',
                    'sub_categories':subcategories,
                    'extra_head':extra + getMapJS(),
                    'media_path':settings.MEDIA_URL,
                    'extra_url':settings.EXTRA_URL,
                    'welcome':welcome(request, display_welcome),
                    'areas':Area.getAvailable(),
                    'map_layer':settings.MAP_LAYER
                    }
    # manage permalink
    if request.GET:
        for key in ('zoom', 'lon', 'lat', 'display_submited'):
            if key in request.GET and request.GET[key]:
                response_dct['p_'+key] = request.GET[key]
            else:
                response_dct['p_'+key] = '""'
        if 'checked_categories' in request.GET \
           and request.GET['checked_categories']:
            cats = request.GET['checked_categories'].split('_')
            response_dct['p_checked_categories'] = ",".join(cats)
        else:
            response_dct['p_checked_categories'] = '';
    return render_to_response('main_map.html', response_dct)

def edit(request):
    """
    Edition page
    """
    # If the form has been submited
    if request.method == 'POST':
        form = MarkerForm(request.POST, request.FILES)
        # All validation rules pass
        if form.is_valid():
            marker = form.save()
            # set the submited status
            marker.status = 'S'
            marker.save()
            notifySubmission(marker)
            return HttpResponseRedirect('/' + settings.EXTRA_URL +'submited/edit')
    else:
        # An unbound form
        form = MarkerForm()
    # get the « manualy » declared_fields. Ie: properties
    declared_fields = form.declared_fields.keys()
    response_dct = {'actions':actions, 'action_selected':('contribute', 'edit'),
                  'error_message':'',
                  'media_path':settings.MEDIA_URL,
                  'extra_url':settings.EXTRA_URL,
                  'map_layer':settings.MAP_LAYER,
                  'form':form,
                  'extra_head':form.media,
                  'sub_categories':SubCategory.getAvailable(['M', 'B']),
                  'point_widget':PointChooserWidget().render('point', None),
                  'properties':declared_fields
                   }
    # manualy populate the custom widget
    if 'subcategory' in form.data and form.data['subcategory']:
        response_dct['current_category'] = int(form.data['subcategory'])
    return render_to_response('edit.html', response_dct)

def editRoute(request):
    """
    Route edition page
    """
    # If the form has been submited
    if request.method == 'POST':
        form = RouteForm(request.POST, request.FILES)
        # All validation rules pass
        if form.is_valid():
            route = form.save()
            # set the submited status
            route.status = 'S'
            route.save()
            notifySubmission(route)
            return HttpResponseRedirect('/' + settings.EXTRA_URL + \
                                        'submited/edit_route')
    else:
        # An unbound form
        form = RouteForm()
    # get the « manualy » declared_fields. Ie: properties
    declared_fields = form.declared_fields.keys()
    response_dct = {'actions':actions,
                    'action_selected':('contribute', 'edit_route'),
                  'error_message':'',
                  'media_path':settings.MEDIA_URL,
                  'map_layer':settings.MAP_LAYER,
                  'form':form,
                  'extra_head':form.media,
                  'extra_url':settings.EXTRA_URL,
                  'sub_categories':SubCategory.getAvailable(['R', 'B']),
                  'route_widget':RouteChooserWidget().render('route', None),
                  'properties':declared_fields
                   }
    # manualy populate the custom widget
    if 'subcategory' in form.data and form.data['subcategory']:
        response_dct['current_category'] = int(form.data['subcategory'])
    return render_to_response('edit_route.html', response_dct)

def welcome(request, display=None):
    """
    Welcome string
    """
    response_dct = {'display':display}
    response_dct['news_lst'] = News.objects.filter(available=True)
    return loader.render_to_string('welcome.html', response_dct)

def submited(request, action):
    """
    Successful submission page
    """
    response_dct = {'actions':actions, 'action_selected':action,
                    'media_path':settings.MEDIA_URL,}
    return render_to_response('submited.html', response_dct)

def contactus(request):
    """
    Contact page
    """
    form = None
    msg = ''
    # If the form has been submited
    if request.method == 'POST':
        form = ContactForm(request.POST)
        # All validation rules pass
        if form.is_valid():
            response = notifyStaff(_(u"Comments/request on the map"),
                     form.cleaned_data['content'], form.cleaned_data['email'])
            if response:
                msg = _(u"Thank you for your contribution. It will be taken \
into account. If you have left your email you may be contacted soon for more \
details.")
            else:
                msg = _(u"Temporary error. Renew your message later.")
    else:
        form = ContactForm()
    response_dct = {'actions':actions, 'action_selected':('contact',),
             'media_path':settings.MEDIA_URL,'contact_form':form, 'message':msg}
    return render_to_response('contactus.html', response_dct)

def getDetail(request, marker_id):
    '''
    Get the detail for a marker
    '''
    try:
        marker = Marker.objects.filter(id=int(marker_id), status='A')[0]
    except (ValueError, IndexError):
        return HttpResponse('no results')
    response_dct= {'media_path':settings.MEDIA_URL, 'marker':marker}
    return render_to_response('detail.html', response_dct)

def getDescriptionDetail(request, category_id):
    '''
    Get the description for a category
    '''
    try:
        category = Category.objects.filter(id=int(category_id))[0]
    except (ValueError, IndexError):
        return HttpResponse('no results')
    response_dct= {'media_path':settings.MEDIA_URL, 'category':category}
    return render_to_response('category_detail.html', response_dct)

def getGeoObjects(request, category_ids, status='A'):
    '''
    Get the JSON for a route
    '''
    status = status.split('_')
    try:
        query = Route.objects.filter(status__in=status,
                                    subcategory__in=category_ids.split('_'))
    except:
        return HttpResponse('no results')
    query.order_by('subcategory')
    routes = list(query)
    jsons = []
    current_cat, colors, idx = None, None, 0
    for route in routes:
        if not current_cat or current_cat != route.subcategory:
            idx = 0
            current_cat = route.subcategory
            colors = list(Color.objects.filter(color_theme=\
                                                 route.subcategory.color_theme))
        jsons.append(route.getGeoJSON(color=colors[idx % len(colors)].code))
        idx += 1
    try:
        query = Marker.objects.filter(status__in=status,
                                    subcategory__in=category_ids.split('_'))
    except:
        return HttpResponse('no results')
    jsons += [geo_object.getGeoJSON() for geo_object in list(query)]
    if not jsons:
        return HttpResponse('no results')
    data = '{"type": "FeatureCollection", "features":[%s]}' % ",".join(jsons)
    return HttpResponse(data)