Fix admin
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / savoirs / models.py
CommitLineData
92c7413b 1# -*- encoding: utf-8 -*-
db2999fa
EMS
2import caldav
3import datetime
4import feedparser
5import operator
6import os
7import pytz
8import random
9import uuid
10import vobject
86983865 11from babel.dates import get_timezone_name
6d885e0c 12from django.contrib.auth.models import User
d15017b2 13from django.db import models
15261361 14from django.db.models import Q, Max
b7a741ad 15from django.db.models.signals import pre_delete
116db1fd 16from auf_savoirs_en_partage.backend_config import RESOURCES
da9020f3 17from savoirs.globals import META
74b087e5 18from settings import CALENDRIER_URL, SITE_ROOT_URL
116db1fd
EMS
19from datamaster_modeles.models import Thematique, Pays, Region
20from lib.calendrier import combine
21from caldav.lib import error
d15017b2 22
15261361
EMS
23class RandomQuerySetMixin(object):
24 """Mixin pour les modèles.
25
26 ORDER BY RAND() est très lent sous MySQL. On a besoin d'une autre
27 méthode pour récupérer des objets au hasard.
28 """
29
30 def random(self, n=1):
31 """Récupère aléatoirement un nombre donné d'objets."""
bae03b7b
EMS
32 count = self.count()
33 positions = random.sample(xrange(count), min(n, count))
34 return [self[p] for p in positions]
15261361 35
d15017b2
CR
36class Discipline(models.Model):
37 id = models.IntegerField(primary_key=True, db_column='id_discipline')
38 nom = models.CharField(max_length=765, db_column='nom_discipline')
6ef8ead4
CR
39
40 def __unicode__ (self):
92c7413b 41 return self.nom
6ef8ead4 42
d15017b2
CR
43 class Meta:
44 db_table = u'discipline'
45 ordering = ["nom",]
46
79c398f6
CR
47class SourceActualite(models.Model):
48 nom = models.CharField(max_length=255)
db2999fa 49 url = models.CharField(max_length=255, verbose_name='URL')
ccbc4363 50
51 def __unicode__(self,):
52 return u"%s" % self.nom
79c398f6 53
db2999fa
EMS
54 class Meta:
55 verbose_name = u'fil RSS syndiqué'
56 verbose_name_plural = u'fils RSS syndiqués'
57
58 def update(self):
59 """Mise à jour du fil RSS."""
60 feed = feedparser.parse(self.url)
61 for entry in feed.entries:
62 if Actualite.all_objects.filter(url=entry.link).count() == 0:
63 ts = entry.updated_parsed
64 date = datetime.date(ts.tm_year, ts.tm_mon, ts.tm_mday)
65 a = self.actualites.create(titre=entry.title,
66 texte=entry.summary_detail.value,
67 url=entry.link, date=date)
68
116db1fd
EMS
69class ActualiteManager(models.Manager):
70
71 def get_query_set(self):
c59dba82 72 return ActualiteQuerySet(self.model).filter(visible=True)
2f9c4d6c 73
116db1fd
EMS
74 def search(self, text):
75 return self.get_query_set().search(text)
da44ce68 76
116db1fd
EMS
77 def filter_region(self, region):
78 return self.get_query_set().filter_region(region)
c1b134f8 79
116db1fd
EMS
80 def filter_discipline(self, discipline):
81 return self.get_query_set().filter_discipline(discipline)
c1b134f8 82
116db1fd 83class ActualiteQuerySet(models.query.QuerySet, RandomQuerySetMixin):
2f9c4d6c 84
116db1fd
EMS
85 def search(self, text):
86 q = None
87 for word in text.split():
88 part = (Q(titre__icontains=word) | Q(texte__icontains=word) |
89 Q(regions__nom__icontains=word) | Q(disciplines__nom__icontains=word))
90 if q is None:
91 q = part
92 else:
93 q = q & part
94 return self.filter(q).distinct() if q is not None else self
2f9c4d6c 95
116db1fd
EMS
96 def filter_discipline(self, discipline):
97 """Ne conserve que les actualités dans la discipline donnée.
98
99 Si ``disicipline`` est None, ce filtre n'a aucun effet."""
100 if discipline is None:
101 return self
102 if not isinstance(discipline, Discipline):
103 discipline = Discipline.objects.get(pk=discipline)
104 return self.filter(Q(disciplines=discipline) |
105 Q(titre__icontains=discipline.nom) |
106 Q(texte__icontains=discipline.nom)).distinct()
bae03b7b 107
116db1fd
EMS
108 def filter_region(self, region):
109 """Ne conserve que les actualités dans la région donnée.
110
111 Si ``region`` est None, ce filtre n'a aucun effet."""
112 if region is None:
113 return self
114 if not isinstance(region, Region):
115 region = Region.objects.get(pk=region)
116 return self.filter(Q(regions=region) |
117 Q(titre__icontains=region.nom) |
118 Q(texte__icontains=region.nom)).distinct()
bae03b7b 119
d15017b2 120class Actualite(models.Model):
4f262f90 121 id = models.AutoField(primary_key=True, db_column='id_actualite')
d15017b2
CR
122 titre = models.CharField(max_length=765, db_column='titre_actualite')
123 texte = models.TextField(db_column='texte_actualite')
124 url = models.CharField(max_length=765, db_column='url_actualite')
d15017b2 125 date = models.DateField(db_column='date_actualite')
db2999fa
EMS
126 visible = models.BooleanField(db_column='visible_actualite', default=False)
127 ancienid = models.IntegerField(db_column='ancienId_actualite', blank=True, null=True)
128 source = models.ForeignKey(SourceActualite, blank=True, null=True)
3a45eb64 129 disciplines = models.ManyToManyField(Discipline, blank=True, related_name="actualites")
a5f76eb4 130 regions = models.ManyToManyField(Region, blank=True, related_name="actualites", verbose_name='régions')
6ef8ead4 131
2f9c4d6c 132 objects = ActualiteManager()
c59dba82 133 all_objects = models.Manager()
2f9c4d6c 134
d15017b2
CR
135 class Meta:
136 db_table = u'actualite'
7020ea3d 137 ordering = ["-date"]
92c7413b 138
264a3210
EMS
139 def __unicode__ (self):
140 return "%s" % (self.titre)
141
142 def assigner_disciplines(self, disciplines):
143 self.disciplines.add(*disciplines)
144
145 def assigner_regions(self, regions):
146 self.regions.add(*regions)
147
116db1fd 148class EvenementManager(models.Manager):
4101cfc0 149
116db1fd 150 def get_query_set(self):
c59dba82 151 return EvenementQuerySet(self.model).filter(approuve=True)
4101cfc0 152
116db1fd
EMS
153 def search(self, text):
154 return self.get_query_set().search(text)
4101cfc0 155
116db1fd
EMS
156 def filter_region(self, region):
157 return self.get_query_set().filter_region(region)
c1b134f8 158
116db1fd
EMS
159 def filter_discipline(self, discipline):
160 return self.get_query_set().filter_discipline(discipline)
c1b134f8 161
116db1fd 162class EvenementQuerySet(models.query.QuerySet, RandomQuerySetMixin):
4101cfc0 163
116db1fd
EMS
164 def search(self, text):
165 q = None
166 for word in text.split():
167 part = (Q(titre__icontains=word) |
168 Q(mots_cles__icontains=word) |
169 Q(discipline__nom__icontains=word) |
170 Q(discipline_secondaire__nom__icontains=word) |
171 Q(type__icontains=word) |
172 Q(lieu__icontains=word) |
173 Q(description__icontains=word) |
174 Q(contact__icontains=word) |
175 Q(regions__nom__icontains=word))
176 if q is None:
177 q = part
178 else:
179 q = q & part
180 return self.filter(q).distinct() if q is not None else self
181
182 def search_titre(self, text):
7bbf600c 183 qs = self
116db1fd
EMS
184 for word in text.split():
185 qs = qs.filter(titre__icontains=word)
7bbf600c
EMS
186 return qs
187
116db1fd
EMS
188 def filter_discipline(self, discipline):
189 """Ne conserve que les évènements dans la discipline donnée.
190
191 Si ``disicipline`` est None, ce filtre n'a aucun effet."""
192 if discipline is None:
193 return self
194 if not isinstance(discipline, Discipline):
195 discipline = Discipline.objects.get(pk=discipline)
196 return self.filter(Q(discipline=discipline) |
197 Q(discipline_secondaire=discipline) |
198 Q(titre__icontains=discipline.nom) |
199 Q(mots_cles__icontains=discipline.nom) |
200 Q(description__icontains=discipline.nom))
5212238e 201
116db1fd
EMS
202 def filter_region(self, region):
203 """Ne conserve que les évènements dans la région donnée.
204
205 Si ``region`` est None, ce filtre n'a aucun effet."""
206 if region is None:
207 return self
208 if not isinstance(region, Region):
209 region = Region.objects.get(pk=region)
210 return self.filter(Q(regions=region) |
211 Q(titre__icontains=region.nom) |
212 Q(mots_cles__icontains=region.nom) |
213 Q(description__icontains=region.nom) |
214 Q(lieu__icontains=region.nom)).distinct()
bae03b7b 215
86983865
EMS
216def build_time_zone_choices():
217 fr_names = set()
218 tzones = []
219 now = datetime.datetime.now()
220 for tzname in pytz.common_timezones:
221 tz = pytz.timezone(tzname)
222 fr_name = get_timezone_name(tz, locale='fr_FR')
223 if fr_name in fr_names:
224 continue
225 fr_names.add(fr_name)
226 offset = tz.utcoffset(now)
227 seconds = offset.seconds + offset.days * 86400
228 (hours, minutes) = divmod(seconds // 60, 60)
229 offset_str = 'UTC%+d:%d' % (hours, minutes) if minutes else 'UTC%+d' % hours
230 tzones.append((seconds, tzname, '%s - %s' % (offset_str, fr_name)))
231 tzones.sort()
232 return [(tz[1], tz[2]) for tz in tzones]
233
92c7413b 234class Evenement(models.Model):
7bbf600c
EMS
235 TYPE_CHOICES = ((u'Colloque', u'Colloque'),
236 (u'Conférence', u'Conférence'),
237 (u'Appel à contribution', u'Appel à contribution'),
238 (u'Journée d\'étude', u'Journée d\'étude'),
116db1fd 239 (None, u'Autre'))
86983865
EMS
240 TIME_ZONE_CHOICES = build_time_zone_choices()
241
74b087e5 242 uid = models.CharField(max_length=255, default=str(uuid.uuid1()))
a5f76eb4 243 approuve = models.BooleanField(default=False, verbose_name=u'approuvé')
92c7413b
CR
244 titre = models.CharField(max_length=255)
245 discipline = models.ForeignKey('Discipline', related_name = "discipline",
246 blank = True, null = True)
a5f76eb4
EMS
247 discipline_secondaire = models.ForeignKey('Discipline', related_name="discipline_secondaire",
248 verbose_name=u"discipline secondaire",
249 blank=True, null=True)
74b087e5 250 mots_cles = models.TextField('Mots-Clés', blank=True, null=True)
7bbf600c 251 type = models.CharField(max_length=255, choices=TYPE_CHOICES)
86983865 252 lieu = models.TextField()
74b087e5
EMS
253 debut = models.DateTimeField(default=datetime.datetime.now)
254 fin = models.DateTimeField(default=datetime.datetime.now)
86983865 255 fuseau = models.CharField(max_length=100, choices=TIME_ZONE_CHOICES, verbose_name='fuseau horaire')
74b087e5
EMS
256 description = models.TextField(blank=True, null=True)
257 contact = models.TextField(blank=True, null=True)
258 url = models.CharField(max_length=255, blank=True, null=True)
259 piece_jointe = models.FileField(upload_to='agenda/pj', blank=True, verbose_name='pièce jointe')
a5f76eb4 260 regions = models.ManyToManyField(Region, blank=True, related_name="evenements", verbose_name='régions')
92c7413b 261
4101cfc0 262 objects = EvenementManager()
c59dba82 263 all_objects = models.Manager()
4101cfc0
EMS
264
265 class Meta:
266 ordering = ['-debut']
267
020f79a9 268 def __unicode__(self,):
269 return "[%s] %s" % (self.uid, self.titre)
270
27fe0d70
EMS
271 def piece_jointe_display(self):
272 return self.piece_jointe and os.path.basename(self.piece_jointe.name)
273
73309469 274 def clean(self):
275 from django.core.exceptions import ValidationError
276 if self.debut > self.fin:
277 raise ValidationError('La date de fin ne doit pas être antérieure à la date de début')
278
b7a741ad 279 def save(self, *args, **kwargs):
280 """Sauvegarde l'objet dans django et le synchronise avec caldav s'il a été
281 approuvé"""
73309469 282 self.clean()
b7a741ad 283 self.update_vevent()
284 super(Evenement, self).save(*args, **kwargs)
285
286 # methodes de commnunications avec CALDAV
287 def as_ical(self,):
288 """Retourne l'evenement django sous forme d'objet icalendar"""
289 cal = vobject.iCalendar()
290 cal.add('vevent')
291
292 # fournit son propre uid
7f56d0d4 293 if self.uid in [None, ""]:
b7a741ad 294 self.uid = str(uuid.uuid1())
295
296 cal.vevent.add('uid').value = self.uid
297
298 cal.vevent.add('summary').value = self.titre
299
300 if self.mots_cles is None:
301 kw = []
302 else:
303 kw = self.mots_cles.split(",")
304
305 try:
306 kw.append(self.discipline.nom)
307 kw.append(self.discipline_secondaire.nom)
308 kw.append(self.type)
309 except: pass
310
79b400f0 311 kw = [x.strip() for x in kw if len(x.strip()) > 0 and x is not None]
b7a741ad 312 for k in kw:
313 cal.vevent.add('x-auf-keywords').value = k
314
315 description = self.description
316 if len(kw) > 0:
317 if len(self.description) > 0:
318 description += "\n"
028f548f 319 description += u"Mots-clés: " + ", ".join(kw)
b7a741ad 320
7f214e0f
EMS
321 cal.vevent.add('dtstart').value = combine(self.debut, pytz.timezone(self.fuseau))
322 cal.vevent.add('dtend').value = combine(self.fin, pytz.timezone(self.fuseau))
b7a741ad 323 cal.vevent.add('created').value = combine(datetime.datetime.now(), "UTC")
324 cal.vevent.add('dtstamp').value = combine(datetime.datetime.now(), "UTC")
79b400f0 325 if len(description) > 0:
b7a741ad 326 cal.vevent.add('description').value = description
327 if len(self.contact) > 0:
328 cal.vevent.add('contact').value = self.contact
329 if len(self.url) > 0:
330 cal.vevent.add('url').value = self.url
331 if len(self.lieu) > 0:
332 cal.vevent.add('location').value = self.lieu
74b087e5
EMS
333 if self.piece_jointe:
334 url = self.piece_jointe.url
335 if not url.startswith('http://'):
336 url = SITE_ROOT_URL + url
337 cal.vevent.add('attach').value = url
b7a741ad 338 return cal
339
340 def update_vevent(self,):
341 """Essaie de créer l'évènement sur le serveur ical.
342 En cas de succès, l'évènement local devient donc inactif et approuvé"""
343 try:
344 if self.approuve:
345 event = self.as_ical()
346 client = caldav.DAVClient(CALENDRIER_URL)
347 cal = caldav.Calendar(client, url = CALENDRIER_URL)
348 e = caldav.Event(client, parent = cal, data = event.serialize(), id=self.uid)
349 e.save()
350 except:
351 self.approuve = False
352
353 def delete_vevent(self,):
354 """Supprime l'evenement sur le serveur caldav"""
355 try:
356 if self.approuve:
357 event = self.as_ical()
358 client = caldav.DAVClient(CALENDRIER_URL)
359 cal = caldav.Calendar(client, url = CALENDRIER_URL)
360 e = cal.event(self.uid)
361 e.delete()
362 except error.NotFoundError:
363 pass
364
264a3210
EMS
365 def assigner_regions(self, regions):
366 self.regions.add(*regions)
367
368 def assigner_disciplines(self, disciplines):
369 if len(disciplines) == 1:
370 if self.discipline:
371 self.discipline_secondaire = disciplines[0]
372 else:
373 self.discipline = disciplines[0]
374 elif len(disciplines) >= 2:
375 self.discipline = disciplines[0]
376 self.discipline_secondaire = disciplines[1]
377
116db1fd
EMS
378
379# Surcharge du comportement de suppression
380# La méthode de connexion par signals est préférable à surcharger la méthode delete()
381# car dans le cas de la suppression par lots, cell-ci n'est pas invoquée
b7a741ad 382def delete_vevent(sender, instance, *args, **kwargs):
383 instance.delete_vevent()
384
116db1fd
EMS
385pre_delete.connect(delete_vevent, sender = Evenement)
386
b7a741ad 387
d972b61d 388class ListSet(models.Model):
389 spec = models.CharField(primary_key = True, max_length = 255)
390 name = models.CharField(max_length = 255)
391 server = models.CharField(max_length = 255)
9eda5d6c 392 validated = models.BooleanField(default = True)
d972b61d 393
10d37e44 394 def __unicode__(self,):
395 return self.name
396
116db1fd
EMS
397class RecordManager(models.Manager):
398
399 def get_query_set(self):
c59dba82 400 return RecordQuerySet(self.model).filter(validated=True)
f153be1b 401
116db1fd
EMS
402 def search(self, text):
403 return self.get_query_set().search(text)
c1b134f8 404
116db1fd
EMS
405 def validated(self):
406 return self.get_query_set().validated()
f12cc7fb 407
116db1fd
EMS
408 def filter_region(self, region):
409 return self.get_query_set().filter_region(region)
410
411 def filter_discipline(self, discipline):
412 return self.get_query_set().filter_discipline(discipline)
413
414class RecordQuerySet(models.query.QuerySet, RandomQuerySetMixin):
415
416 def search(self, text):
417 qs = self
418 words = text.split()
419
420 # Ne garder que les ressources qui contiennent tous les mots
421 # demandés.
422 q = None
423 for word in words:
424 matching_pays = list(Pays.objects.filter(Q(nom__icontains=word) | Q(region__nom__icontains=word)).values_list('pk', flat=True))
425 part = (Q(title__icontains=word) | Q(description__icontains=word) |
426 Q(creator__icontains=word) | Q(contributor__icontains=word) |
427 Q(subject__icontains=word) | Q(disciplines__nom__icontains=word) |
428 Q(regions__nom__icontains=word) | Q(pays__in=matching_pays) |
429 Q(publisher__icontains=word))
430 if q is None:
431 q = part
432 else:
433 q = q & part
434 if q is not None:
435 qs = qs.filter(q).distinct()
436
437 # On donne un point pour chaque mot présent dans le titre.
438 if words:
439 score_expr = ' + '.join(['(title LIKE %s)'] * len(words))
440 score_params = ['%' + word + '%' for word in words]
441 qs = qs.extra(
442 select={'score': score_expr},
443 select_params=score_params
444 ).order_by('-score')
445 return qs
446
447 def search_auteur(self, text):
448 qs = self
449 for word in text.split():
450 qs = qs.filter(Q(creator__icontains=word) | Q(contributor__icontains=word))
451 return qs
452
453 def search_sujet(self, text):
454 qs = self
455 for word in text.split():
456 qs = qs.filter(subject__icontains=word)
457 return qs
458
459 def search_titre(self, text):
460 qs = self
461 for word in text.split():
462 qs = qs.filter(title__icontains=word)
463 return qs
464
465 def filter_discipline(self, discipline):
466 """Ne conserve que les ressources dans la discipline donnée.
467
468 Si ``disicipline`` est None, ce filtre n'a aucun effet."""
469 if discipline is None:
470 return self
471 if not isinstance(discipline, Discipline):
472 discipline = Discipline.objects.get(pk=discipline)
473 return self.filter(Q(disciplines=discipline) |
474 Q(title__icontains=discipline.nom) |
475 Q(description__icontains=discipline.nom) |
476 Q(subject__icontains=discipline.nom)).distinct()
477
478 def filter_region(self, region):
479 """Ne conserve que les ressources dans la région donnée.
480
481 Si ``region`` est None, ce filtre n'a aucun effet."""
482 if region is None:
483 return self
484 if not isinstance(region, Region):
485 region = Region.objects.get(pk=region)
486 return self.filter(Q(pays__region=region) |
487 Q(regions=region) |
488 Q(title__icontains=region.nom) |
489 Q(description__icontains=region.nom) |
490 Q(subject__icontains=region.nom)).distinct()
491
492 def validated(self):
f153be1b
EMS
493 """Ne garder que les ressources validées et qui sont soit dans aucun
494 listset ou au moins dans un listset validé."""
116db1fd 495 qs = self.filter(validated=True)
82f25472
EMS
496 qs = qs.filter(Q(listsets__isnull=True) | Q(listsets__validated=True))
497 return qs.distinct()
f153be1b 498
116db1fd
EMS
499 def filter(self, *args, **kwargs):
500 """Gère des filtres supplémentaires pour l'admin.
501
502 C'est la seule façon que j'ai trouvée de contourner les mécanismes
503 de recherche de l'admin."""
504 search = kwargs.pop('admin_search', None)
505 search_titre = kwargs.pop('admin_search_titre', None)
506 search_sujet = kwargs.pop('admin_search_sujet', None)
507 search_description = kwargs.pop('admin_search_description', None)
508 search_auteur = kwargs.pop('admin_search_auteur', None)
509
510 if search:
511 qs = self
512 search_all = not (search_titre or search_description or search_sujet or search_auteur)
513 fields = []
514 if search_titre or search_all:
515 fields += ['title', 'alt_title']
516 if search_description or search_all:
517 fields += ['description', 'abstract']
518 if search_sujet or search_all:
519 fields += ['subject']
520 if search_auteur or search_all:
521 fields += ['creator', 'contributor']
522
523 for bit in search.split():
524 or_queries = [Q(**{field + '__icontains': bit}) for field in fields]
525 qs = qs.filter(reduce(operator.or_, or_queries))
526
527 if args or kwargs:
528 qs = super(RecordQuerySet, qs).filter(*args, **kwargs)
529 return qs
530 else:
531 return super(RecordQuerySet, self).filter(*args, **kwargs)
77b0fac0 532
0cc5f772 533class Record(models.Model):
23b5b3d5 534
535 #fonctionnement interne
0cc5f772 536 id = models.AutoField(primary_key = True)
a5f76eb4 537 server = models.CharField(max_length = 255, verbose_name=u'serveur')
23b5b3d5 538 last_update = models.CharField(max_length = 255)
539 last_checksum = models.CharField(max_length = 255)
a5f76eb4 540 validated = models.BooleanField(default=True, verbose_name=u'validé')
23b5b3d5 541
542 #OAI
18dbd2cf
EMS
543 title = models.TextField(null=True, blank=True, verbose_name=u'titre')
544 creator = models.TextField(null=True, blank=True, verbose_name=u'auteur')
545 description = models.TextField(null=True, blank=True)
546 modified = models.CharField(max_length=255, null=True, blank=True)
23b5b3d5 547 identifier = models.CharField(max_length = 255, null = True, blank = True, unique = True)
548 uri = models.CharField(max_length = 255, null = True, blank = True, unique = True)
549 source = models.TextField(null = True, blank = True)
550 contributor = models.TextField(null = True, blank = True)
18dbd2cf 551 subject = models.TextField(null=True, blank=True, verbose_name='sujet')
23b5b3d5 552 publisher = models.TextField(null = True, blank = True)
553 type = models.TextField(null = True, blank = True)
554 format = models.TextField(null = True, blank = True)
555 language = models.TextField(null = True, blank = True)
da9020f3 556
c88d78dc 557 listsets = models.ManyToManyField(ListSet, null = True, blank = True)
d972b61d 558
da9020f3 559 #SEP 2 (aucune données récoltées)
23b5b3d5 560 alt_title = models.TextField(null = True, blank = True)
561 abstract = models.TextField(null = True, blank = True)
562 creation = models.CharField(max_length = 255, null = True, blank = True)
563 issued = models.CharField(max_length = 255, null = True, blank = True)
564 isbn = models.TextField(null = True, blank = True)
565 orig_lang = models.TextField(null = True, blank = True)
da9020f3 566
567 # Metadata AUF multivaluées
a342f93a
EMS
568 disciplines = models.ManyToManyField(Discipline, blank=True)
569 thematiques = models.ManyToManyField(Thematique, blank=True, verbose_name='thématiques')
570 pays = models.ManyToManyField(Pays, blank=True)
571 regions = models.ManyToManyField(Region, blank=True, verbose_name='régions')
0cc5f772 572
116db1fd 573 # Manager
da44ce68 574 objects = RecordManager()
c59dba82 575 all_objects = models.Manager()
da44ce68 576
18dbd2cf
EMS
577 class Meta:
578 verbose_name = 'ressource'
579
264a3210
EMS
580 def __unicode__(self):
581 return "[%s] %s" % (self.server, self.title)
582
583 def getServeurURL(self):
f98ad449 584 """Retourne l'URL du serveur de provenance"""
585 return RESOURCES[self.server]['url']
586
264a3210 587 def est_complet(self):
6d885e0c 588 """teste si le record à toutes les données obligatoires"""
589 return self.disciplines.count() > 0 and \
590 self.thematiques.count() > 0 and \
591 self.pays.count() > 0 and \
592 self.regions.count() > 0
593
264a3210
EMS
594 def assigner_regions(self, regions):
595 self.regions.add(*regions)
da9020f3 596
264a3210
EMS
597 def assigner_disciplines(self, disciplines):
598 self.disciplines.add(*disciplines)
264a3210 599
6d885e0c 600class Serveur(models.Model):
b7a741ad 601 """Identification d'un serveur d'ou proviennent les références"""
6d885e0c 602 nom = models.CharField(primary_key = True, max_length = 255)
603
604 def __unicode__(self,):
605 return self.nom
606
607 def conf_2_db(self,):
608 for k in RESOURCES.keys():
609 s, created = Serveur.objects.get_or_create(nom=k)
610 s.nom = k
611 s.save()
612
613class Profile(models.Model):
614 user = models.ForeignKey(User, unique=True)
615 serveurs = models.ManyToManyField(Serveur, null = True, blank = True)
0cc5f772
CR
616
617class HarvestLog(models.Model):
23b5b3d5 618 context = models.CharField(max_length = 255)
619 name = models.CharField(max_length = 255)
0cc5f772 620 date = models.DateTimeField(auto_now = True)
23b5b3d5 621 added = models.IntegerField(null = True, blank = True)
622 updated = models.IntegerField(null = True, blank = True)
a85ba76e 623 processed = models.IntegerField(null = True, blank = True)
23b5b3d5 624 record = models.ForeignKey(Record, null = True, blank = True)
625
626 @staticmethod
627 def add(message):
628 logger = HarvestLog()
629 if message.has_key('record_id'):
d566e9c1 630 message['record'] = Record.all_objects.get(id=message['record_id'])
23b5b3d5 631 del(message['record_id'])
632
633 for k,v in message.items():
634 setattr(logger, k, v)
635 logger.save()