e228634f01a8567cd19065ccbe66c7a785b32a47
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / savoirs / models.py
1 # -*- encoding: utf-8 -*-
2 import simplejson, uuid, datetime, caldav, vobject, uuid
3 from django.contrib.auth.models import User
4 from django.db import models
5 from django.db.models.signals import pre_delete
6 from timezones.fields import TimeZoneField
7 from auf_savoirs_en_partage.backend_config import RESOURCES
8 from savoirs.globals import META
9 from settings import CALENDRIER_URL
10 from datamaster_modeles.models import Thematique, Pays, Region
11 from lib.calendrier import combine
12 from caldav.lib import error
13
14 class Discipline(models.Model):
15 id = models.IntegerField(primary_key=True, db_column='id_discipline')
16 nom = models.CharField(max_length=765, db_column='nom_discipline')
17
18 def __unicode__ (self):
19 return self.nom
20
21 class Meta:
22 db_table = u'discipline'
23 ordering = ["nom",]
24
25 class SourceActualite(models.Model):
26 nom = models.CharField(max_length=255)
27 url = models.CharField(max_length=255)
28
29 def __unicode__(self,):
30 return u"%s" % self.nom
31
32 class ActualiteManager(models.Manager):
33
34 def get_query_set(self):
35 return ActualiteQuerySet(self.model)
36
37 class ActualiteQuerySet(models.query.QuerySet):
38
39 def search(self, text):
40 return self.filter(titre__icontains=text)
41
42 class Actualite(models.Model):
43 id = models.AutoField(primary_key=True, db_column='id_actualite')
44 titre = models.CharField(max_length=765, db_column='titre_actualite')
45 texte = models.TextField(db_column='texte_actualite')
46 url = models.CharField(max_length=765, db_column='url_actualite')
47 date = models.DateField(db_column='date_actualite')
48 visible = models.BooleanField(db_column='visible_actualite', default = False)
49 ancienid = models.IntegerField(db_column='ancienId_actualite', blank = True, null = True)
50 source = models.ForeignKey(SourceActualite, blank = True, null = True)
51
52 objects = ActualiteManager()
53
54 def __unicode__ (self):
55 return "%s" % (self.titre)
56
57 class Meta:
58 db_table = u'actualite'
59 ordering = ["-date",]
60
61 class Evenement(models.Model):
62 uid = models.CharField(max_length = 255, default = str(uuid.uuid1()))
63 approuve = models.BooleanField(default = False)
64 titre = models.CharField(max_length=255)
65 discipline = models.ForeignKey('Discipline', related_name = "discipline",
66 blank = True, null = True)
67 discipline_secondaire = models.ForeignKey('Discipline', related_name = \
68 "discipline_secondaire",
69 verbose_name = \
70 "Discipline secondaire",
71 blank = True, null = True)
72 mots_cles = models.TextField('Mots-Clés', blank = True, null = True)
73 type = models.CharField(max_length = 255, choices = \
74 (('Colloque', 'Colloque'),
75 ('Conférence', 'Conférence'),
76 ('Appel à contribution', 'Appel à contribution'),
77 ('Journée d\'étude', 'Journée d\'étude'),
78 (None, 'Autre')
79 )) #TODO: choices
80 fuseau = TimeZoneField(verbose_name = 'Fuseau horaire')
81 debut = models.DateTimeField(default = datetime.datetime.now)
82 fin = models.DateTimeField(default = datetime.datetime.now)
83 lieu = models.TextField()
84 description = models.TextField(blank = True, null = True)
85 #fichiers = TODO?
86 contact = models.TextField(blank = True, null = True)
87 url = models.CharField(max_length=255, blank = True, null = True)
88
89 def __unicode__(self,):
90 return "[%s] %s" % (self.uid, self.titre)
91
92 def save(self, *args, **kwargs):
93 """Sauvegarde l'objet dans django et le synchronise avec caldav s'il a été
94 approuvé"""
95 self.update_vevent()
96 super(Evenement, self).save(*args, **kwargs)
97
98 # methodes de commnunications avec CALDAV
99 def as_ical(self,):
100 """Retourne l'evenement django sous forme d'objet icalendar"""
101 cal = vobject.iCalendar()
102 cal.add('vevent')
103
104 # fournit son propre uid
105 if self.uid in [None, ""]:
106 self.uid = str(uuid.uuid1())
107
108 cal.vevent.add('uid').value = self.uid
109
110 cal.vevent.add('summary').value = self.titre
111
112 if self.mots_cles is None:
113 kw = []
114 else:
115 kw = self.mots_cles.split(",")
116
117 try:
118 kw.append(self.discipline.nom)
119 kw.append(self.discipline_secondaire.nom)
120 kw.append(self.type)
121 except: pass
122
123 kw = [x.strip() for x in kw if len(x.strip()) > 0 and x is not None]
124 for k in kw:
125 cal.vevent.add('x-auf-keywords').value = k
126
127 description = self.description
128 if len(kw) > 0:
129 if len(self.description) > 0:
130 description += "\n"
131 description += u"Mots-clés: " + ", ".join(kw)
132
133 cal.vevent.add('dtstart').value = combine(self.debut, self.fuseau)
134 cal.vevent.add('dtend').value = combine(self.fin, self.fuseau)
135 cal.vevent.add('created').value = combine(datetime.datetime.now(), "UTC")
136 cal.vevent.add('dtstamp').value = combine(datetime.datetime.now(), "UTC")
137 if len(description) > 0:
138 cal.vevent.add('description').value = description
139 if len(self.contact) > 0:
140 cal.vevent.add('contact').value = self.contact
141 if len(self.url) > 0:
142 cal.vevent.add('url').value = self.url
143 if len(self.lieu) > 0:
144 cal.vevent.add('location').value = self.lieu
145 return cal
146
147 def update_vevent(self,):
148 """Essaie de créer l'évènement sur le serveur ical.
149 En cas de succès, l'évènement local devient donc inactif et approuvé"""
150 try:
151 if self.approuve:
152 event = self.as_ical()
153 client = caldav.DAVClient(CALENDRIER_URL)
154 cal = caldav.Calendar(client, url = CALENDRIER_URL)
155 e = caldav.Event(client, parent = cal, data = event.serialize(), id=self.uid)
156 e.save()
157 except:
158 self.approuve = False
159
160 def delete_vevent(self,):
161 """Supprime l'evenement sur le serveur caldav"""
162 try:
163 if self.approuve:
164 event = self.as_ical()
165 client = caldav.DAVClient(CALENDRIER_URL)
166 cal = caldav.Calendar(client, url = CALENDRIER_URL)
167 e = cal.event(self.uid)
168 e.delete()
169 except error.NotFoundError:
170 pass
171
172
173 # Surcharge du comportement de suppression
174 # La méthode de connexion par signals est préférable à surcharger la méthode delete()
175 # car dans le cas de la suppression par lots, cell-ci n'est pas invoquée
176 def delete_vevent(sender, instance, *args, **kwargs):
177 instance.delete_vevent()
178
179 pre_delete.connect(delete_vevent, sender = Evenement)
180
181
182 class ListSet(models.Model):
183 spec = models.CharField(primary_key = True, max_length = 255)
184 name = models.CharField(max_length = 255)
185 server = models.CharField(max_length = 255)
186 validated = models.BooleanField(default = True)
187
188 def __unicode__(self,):
189 return self.name
190
191 class Record(models.Model):
192
193 #fonctionnement interne
194 id = models.AutoField(primary_key = True)
195 server = models.CharField(max_length = 255)
196 last_update = models.CharField(max_length = 255)
197 last_checksum = models.CharField(max_length = 255)
198 validated = models.BooleanField(default = True)
199
200 #OAI
201 title = models.TextField(null = True, blank = True)
202 creator = models.TextField(null = True, blank = True)
203 description = models.TextField(null = True, blank = True)
204 modified = models.CharField(max_length = 255, null = True, blank = True)
205 identifier = models.CharField(max_length = 255, null = True, blank = True, unique = True)
206 uri = models.CharField(max_length = 255, null = True, blank = True, unique = True)
207 source = models.TextField(null = True, blank = True)
208 contributor = models.TextField(null = True, blank = True)
209 subject = models.TextField(null = True, blank = True)
210 publisher = models.TextField(null = True, blank = True)
211 type = models.TextField(null = True, blank = True)
212 format = models.TextField(null = True, blank = True)
213 language = models.TextField(null = True, blank = True)
214
215 listsets = models.ManyToManyField(ListSet, null = True, blank = True)
216
217 #SEP 2 (aucune données récoltées)
218 alt_title = models.TextField(null = True, blank = True)
219 abstract = models.TextField(null = True, blank = True)
220 creation = models.CharField(max_length = 255, null = True, blank = True)
221 issued = models.CharField(max_length = 255, null = True, blank = True)
222 isbn = models.TextField(null = True, blank = True)
223 orig_lang = models.TextField(null = True, blank = True)
224
225 # Metadata AUF multivaluées
226 disciplines = models.ManyToManyField(Discipline)
227 thematiques = models.ManyToManyField(Thematique)
228 pays = models.ManyToManyField(Pays)
229 regions = models.ManyToManyField(Region)
230
231 def est_complet(self,):
232 """teste si le record à toutes les données obligatoires"""
233 return self.disciplines.count() > 0 and \
234 self.thematiques.count() > 0 and \
235 self.pays.count() > 0 and \
236 self.regions.count() > 0
237
238 def __unicode__(self):
239 return "[%s] %s" % (self.server, self.title)
240
241 class Serveur(models.Model):
242 """Identification d'un serveur d'ou proviennent les références"""
243 nom = models.CharField(primary_key = True, max_length = 255)
244
245 def __unicode__(self,):
246 return self.nom
247
248 def conf_2_db(self,):
249 for k in RESOURCES.keys():
250 s, created = Serveur.objects.get_or_create(nom=k)
251 s.nom = k
252 s.save()
253
254 class Profile(models.Model):
255 user = models.ForeignKey(User, unique=True)
256 serveurs = models.ManyToManyField(Serveur, null = True, blank = True)
257
258 class HarvestLog(models.Model):
259 context = models.CharField(max_length = 255)
260 name = models.CharField(max_length = 255)
261 date = models.DateTimeField(auto_now = True)
262 added = models.IntegerField(null = True, blank = True)
263 updated = models.IntegerField(null = True, blank = True)
264 processed = models.IntegerField(null = True, blank = True)
265 record = models.ForeignKey(Record, null = True, blank = True)
266
267 @staticmethod
268 def add(message):
269 logger = HarvestLog()
270 if message.has_key('record_id'):
271 message['record'] = Record.objects.get(id=message['record_id'])
272 del(message['record_id'])
273
274 for k,v in message.items():
275 setattr(logger, k, v)
276 logger.save()