Réparé l'agenda
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / savoirs / views.py
1 # -*- encoding: utf-8 -*-
2 import copy
3 import datetime
4 import simplejson
5
6 from auf.django.references import models as ref
7 from django.shortcuts import render, get_object_or_404, redirect
8 from django.http import HttpResponse, Http404
9 from django.contrib.auth.decorators import login_required
10 from django.contrib.contenttypes.models import ContentType
11 from django.utils.safestring import mark_safe
12 from django.conf import settings
13
14 import backend_config
15 from chercheurs.forms import ChercheurSearch, ChercheurSearchEditForm
16 from lib.recherche import google_search, excerpt_function
17 from lib import sep
18 from savoirs.globals import configuration
19 from savoirs.forms import \
20 RessourceSearchForm, AppelSearchForm, ActualiteSearchForm, \
21 EvenementSearchForm, EvenementForm, RessourceSearchEditForm, \
22 ActualiteSearchEditForm, EvenementSearchEditForm, \
23 AppelSearchEditForm, SearchEditForm
24 from savoirs.models import \
25 Discipline, Region, Search, Record, PageStatique, HarvestLog, \
26 Actualite, Evenement, build_time_zone_choices, ActualiteSearch, \
27 RessourceSearch, EvenementSearch, AppelSearch
28 from sitotheque.forms import SiteSearch, SiteSearchEditForm
29
30
31 # Accueil
32 def index(request, discipline=None, region=None):
33 """Page d'accueil"""
34 discipline_obj = discipline and get_object_or_404(
35 Discipline, pk=discipline
36 )
37 region_obj = region and get_object_or_404(Region, pk=region)
38 search = Search(discipline=discipline_obj, region=region_obj)
39 results = search.run()
40 today = datetime.date.today()
41 return render(request, "savoirs/index.html", {
42 'actualites': results.actualites[0:4],
43 'appels': results.appels[0:4],
44 'evenements': results.evenements.filter_debut(min=today)
45 .order_by('debut')[0:4],
46 'ressources': results.ressources[0:4],
47 'chercheurs': results.chercheurs[0:10],
48 'sites': results.sites[0:4],
49 'caldav_url': configuration['calendrier_publique']
50 })
51
52
53 # sous-menu droite
54 def a_propos(request):
55 return render(request, "savoirs/a-propos.html")
56
57
58 def nous_contacter(request):
59 return render(request, "savoirs/contact.html", {
60 'courriel': settings.CONTACT_EMAIL
61 })
62
63
64 def legal(request):
65 return render(request, "savoirs/legal.html")
66
67
68 # recherche
69 def recherche(request, discipline=None, region=None):
70 query = request.GET.get("q", "")
71 if not query.strip():
72
73 # Si on n'a pas de recherche par mots-clés, on redirige vers
74 # l'accueil.
75 kwargs = {}
76 if discipline:
77 kwargs['discipline'] = discipline
78 if region:
79 kwargs['region'] = region
80 return redirect('savoirs.views.index', **kwargs)
81
82 # Effectuer la recherche
83 discipline_obj = discipline and \
84 get_object_or_404(Discipline, pk=discipline)
85 region_obj = region and get_object_or_404(Region, pk=region)
86 search = Search(q=query, discipline=discipline_obj, region=region_obj)
87 results = search.run()
88
89 # Bâtissons une query string pour les liens vers les briques
90 params = {}
91 if query:
92 params['q'] = query
93 if discipline:
94 params['discipline'] = unicode(discipline)
95 if region:
96 params['region'] = unicode(region)
97 if params:
98 briques_query_string = mark_safe(
99 '?' + '&'.join(k + '=' + v.replace('"', '"')
100 for (k, v) in params.iteritems())
101 )
102 else:
103 briques_query_string = None
104
105 excerpt = excerpt_function(Record.objects, query)
106
107 return render(request, "savoirs/recherche.html", {
108 'q': query,
109 'excerpt': excerpt,
110 'ressources': results.ressources[0:5],
111 'total_ressources': results.ressources.count(),
112 'evenements': results.evenements[0:5],
113 'total_evenements': results.evenements.count(),
114 'chercheurs': results.chercheurs[0:10],
115 'total_chercheurs': results.chercheurs.count(),
116 'groupes': results.groupes[0:10],
117 'total_groupes': results.groupes.count(),
118 'actualites': results.actualites[0:5],
119 'total_actualites': results.actualites.count(),
120 'appels': results.appels[0:5],
121 'total_appels': results.appels.count(),
122 'sites': results.sites[0:5],
123 'total_sites': results.sites.count(),
124 'sites_auf': results.sites_auf[0:5],
125 'briques_query_string': briques_query_string
126 })
127
128
129 def sites_auf(request):
130 q = request.GET.get('q')
131 page = int(request.GET.get('page', 0))
132 try:
133 data = google_search(page, q) if q else None
134 except:
135 data = None
136 return render(request, 'savoirs/sites_auf.html', {
137 'google_q': q,
138 'data': data,
139 'page': page,
140 })
141
142
143 # ressources
144 def ressource_index(request):
145 search_form = RessourceSearchForm(request.GET)
146 if search_form.is_valid():
147 search = search_form.save(commit=False)
148 else:
149 raise Http404
150 ressources = search.run()
151 nb_resultats = ressources.count()
152 excerpt = excerpt_function(Record.objects, search_form.cleaned_data['q'])
153 try:
154 p = PageStatique.objects.get(id='ressources')
155 entete = p.contenu
156 except PageStatique.DoesNotExist:
157 entete = '<h1>Ressources</h1>'
158
159 return render(request, "savoirs/ressource_index.html", {
160 'search_form': search_form,
161 'ressources': ressources,
162 'nb_resultats': nb_resultats,
163 'excerpt': excerpt,
164 'entete': entete,
165 })
166
167
168 def ressource_retrieve(request, id):
169 """Notice OAI de la ressource"""
170 ressource = get_object_or_404(Record, id=id)
171 return render(request, "savoirs/ressource_retrieve.html", {
172 'ressource': ressource,
173 'disciplines': ressource.disciplines.all(),
174 'regions': ressource.regions.all(),
175 })
176
177
178 def informations(request):
179 resources = copy.deepcopy(backend_config.RESOURCES)
180
181 logs = [
182 l
183 for l in HarvestLog.objects.filter(context='moisson').order_by('date')
184 if l.name in resources.keys()
185 ]
186 for l in logs:
187 resources[l.name]['logs'] = {'date': l.date, 'count': l.processed}
188
189 return render(request, "savoirs/informations.html", {
190 'r': resources,
191 })
192
193
194 # actualités
195 def actualite_index(request, type='actu'):
196 if type == 'appels':
197 search_form = AppelSearchForm(request.GET)
198 template = "savoirs/appels_index.html"
199 try:
200 p = PageStatique.objects.get(id='appels')
201 entete = p.contenu
202 except PageStatique.DoesNotExist:
203 entete = "<h1>Appels d'offres scientifiques</h1>"
204 else:
205 search_form = ActualiteSearchForm(request.GET)
206 template = "savoirs/actualite_index.html"
207 try:
208 p = PageStatique.objects.get(id='actualites')
209 entete = p.contenu
210 except PageStatique.DoesNotExist:
211 entete = '<h1>Actualités</h1>'
212
213 if search_form.is_valid():
214 search = search_form.save(commit=False)
215 else:
216 raise Http404
217 actualites = search.run()
218 excerpt = excerpt_function(
219 Actualite.objects, search_form.cleaned_data['q']
220 )
221
222 return render(request, template, {
223 'actualites': actualites,
224 'search_form': search_form,
225 'excerpt': excerpt,
226 'nb_resultats': actualites.count(),
227 'entete': entete,
228 })
229
230
231 def actualite(request, id):
232 actualite = get_object_or_404(Actualite, pk=id)
233 return render(request, "savoirs/actualite.html", {'actualite': actualite})
234
235
236 # agenda
237 def evenement_index(request):
238 if request.GET.get('q', False) \
239 or request.GET.get('type', False) \
240 or request.GET.get('date_min', False) \
241 or request.GET.get('date_max', False) \
242 or request.GET.get('discipline', False) \
243 or request.GET.get('region', False):
244 search_form = EvenementSearchForm(request.GET)
245 if search_form.is_valid():
246 search = search_form.save(commit=False)
247 else:
248 raise Http404
249 q = search_form.cleaned_data.get('q', '')
250
251 else:
252 today = datetime.date.today()
253 search_form = EvenementSearchForm({'date_min': today})
254 if search_form.is_valid():
255 search = search_form.save(commit=False)
256 else:
257 raise Http404
258 search.date_min = today
259 q = ''
260
261 evenements = search.run()
262 excerpt = excerpt_function(Evenement.objects, q)
263
264 ordre = request.GET.get('sort', 'soumission')
265 if ordre == 'soumission':
266 evenements = evenements.order_by('-date_modification')
267 else:
268 evenements = evenements.order_by('debut')
269
270 try:
271 p = PageStatique.objects.get(id='agenda')
272 entete = p.contenu
273 except PageStatique.DoesNotExist:
274 entete = '<h1>Agenda</h1>'
275
276 return render(request, "savoirs/evenement_index.html", {
277 'evenements': evenements,
278 'search_form': search_form,
279 'ordre': ordre,
280 'excerpt': excerpt,
281 'nb_resultats': evenements.count(),
282 'entete': entete,
283 })
284
285
286 def evenement_utilisation(request):
287 return render(request, "savoirs/evenement_utilisation.html")
288
289
290 def evenement(request, id):
291 evenement = get_object_or_404(Evenement, pk=id)
292 return render(request, "savoirs/evenement.html", {'evenement': evenement})
293
294
295 def evenement_ajout(request):
296 template = "savoirs/evenement_ajout.html"
297 if request.method == "POST":
298 form = EvenementForm(request.POST, request.FILES)
299 if form.is_valid():
300 form.save()
301 template = "savoirs/evenement_confirmation.html"
302 else:
303 form = EvenementForm()
304 return render(request, template, {'form': form})
305
306
307 def options_fuseau_horaire(request):
308 pays = get_object_or_404(ref.Pays, id=request.GET.get('pays'))
309 choices = build_time_zone_choices(pays.code)
310 if len(choices) > 1:
311 choices = [('', '---------')] + choices
312 return render(request, 'savoirs/options_fuseau_horaire.html', {
313 'choices': choices
314 })
315
316
317 # pages statiques
318
319 def page_statique(request, id):
320 page = get_object_or_404(PageStatique, pk=id)
321 return render(request, 'savoirs/page_statique.html', {'page': page})
322
323
324 # recherches sauvegardées
325
326 @login_required
327 def recherches(request):
328 types = []
329 for model in [Search, ChercheurSearch, RessourceSearch,
330 ActualiteSearch, AppelSearch, EvenementSearch, SiteSearch]:
331 content_type = ContentType.objects.get_for_model(model)
332 recherches = model.objects.filter(
333 user=request.user, content_type=content_type
334 )
335 if recherches.count() > 0:
336 types.append({
337 'label': model._meta.verbose_name_plural.capitalize(),
338 'recherches': recherches
339 })
340
341 return render(request, 'savoirs/recherches.html', {'types': types})
342
343
344 @login_required
345 def sauvegarder_recherche(request, type):
346 """Sauvegarde une recherche"""
347 if type == 'ressources':
348 form_class = RessourceSearchEditForm
349 elif type == 'actualites':
350 form_class = ActualiteSearchEditForm
351 elif type == 'appels':
352 form_class = AppelSearchEditForm
353 elif type == 'sites':
354 form_class = SiteSearchEditForm
355 elif type == 'chercheurs':
356 form_class = ChercheurSearchEditForm
357 elif type == 'evenements':
358 form_class = EvenementSearchEditForm
359 else:
360 form_class = SearchEditForm
361
362 if request.POST:
363 form = form_class(request.POST)
364 if form.is_valid():
365 search = form.save(commit=False)
366 search.user = request.user
367 search.save()
368 request.flash['message'] = 'Votre recherche a été sauvegardée.'
369 return redirect(search.url())
370 else:
371 form = form_class(
372 initial=dict(request.GET.iteritems(), alerte_courriel=True)
373 )
374 return render(request, "savoirs/sauvegarder_recherche.html", {
375 'form': form
376 })
377
378
379 @login_required
380 def editer_recherche(request, id):
381 """Éditer une recherche"""
382 recherche = get_object_or_404(
383 Search, id=id, user=request.user
384 ).as_leaf_class()
385 if isinstance(recherche, RessourceSearch):
386 form_class = RessourceSearchEditForm
387 elif isinstance(recherche, ActualiteSearch):
388 form_class = ActualiteSearchEditForm
389 elif isinstance(recherche, AppelSearch):
390 form_class = AppelSearchEditForm
391 elif isinstance(recherche, SiteSearch):
392 form_class = SiteSearchEditForm
393 elif isinstance(recherche, ChercheurSearch):
394 form_class = ChercheurSearchEditForm
395 elif isinstance(recherche, EvenementSearch):
396 form_class = EvenementSearchEditForm
397 else:
398 form_class = SearchEditForm
399
400 if request.POST:
401 form = form_class(request.POST, instance=recherche)
402 if form.is_valid():
403 form.save()
404 return redirect('recherches')
405 else:
406 form = form_class(instance=recherche)
407 return render(request, 'savoirs/editer_recherche.html', {'form': form})
408
409
410 @login_required
411 def supprimer_recherche(request, id):
412 """Supprimer une recherche"""
413 recherche = get_object_or_404(Search, id=id, user=request.user)
414 if request.POST:
415 if request.POST.get('confirmation'):
416 request.flash['message'] = 'La recherche a été supprimée.'
417 recherche.delete()
418 return redirect('recherches')
419 return render(request, 'savoirs/supprimer_recherche.html', {
420 'recherche': recherche
421 })
422
423
424 @login_required
425 def activer_alerte(request, id):
426 """Activer une alerte courriel"""
427 recherche = get_object_or_404(Search, id=id, user=request.user)
428 recherche.alerte_courriel = True
429 recherche.save()
430 return redirect('recherches')
431
432
433 @login_required
434 def desactiver_alerte(request, id):
435 """Désactiver une alerte courriel"""
436 recherche = get_object_or_404(Search, id=id, user=request.user)
437 recherche.alerte_courriel = False
438 recherche.save()
439 return redirect('recherches')
440
441
442 @login_required
443 def evenement_moderation(request):
444 events = Evenement.objects.filter(approuve=False)
445 return render(request, "savoirs/evenement_moderation.html", {
446 'events': events
447 })
448
449
450 @login_required
451 def evenement_accepter(request, pk):
452 e = Evenement.objects.get(pk=pk)
453 e.save()
454 return redirect('savoirs.views.evenement_moderation')
455
456
457 @login_required
458 def evenement_refuser(request, pk):
459 evenement = Evenement.objects.get(pk=pk)
460 evenement.actif = False
461 evenement.save()
462 return redirect('savoirs.views.evenement_moderation')
463
464
465 @login_required
466 def json_get(request):
467 uri = request.GET.get("uri")
468 if uri:
469 s = sep.SEP()
470 res = s.search({'uri': uri.encode("utf-8")})
471 r = s.get(res)
472
473 return HttpResponse(simplejson.dumps(r[0]),
474 mimetype='application/json')
475
476
477 @login_required
478 def json_set(request):
479 data = request.POST.get("data")
480 if data:
481 r = simplejson.loads(data)
482 s = sep.SEP()
483 s.add(r)
484 return HttpResponse(simplejson.dumps("OK"),
485 mimetype='application/json')