Ajout de champs régions et disciplines
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / savoirs / models.py
CommitLineData
92c7413b 1# -*- encoding: utf-8 -*-
b7a741ad 2import simplejson, uuid, datetime, caldav, vobject, uuid
6d885e0c 3from django.contrib.auth.models import User
d15017b2 4from django.db import models
f12cc7fb 5from django.db.models import Q
b7a741ad 6from django.db.models.signals import pre_delete
92c7413b 7from timezones.fields import TimeZoneField
6d885e0c 8from auf_savoirs_en_partage.backend_config import RESOURCES
da9020f3 9from savoirs.globals import META
b7a741ad 10from settings import CALENDRIER_URL
e3c3296e 11from datamaster_modeles.models import Thematique, Pays, Region
b7a741ad 12from lib.calendrier import combine
13from caldav.lib import error
d15017b2
CR
14
15class Discipline(models.Model):
16 id = models.IntegerField(primary_key=True, db_column='id_discipline')
17 nom = models.CharField(max_length=765, db_column='nom_discipline')
6ef8ead4
CR
18
19 def __unicode__ (self):
92c7413b 20 return self.nom
6ef8ead4 21
d15017b2
CR
22 class Meta:
23 db_table = u'discipline'
24 ordering = ["nom",]
25
79c398f6
CR
26class SourceActualite(models.Model):
27 nom = models.CharField(max_length=255)
28 url = models.CharField(max_length=255)
ccbc4363 29
30 def __unicode__(self,):
31 return u"%s" % self.nom
79c398f6 32
2f9c4d6c
EMS
33class ActualiteManager(models.Manager):
34
35 def get_query_set(self):
36 return ActualiteQuerySet(self.model)
37
da44ce68
EMS
38 def search(self, text):
39 return self.get_query_set().search(text)
40
2f9c4d6c
EMS
41class ActualiteQuerySet(models.query.QuerySet):
42
43 def search(self, text):
c9cbc784 44 return self.filter(Q(titre__icontains=text) | Q(texte__icontains=text))
2f9c4d6c 45
d15017b2 46class Actualite(models.Model):
4f262f90 47 id = models.AutoField(primary_key=True, db_column='id_actualite')
d15017b2
CR
48 titre = models.CharField(max_length=765, db_column='titre_actualite')
49 texte = models.TextField(db_column='texte_actualite')
50 url = models.CharField(max_length=765, db_column='url_actualite')
d15017b2 51 date = models.DateField(db_column='date_actualite')
f554ef70 52 visible = models.BooleanField(db_column='visible_actualite', default = False)
3b6456b0 53 ancienid = models.IntegerField(db_column='ancienId_actualite', blank = True, null = True)
ccbc4363 54 source = models.ForeignKey(SourceActualite, blank = True, null = True)
3a45eb64
EMS
55 disciplines = models.ManyToManyField(Discipline, blank=True, related_name="actualites")
56 regions = models.ManyToManyField(Region, blank=True, related_name="actualites", verbose_name='Régions')
6ef8ead4 57
2f9c4d6c
EMS
58 objects = ActualiteManager()
59
6ef8ead4 60 def __unicode__ (self):
f554ef70 61 return "%s" % (self.titre)
6ef8ead4 62
d15017b2
CR
63 class Meta:
64 db_table = u'actualite'
65 ordering = ["-date",]
92c7413b 66
4101cfc0
EMS
67class EvenementManager(models.Manager):
68
69 def get_query_set(self):
70 return EvenementQuerySet(self.model)
71
72 def search(self, text):
73 return self.get_query_set().search(text)
74
75class EvenementQuerySet(models.query.QuerySet):
76
77 def search(self, text):
78 qs = self
0b1ddc11
EMS
79 q = None
80 for word in text.split():
81 part = (Q(titre__icontains=word) |
82 Q(mots_cles__icontains=word) |
83 Q(discipline__nom__icontains=word) |
84 Q(discipline_secondaire__nom__icontains=word) |
85 Q(type__icontains=word) |
86 Q(lieu__icontains=word) |
87 Q(description__icontains=word) |
88 Q(contact__icontains=word))
89 if q is None:
90 q = part
91 else:
92 q = q & part
3c23982e 93 return qs.filter(q) if q is not None else qs
4101cfc0 94
7bbf600c
EMS
95 def search_titre(self, text):
96 qs = self
97 for word in text.split():
98 qs = qs.filter(titre__icontains=word)
99 return qs
100
92c7413b 101class Evenement(models.Model):
7bbf600c
EMS
102 TYPE_CHOICES = ((u'Colloque', u'Colloque'),
103 (u'Conférence', u'Conférence'),
104 (u'Appel à contribution', u'Appel à contribution'),
105 (u'Journée d\'étude', u'Journée d\'étude'),
106 (None, u'Autre'))
107
c5b3da8b 108 uid = models.CharField(max_length = 255, default = str(uuid.uuid1()))
92c7413b
CR
109 approuve = models.BooleanField(default = False)
110 titre = models.CharField(max_length=255)
111 discipline = models.ForeignKey('Discipline', related_name = "discipline",
112 blank = True, null = True)
113 discipline_secondaire = models.ForeignKey('Discipline', related_name = \
114 "discipline_secondaire",
115 verbose_name = \
116 "Discipline secondaire",
117 blank = True, null = True)
118 mots_cles = models.TextField('Mots-Clés', blank = True, null = True)
7bbf600c 119 type = models.CharField(max_length=255, choices=TYPE_CHOICES)
92c7413b
CR
120 fuseau = TimeZoneField(verbose_name = 'Fuseau horaire')
121 debut = models.DateTimeField(default = datetime.datetime.now)
122 fin = models.DateTimeField(default = datetime.datetime.now)
123 lieu = models.TextField()
124 description = models.TextField(blank = True, null = True)
125 #fichiers = TODO?
126 contact = models.TextField(blank = True, null = True)
127 url = models.CharField(max_length=255, blank = True, null = True)
3a45eb64 128 regions = models.ManyToManyField(Region, blank=True, related_name="evenements", verbose_name='Régions')
92c7413b 129
4101cfc0
EMS
130 objects = EvenementManager()
131
132 class Meta:
133 ordering = ['-debut']
134
020f79a9 135 def __unicode__(self,):
136 return "[%s] %s" % (self.uid, self.titre)
137
73309469 138 def clean(self):
139 from django.core.exceptions import ValidationError
140 if self.debut > self.fin:
141 raise ValidationError('La date de fin ne doit pas être antérieure à la date de début')
142
b7a741ad 143 def save(self, *args, **kwargs):
144 """Sauvegarde l'objet dans django et le synchronise avec caldav s'il a été
145 approuvé"""
73309469 146 self.clean()
b7a741ad 147 self.update_vevent()
148 super(Evenement, self).save(*args, **kwargs)
149
150 # methodes de commnunications avec CALDAV
151 def as_ical(self,):
152 """Retourne l'evenement django sous forme d'objet icalendar"""
153 cal = vobject.iCalendar()
154 cal.add('vevent')
155
156 # fournit son propre uid
7f56d0d4 157 if self.uid in [None, ""]:
b7a741ad 158 self.uid = str(uuid.uuid1())
159
160 cal.vevent.add('uid').value = self.uid
161
162 cal.vevent.add('summary').value = self.titre
163
164 if self.mots_cles is None:
165 kw = []
166 else:
167 kw = self.mots_cles.split(",")
168
169 try:
170 kw.append(self.discipline.nom)
171 kw.append(self.discipline_secondaire.nom)
172 kw.append(self.type)
173 except: pass
174
79b400f0 175 kw = [x.strip() for x in kw if len(x.strip()) > 0 and x is not None]
b7a741ad 176 for k in kw:
177 cal.vevent.add('x-auf-keywords').value = k
178
179 description = self.description
180 if len(kw) > 0:
181 if len(self.description) > 0:
182 description += "\n"
028f548f 183 description += u"Mots-clés: " + ", ".join(kw)
b7a741ad 184
185 cal.vevent.add('dtstart').value = combine(self.debut, self.fuseau)
186 cal.vevent.add('dtend').value = combine(self.fin, self.fuseau)
187 cal.vevent.add('created').value = combine(datetime.datetime.now(), "UTC")
188 cal.vevent.add('dtstamp').value = combine(datetime.datetime.now(), "UTC")
79b400f0 189 if len(description) > 0:
b7a741ad 190 cal.vevent.add('description').value = description
191 if len(self.contact) > 0:
192 cal.vevent.add('contact').value = self.contact
193 if len(self.url) > 0:
194 cal.vevent.add('url').value = self.url
195 if len(self.lieu) > 0:
196 cal.vevent.add('location').value = self.lieu
197 return cal
198
199 def update_vevent(self,):
200 """Essaie de créer l'évènement sur le serveur ical.
201 En cas de succès, l'évènement local devient donc inactif et approuvé"""
202 try:
203 if self.approuve:
204 event = self.as_ical()
205 client = caldav.DAVClient(CALENDRIER_URL)
206 cal = caldav.Calendar(client, url = CALENDRIER_URL)
207 e = caldav.Event(client, parent = cal, data = event.serialize(), id=self.uid)
208 e.save()
209 except:
210 self.approuve = False
211
212 def delete_vevent(self,):
213 """Supprime l'evenement sur le serveur caldav"""
214 try:
215 if self.approuve:
216 event = self.as_ical()
217 client = caldav.DAVClient(CALENDRIER_URL)
218 cal = caldav.Calendar(client, url = CALENDRIER_URL)
219 e = cal.event(self.uid)
220 e.delete()
221 except error.NotFoundError:
222 pass
223
224
225# Surcharge du comportement de suppression
226# La méthode de connexion par signals est préférable à surcharger la méthode delete()
227# car dans le cas de la suppression par lots, cell-ci n'est pas invoquée
228def delete_vevent(sender, instance, *args, **kwargs):
229 instance.delete_vevent()
230
231pre_delete.connect(delete_vevent, sender = Evenement)
232
233
d972b61d 234class ListSet(models.Model):
235 spec = models.CharField(primary_key = True, max_length = 255)
236 name = models.CharField(max_length = 255)
237 server = models.CharField(max_length = 255)
9eda5d6c 238 validated = models.BooleanField(default = True)
d972b61d 239
10d37e44 240 def __unicode__(self,):
241 return self.name
242
da44ce68
EMS
243class RecordManager(models.Manager):
244
245 def get_query_set(self):
246 return RecordQuerySet(self.model)
247
248 def search(self, text):
249 return self.get_query_set().search(text)
250
f153be1b
EMS
251 def validated(self):
252 return self.get_query_set().validated()
253
da44ce68
EMS
254class RecordQuerySet(models.query.QuerySet):
255
256 def search(self, text):
f12cc7fb 257 qs = self
da44ce68 258 words = text.split()
da44ce68 259
f12cc7fb
EMS
260 # Ne garder que les ressources qui contiennent tous les mots
261 # demandés.
0b1ddc11 262 q = None
f12cc7fb 263 for word in words:
0b1ddc11
EMS
264 part = (Q(title__icontains=word) | Q(description__icontains=word) |
265 Q(creator__icontains=word) | Q(contributor__icontains=word) |
266 Q(subject__icontains=word) | Q(disciplines__nom__icontains=word) |
ad0600bc 267 Q(regions__nom__icontains=word) | Q(pays__nom__icontains=word))
0b1ddc11
EMS
268 if q is None:
269 q = part
270 else:
271 q = q & part
3c23982e
EMS
272 if q is not None:
273 qs = qs.filter(q).distinct()
f12cc7fb
EMS
274
275 # On donne un point pour chaque mot présent dans le titre.
3c23982e
EMS
276 if words:
277 score_expr = ' + '.join(['(title LIKE %s)'] * len(words))
278 score_params = ['%' + word + '%' for word in words]
279 qs = qs.extra(
280 select={'score': score_expr},
281 select_params=score_params
282 ).order_by('-score')
283
284 return qs
f12cc7fb
EMS
285
286 def search_auteur(self, text):
287 qs = self
288 for word in text.split():
289 qs = qs.filter(Q(creator__icontains=word) | Q(contributor__icontains=word))
290 return qs
291
292 def search_sujet(self, text):
293 qs = self
294 for word in text.split():
295 qs = qs.filter(subject__icontains=word)
296 return qs
297
298 def search_titre(self, text):
299 qs = self
300 for word in text.split():
301 qs = qs.filter(title__icontains=word)
302 return qs
303
f153be1b
EMS
304 def validated(self):
305 """Ne garder que les ressources validées et qui sont soit dans aucun
306 listset ou au moins dans un listset validé."""
307 qs = self.filter(validated=True)
308 qs = qs.extra(where=['''((savoirs_record.id NOT IN (SELECT record_id FROM savoirs_record_listsets)) OR
309 ((SELECT MAX(l.validated) FROM savoirs_listset l
310 INNER JOIN savoirs_record_listsets rl ON rl.listset_id = l.spec
311 WHERE rl.record_id = savoirs_record.id) = TRUE))'''])
312 return qs
313
0cc5f772 314class Record(models.Model):
23b5b3d5 315
316 #fonctionnement interne
0cc5f772 317 id = models.AutoField(primary_key = True)
23b5b3d5 318 server = models.CharField(max_length = 255)
319 last_update = models.CharField(max_length = 255)
320 last_checksum = models.CharField(max_length = 255)
c88d78dc 321 validated = models.BooleanField(default = True)
23b5b3d5 322
323 #OAI
324 title = models.TextField(null = True, blank = True)
325 creator = models.TextField(null = True, blank = True)
326 description = models.TextField(null = True, blank = True)
327 modified = models.CharField(max_length = 255, null = True, blank = True)
328 identifier = models.CharField(max_length = 255, null = True, blank = True, unique = True)
329 uri = models.CharField(max_length = 255, null = True, blank = True, unique = True)
330 source = models.TextField(null = True, blank = True)
331 contributor = models.TextField(null = True, blank = True)
332 subject = models.TextField(null = True, blank = True)
333 publisher = models.TextField(null = True, blank = True)
334 type = models.TextField(null = True, blank = True)
335 format = models.TextField(null = True, blank = True)
336 language = models.TextField(null = True, blank = True)
da9020f3 337
c88d78dc 338 listsets = models.ManyToManyField(ListSet, null = True, blank = True)
d972b61d 339
da9020f3 340 #SEP 2 (aucune données récoltées)
23b5b3d5 341 alt_title = models.TextField(null = True, blank = True)
342 abstract = models.TextField(null = True, blank = True)
343 creation = models.CharField(max_length = 255, null = True, blank = True)
344 issued = models.CharField(max_length = 255, null = True, blank = True)
345 isbn = models.TextField(null = True, blank = True)
346 orig_lang = models.TextField(null = True, blank = True)
da9020f3 347
348 # Metadata AUF multivaluées
349 disciplines = models.ManyToManyField(Discipline)
350 thematiques = models.ManyToManyField(Thematique)
e3c3296e 351 pays = models.ManyToManyField(Pays)
3a45eb64 352 regions = models.ManyToManyField(Region, verbose_name='Régions')
0cc5f772 353
da44ce68
EMS
354 # Manager
355 objects = RecordManager()
356
f98ad449 357 def getServeurURL(self,):
358 """Retourne l'URL du serveur de provenance"""
359 return RESOURCES[self.server]['url']
360
6d885e0c 361 def est_complet(self,):
362 """teste si le record à toutes les données obligatoires"""
363 return self.disciplines.count() > 0 and \
364 self.thematiques.count() > 0 and \
365 self.pays.count() > 0 and \
366 self.regions.count() > 0
367
0cc5f772 368 def __unicode__(self):
f554ef70 369 return "[%s] %s" % (self.server, self.title)
da9020f3 370
6d885e0c 371class Serveur(models.Model):
b7a741ad 372 """Identification d'un serveur d'ou proviennent les références"""
6d885e0c 373 nom = models.CharField(primary_key = True, max_length = 255)
374
375 def __unicode__(self,):
376 return self.nom
377
378 def conf_2_db(self,):
379 for k in RESOURCES.keys():
380 s, created = Serveur.objects.get_or_create(nom=k)
381 s.nom = k
382 s.save()
383
384class Profile(models.Model):
385 user = models.ForeignKey(User, unique=True)
386 serveurs = models.ManyToManyField(Serveur, null = True, blank = True)
0cc5f772
CR
387
388class HarvestLog(models.Model):
23b5b3d5 389 context = models.CharField(max_length = 255)
390 name = models.CharField(max_length = 255)
0cc5f772 391 date = models.DateTimeField(auto_now = True)
23b5b3d5 392 added = models.IntegerField(null = True, blank = True)
393 updated = models.IntegerField(null = True, blank = True)
a85ba76e 394 processed = models.IntegerField(null = True, blank = True)
23b5b3d5 395 record = models.ForeignKey(Record, null = True, blank = True)
396
397 @staticmethod
398 def add(message):
399 logger = HarvestLog()
400 if message.has_key('record_id'):
401 message['record'] = Record.objects.get(id=message['record_id'])
402 del(message['record_id'])
403
404 for k,v in message.items():
405 setattr(logger, k, v)
406 logger.save()