Réparé l'agenda
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / savoirs / views.py
CommitLineData
d15017b2 1# -*- encoding: utf-8 -*-
1719bf4e 2import copy
832f8a9d 3import datetime
ae7d2874 4import simplejson
92c7413b 5
9965b831 6from auf.django.references import models as ref
ae7d2874 7from django.shortcuts import render, get_object_or_404, redirect
2aa2a26c 8from django.http import HttpResponse, Http404
5ecd5424 9from django.contrib.auth.decorators import login_required
fdcf5874 10from django.contrib.contenttypes.models import ContentType
f0692c02 11from django.utils.safestring import mark_safe
0e9597af 12from django.conf import settings
fdcf5874
EMS
13
14import backend_config
15from chercheurs.forms import ChercheurSearch, ChercheurSearchEditForm
2b564f72 16from lib.recherche import google_search, excerpt_function
c08a8cb8 17from lib import sep
ecc62927 18from savoirs.globals import configuration
ae7d2874
EMS
19from savoirs.forms import \
20 RessourceSearchForm, AppelSearchForm, ActualiteSearchForm, \
21 EvenementSearchForm, EvenementForm, RessourceSearchEditForm, \
22 ActualiteSearchEditForm, EvenementSearchEditForm, \
23 AppelSearchEditForm, SearchEditForm
24from savoirs.models import \
25 Discipline, Region, Search, Record, PageStatique, HarvestLog, \
26 Actualite, Evenement, build_time_zone_choices, ActualiteSearch, \
27 RessourceSearch, EvenementSearch, AppelSearch
fdcf5874 28from sitotheque.forms import SiteSearch, SiteSearchEditForm
92c7413b 29
bae03b7b 30
ae7d2874 31# Accueil
f0692c02 32def index(request, discipline=None, region=None):
f8c16b3d 33 """Page d'accueil"""
ae7d2874
EMS
34 discipline_obj = discipline and get_object_or_404(
35 Discipline, pk=discipline
36 )
fdcf5874
EMS
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()
7a5b8e23 40 today = datetime.date.today()
ae7d2874
EMS
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
d15017b2 52
f8c16b3d 53# sous-menu droite
f0692c02 54def a_propos(request):
ae7d2874
EMS
55 return render(request, "savoirs/a-propos.html")
56
f8c16b3d 57
f0692c02 58def nous_contacter(request):
ae7d2874
EMS
59 return render(request, "savoirs/contact.html", {
60 'courriel': settings.CONTACT_EMAIL
61 })
62
63
f0692c02 64def legal(request):
ae7d2874
EMS
65 return render(request, "savoirs/legal.html")
66
f8c16b3d 67
68# recherche
c1b134f8 69def recherche(request, discipline=None, region=None):
0b72ebef 70 query = request.GET.get("q", "")
3c23982e 71 if not query.strip():
ae7d2874 72
37cce5f0
EMS
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
ae7d2874 80 return redirect('savoirs.views.index', **kwargs)
37cce5f0 81
fdcf5874 82 # Effectuer la recherche
ae7d2874
EMS
83 discipline_obj = discipline and \
84 get_object_or_404(Discipline, pk=discipline)
fdcf5874
EMS
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()
f0692c02
EMS
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:
fdcf5874 94 params['discipline'] = unicode(discipline)
f0692c02 95 if region:
fdcf5874 96 params['region'] = unicode(region)
f0692c02 97 if params:
ae7d2874
EMS
98 briques_query_string = mark_safe(
99 '?' + '&'.join(k + '=' + v.replace('"', '"')
100 for (k, v) in params.iteritems())
101 )
f0692c02
EMS
102 else:
103 briques_query_string = None
ae7d2874 104
5212238e
EMS
105 excerpt = excerpt_function(Record.objects, query)
106
ae7d2874
EMS
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
d15017b2 128
f0692c02 129def sites_auf(request):
0b1ddc11
EMS
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
ae7d2874
EMS
136 return render(request, 'savoirs/sites_auf.html', {
137 'google_q': q,
138 'data': data,
139 'page': page,
140 })
141
d15017b2 142
f8c16b3d 143# ressources
f0692c02 144def ressource_index(request):
fdcf5874 145 search_form = RessourceSearchForm(request.GET)
2aa2a26c
EMS
146 if search_form.is_valid():
147 search = search_form.save(commit=False)
148 else:
149 raise Http404
fdcf5874 150 ressources = search.run()
878de341 151 nb_resultats = ressources.count()
2b564f72 152 excerpt = excerpt_function(Record.objects, search_form.cleaned_data['q'])
f09bc1c6
EMS
153 try:
154 p = PageStatique.objects.get(id='ressources')
155 entete = p.contenu
156 except PageStatique.DoesNotExist:
157 entete = '<h1>Ressources</h1>'
fdcf5874 158
ae7d2874
EMS
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
f61e4846 167
f0692c02 168def ressource_retrieve(request, id):
91e0aefb 169 """Notice OAI de la ressource"""
2127a108 170 ressource = get_object_or_404(Record, id=id)
ae7d2874
EMS
171 return render(request, "savoirs/ressource_retrieve.html", {
172 'ressource': ressource,
173 'disciplines': ressource.disciplines.all(),
174 'regions': ressource.regions.all(),
175 })
176
80469cb6 177
ae7d2874
EMS
178def 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 ]
80469cb6 186 for l in logs:
ae7d2874
EMS
187 resources[l.name]['logs'] = {'date': l.date, 'count': l.processed}
188
189 return render(request, "savoirs/informations.html", {
190 'r': resources,
191 })
80469cb6 192
d15017b2 193
f8c16b3d 194# actualités
011804bb 195def actualite_index(request, type='actu'):
011804bb 196 if type == 'appels':
bb7d016f 197 search_form = AppelSearchForm(request.GET)
011804bb 198 template = "savoirs/appels_index.html"
f09bc1c6
EMS
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>"
011804bb 204 else:
bb7d016f 205 search_form = ActualiteSearchForm(request.GET)
011804bb 206 template = "savoirs/actualite_index.html"
f09bc1c6
EMS
207 try:
208 p = PageStatique.objects.get(id='actualites')
209 entete = p.contenu
210 except PageStatique.DoesNotExist:
211 entete = '<h1>Actualités</h1>'
212
2aa2a26c
EMS
213 if search_form.is_valid():
214 search = search_form.save(commit=False)
215 else:
216 raise Http404
bb7d016f 217 actualites = search.run()
ae7d2874
EMS
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 })
bb7d016f 229
5ecd5424 230
c30f12c5
EMS
231def actualite(request, id):
232 actualite = get_object_or_404(Actualite, pk=id)
ae7d2874
EMS
233 return render(request, "savoirs/actualite.html", {'actualite': actualite})
234
c30f12c5 235
f8c16b3d 236# agenda
f0692c02 237def evenement_index(request):
ae7d2874
EMS
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):
832f8a9d 244 search_form = EvenementSearchForm(request.GET)
2aa2a26c
EMS
245 if search_form.is_valid():
246 search = search_form.save(commit=False)
247 else:
248 raise Http404
832f8a9d
PP
249 q = search_form.cleaned_data.get('q', '')
250
251 else:
252 today = datetime.date.today()
743b02a9 253 search_form = EvenementSearchForm({'date_min': today})
2aa2a26c
EMS
254 if search_form.is_valid():
255 search = search_form.save(commit=False)
256 else:
257 raise Http404
832f8a9d
PP
258 search.date_min = today
259 q = ''
260
fdcf5874 261 evenements = search.run()
832f8a9d 262 excerpt = excerpt_function(Evenement.objects, q)
3ea74990
PP
263
264 ordre = request.GET.get('sort', 'soumission')
265 if ordre == 'soumission':
266 evenements = evenements.order_by('-date_modification')
267 else:
832f8a9d 268 evenements = evenements.order_by('debut')
3ea74990 269
f09bc1c6
EMS
270 try:
271 p = PageStatique.objects.get(id='agenda')
272 entete = p.contenu
273 except PageStatique.DoesNotExist:
274 entete = '<h1>Agenda</h1>'
275
ae7d2874
EMS
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
d566e9c1 285
f0692c02 286def evenement_utilisation(request):
ae7d2874
EMS
287 return render(request, "savoirs/evenement_utilisation.html")
288
289
f0692c02 290def evenement(request, id):
4101cfc0 291 evenement = get_object_or_404(Evenement, pk=id)
ae7d2874
EMS
292 return render(request, "savoirs/evenement.html", {'evenement': evenement})
293
92c7413b 294
f0692c02 295def evenement_ajout(request):
92c7413b
CR
296 template = "savoirs/evenement_ajout.html"
297 if request.method == "POST":
ea3822a7 298 form = EvenementForm(request.POST, request.FILES)
92c7413b
CR
299 if form.is_valid():
300 form.save()
301 template = "savoirs/evenement_confirmation.html"
302 else:
303 form = EvenementForm()
ae7d2874
EMS
304 return render(request, template, {'form': form})
305
92c7413b 306
1719bf4e 307def options_fuseau_horaire(request):
9965b831
EMS
308 pays = get_object_or_404(ref.Pays, id=request.GET.get('pays'))
309 choices = build_time_zone_choices(pays.code)
1719bf4e
EMS
310 if len(choices) > 1:
311 choices = [('', '---------')] + choices
ae7d2874
EMS
312 return render(request, 'savoirs/options_fuseau_horaire.html', {
313 'choices': choices
314 })
315
1719bf4e 316
f09bc1c6
EMS
317# pages statiques
318
319def page_statique(request, id):
320 page = get_object_or_404(PageStatique, pk=id)
ae7d2874
EMS
321 return render(request, 'savoirs/page_statique.html', {'page': page})
322
323
fdcf5874
EMS
324# recherches sauvegardées
325
326@login_required
327def 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)
ae7d2874
EMS
332 recherches = model.objects.filter(
333 user=request.user, content_type=content_type
334 )
fdcf5874 335 if recherches.count() > 0:
ae7d2874
EMS
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})
fdcf5874 342
fdcf5874
EMS
343
344@login_required
345def sauvegarder_recherche(request, type):
346 """Sauvegarde une recherche"""
347 if type == 'ressources':
348 form_class = RessourceSearchEditForm
4bef5dc2 349 elif type == 'actualites':
fdcf5874 350 form_class = ActualiteSearchEditForm
4bef5dc2
EMS
351 elif type == 'appels':
352 form_class = AppelSearchEditForm
fdcf5874
EMS
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.'
ae7d2874 369 return redirect(search.url())
fdcf5874 370 else:
ae7d2874
EMS
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
fdcf5874
EMS
378
379@login_required
380def editer_recherche(request, id):
381 """Éditer une recherche"""
ae7d2874
EMS
382 recherche = get_object_or_404(
383 Search, id=id, user=request.user
384 ).as_leaf_class()
fdcf5874
EMS
385 if isinstance(recherche, RessourceSearch):
386 form_class = RessourceSearchEditForm
4bef5dc2 387 elif isinstance(recherche, ActualiteSearch):
fdcf5874 388 form_class = ActualiteSearchEditForm
4bef5dc2
EMS
389 elif isinstance(recherche, AppelSearch):
390 form_class = AppelSearchEditForm
fdcf5874
EMS
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()
ae7d2874 404 return redirect('recherches')
fdcf5874
EMS
405 else:
406 form = form_class(instance=recherche)
ae7d2874
EMS
407 return render(request, 'savoirs/editer_recherche.html', {'form': form})
408
fdcf5874
EMS
409
410@login_required
411def 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()
ae7d2874
EMS
418 return redirect('recherches')
419 return render(request, 'savoirs/supprimer_recherche.html', {
fdcf5874 420 'recherche': recherche
ae7d2874
EMS
421 })
422
fdcf5874 423
92c7413b 424@login_required
4b89a7df
EMS
425def 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()
ae7d2874
EMS
430 return redirect('recherches')
431
4b89a7df
EMS
432
433@login_required
434def 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()
ae7d2874
EMS
439 return redirect('recherches')
440
4b89a7df
EMS
441
442@login_required
92c7413b 443def evenement_moderation(request):
ae7d2874
EMS
444 events = Evenement.objects.filter(approuve=False)
445 return render(request, "savoirs/evenement_moderation.html", {
446 'events': events
447 })
448
92c7413b
CR
449
450@login_required
451def evenement_accepter(request, pk):
ae7d2874 452 e = Evenement.objects.get(pk=pk)
92c7413b 453 e.save()
ae7d2874
EMS
454 return redirect('savoirs.views.evenement_moderation')
455
92c7413b
CR
456
457@login_required
458def evenement_refuser(request, pk):
ae7d2874 459 evenement = Evenement.objects.get(pk=pk)
92c7413b
CR
460 evenement.actif = False
461 evenement.save()
ae7d2874
EMS
462 return redirect('savoirs.views.evenement_moderation')
463
92c7413b 464
5ecd5424 465@login_required
ae7d2874
EMS
466def json_get(request):
467 uri = request.GET.get("uri")
5ecd5424 468 if uri:
ae7d2874
EMS
469 s = sep.SEP()
470 res = s.search({'uri': uri.encode("utf-8")})
471 r = s.get(res)
472
c08a8cb8 473 return HttpResponse(simplejson.dumps(r[0]),
5ecd5424
CR
474 mimetype='application/json')
475
ae7d2874 476
5ecd5424 477@login_required
ae7d2874 478def json_set(request):
5ecd5424
CR
479 data = request.POST.get("data")
480 if data:
481 r = simplejson.loads(data)
ae7d2874
EMS
482 s = sep.SEP()
483 s.add(r)
5ecd5424
CR
484 return HttpResponse(simplejson.dumps("OK"),
485 mimetype='application/json')