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