Supprimé des sources qui ne fonctionnent plus
[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 try:
309 pays = ref.Pays.objects.get(id=request.GET.get('pays'))
310 except ValueError, ref.Pays.DoesNotExist:
311 choices = build_time_zone_choices()
312 else:
313 choices = build_time_zone_choices(pays.code)
314 if len(choices) > 1:
315 choices = [('', '---------')] + choices
316 return render(request, 'savoirs/options_fuseau_horaire.html', {
317 'choices': choices
318 })
319
320
321 # pages statiques
322
323 def page_statique(request, id):
324 page = get_object_or_404(PageStatique, pk=id)
325 return render(request, 'savoirs/page_statique.html', {'page': page})
326
327
328 # recherches sauvegardées
329
330 @login_required
331 def recherches(request):
332 types = []
333 for model in [Search, ChercheurSearch, RessourceSearch,
334 ActualiteSearch, AppelSearch, EvenementSearch, SiteSearch]:
335 content_type = ContentType.objects.get_for_model(model)
336 recherches = model.objects.filter(
337 user=request.user, content_type=content_type
338 )
339 if recherches.count() > 0:
340 types.append({
341 'label': model._meta.verbose_name_plural.capitalize(),
342 'recherches': recherches
343 })
344
345 return render(request, 'savoirs/recherches.html', {'types': types})
346
347
348 @login_required
349 def sauvegarder_recherche(request, type):
350 """Sauvegarde une recherche"""
351 if type == 'ressources':
352 form_class = RessourceSearchEditForm
353 elif type == 'actualites':
354 form_class = ActualiteSearchEditForm
355 elif type == 'appels':
356 form_class = AppelSearchEditForm
357 elif type == 'sites':
358 form_class = SiteSearchEditForm
359 elif type == 'chercheurs':
360 form_class = ChercheurSearchEditForm
361 elif type == 'evenements':
362 form_class = EvenementSearchEditForm
363 else:
364 form_class = SearchEditForm
365
366 if request.POST:
367 form = form_class(request.POST)
368 if form.is_valid():
369 search = form.save(commit=False)
370 search.user = request.user
371 search.save()
372 request.flash['message'] = 'Votre recherche a été sauvegardée.'
373 return redirect(search.url())
374 else:
375 form = form_class(
376 initial=dict(request.GET.iteritems(), alerte_courriel=True)
377 )
378 return render(request, "savoirs/sauvegarder_recherche.html", {
379 'form': form
380 })
381
382
383 @login_required
384 def editer_recherche(request, id):
385 """Éditer une recherche"""
386 recherche = get_object_or_404(
387 Search, id=id, user=request.user
388 ).as_leaf_class()
389 if isinstance(recherche, RessourceSearch):
390 form_class = RessourceSearchEditForm
391 elif isinstance(recherche, ActualiteSearch):
392 form_class = ActualiteSearchEditForm
393 elif isinstance(recherche, AppelSearch):
394 form_class = AppelSearchEditForm
395 elif isinstance(recherche, SiteSearch):
396 form_class = SiteSearchEditForm
397 elif isinstance(recherche, ChercheurSearch):
398 form_class = ChercheurSearchEditForm
399 elif isinstance(recherche, EvenementSearch):
400 form_class = EvenementSearchEditForm
401 else:
402 form_class = SearchEditForm
403
404 if request.POST:
405 form = form_class(request.POST, instance=recherche)
406 if form.is_valid():
407 form.save()
408 return redirect('recherches')
409 else:
410 form = form_class(instance=recherche)
411 return render(request, 'savoirs/editer_recherche.html', {'form': form})
412
413
414 @login_required
415 def supprimer_recherche(request, id):
416 """Supprimer une recherche"""
417 recherche = get_object_or_404(Search, id=id, user=request.user)
418 if request.POST:
419 if request.POST.get('confirmation'):
420 request.flash['message'] = 'La recherche a été supprimée.'
421 recherche.delete()
422 return redirect('recherches')
423 return render(request, 'savoirs/supprimer_recherche.html', {
424 'recherche': recherche
425 })
426
427
428 @login_required
429 def activer_alerte(request, id):
430 """Activer une alerte courriel"""
431 recherche = get_object_or_404(Search, id=id, user=request.user)
432 recherche.alerte_courriel = True
433 recherche.save()
434 return redirect('recherches')
435
436
437 @login_required
438 def desactiver_alerte(request, id):
439 """Désactiver une alerte courriel"""
440 recherche = get_object_or_404(Search, id=id, user=request.user)
441 recherche.alerte_courriel = False
442 recherche.save()
443 return redirect('recherches')
444
445
446 @login_required
447 def evenement_moderation(request):
448 events = Evenement.objects.filter(approuve=False)
449 return render(request, "savoirs/evenement_moderation.html", {
450 'events': events
451 })
452
453
454 @login_required
455 def evenement_accepter(request, pk):
456 e = Evenement.objects.get(pk=pk)
457 e.save()
458 return redirect('savoirs.views.evenement_moderation')
459
460
461 @login_required
462 def evenement_refuser(request, pk):
463 evenement = Evenement.objects.get(pk=pk)
464 evenement.actif = False
465 evenement.save()
466 return redirect('savoirs.views.evenement_moderation')
467
468
469 @login_required
470 def json_get(request):
471 uri = request.GET.get("uri")
472 if uri:
473 s = sep.SEP()
474 res = s.search({'uri': uri.encode("utf-8")})
475 r = s.get(res)
476
477 return HttpResponse(simplejson.dumps(r[0]),
478 mimetype='application/json')
479
480
481 @login_required
482 def json_set(request):
483 data = request.POST.get("data")
484 if data:
485 r = simplejson.loads(data)
486 s = sep.SEP()
487 s.add(r)
488 return HttpResponse(simplejson.dumps("OK"),
489 mimetype='application/json')