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