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