d042724db0254ce4fdb1d51d70220788d431b826
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / savoirs / models.py
1 # -*- encoding: utf-8 -*-
2 from django.contrib.auth.models import User
3 from django.db import models
4 from django.db.models.signals import post_save
5 import simplejson
6 import uuid, datetime
7 from timezones.fields import TimeZoneField
8 from auf_savoirs_en_partage.backend_config import RESOURCES
9 from savoirs.globals import META
10 from datamaster_modeles.models import Thematique, Pays, Region
11
12 class Discipline(models.Model):
13 id = models.IntegerField(primary_key=True, db_column='id_discipline')
14 nom = models.CharField(max_length=765, db_column='nom_discipline')
15
16 def __unicode__ (self):
17 return self.nom
18
19 class Meta:
20 db_table = u'discipline'
21 ordering = ["nom",]
22
23 class SourceActualite(models.Model):
24 nom = models.CharField(max_length=255)
25 url = models.CharField(max_length=255)
26
27 def __unicode__(self,):
28 return u"%s" % self.nom
29
30 class Actualite(models.Model):
31 id = models.AutoField(primary_key=True, db_column='id_actualite')
32 titre = models.CharField(max_length=765, db_column='titre_actualite')
33 texte = models.TextField(db_column='texte_actualite')
34 url = models.CharField(max_length=765, db_column='url_actualite')
35 date = models.DateField(db_column='date_actualite')
36 visible = models.BooleanField(db_column='visible_actualite', default = False)
37 ancienid = models.IntegerField(db_column='ancienId_actualite', blank = True, null = True)
38 source = models.ForeignKey(SourceActualite, blank = True, null = True)
39
40 def __unicode__ (self):
41 return "%s" % (self.titre)
42
43 class Meta:
44 db_table = u'actualite'
45 ordering = ["-date",]
46
47
48 class ActiveManager(models.Manager):
49 def get_query_set(self):
50 return super(ActiveManager, self).get_query_set().filter(actif=True)
51
52 class Evenement(models.Model):
53 actif = models.BooleanField(default = True)
54 uid = models.CharField(max_length = 255, default = uuid.uuid1)
55 approuve = models.BooleanField(default = False)
56 titre = models.CharField(max_length=255)
57 discipline = models.ForeignKey('Discipline', related_name = "discipline",
58 blank = True, null = True)
59 discipline_secondaire = models.ForeignKey('Discipline', related_name = \
60 "discipline_secondaire",
61 verbose_name = \
62 "Discipline secondaire",
63 blank = True, null = True)
64 mots_cles = models.TextField('Mots-Clés', blank = True, null = True)
65 type = models.CharField(max_length = 255, choices = \
66 (('Colloque', 'Colloque'),
67 ('Conférence', 'Conférence'),
68 ('Appel à contribution', 'Appel à contribution'),
69 ('Journée d\'étude', 'Journée d\'étude'),
70 (None, 'Autre')
71 )) #TODO: choices
72 fuseau = TimeZoneField(verbose_name = 'Fuseau horaire')
73 debut = models.DateTimeField(default = datetime.datetime.now)
74 fin = models.DateTimeField(default = datetime.datetime.now)
75 lieu = models.TextField()
76 description = models.TextField(blank = True, null = True)
77 #fichiers = TODO?
78 contact = models.TextField(blank = True, null = True)
79 url = models.CharField(max_length=255, blank = True, null = True)
80
81 objects = ActiveManager()
82
83 def __unicode__(self,):
84 return "[%s] %s" % (self.uid, self.titre)
85
86 class ListSet(models.Model):
87 spec = models.CharField(primary_key = True, max_length = 255)
88 name = models.CharField(max_length = 255)
89 server = models.CharField(max_length = 255)
90 validated = models.BooleanField(default = True)
91
92 def __unicode__(self,):
93 return self.name
94
95 class Record(models.Model):
96
97 #fonctionnement interne
98 id = models.AutoField(primary_key = True)
99 server = models.CharField(max_length = 255)
100 last_update = models.CharField(max_length = 255)
101 last_checksum = models.CharField(max_length = 255)
102 validated = models.BooleanField(default = True)
103
104 #OAI
105 title = models.TextField(null = True, blank = True)
106 creator = models.TextField(null = True, blank = True)
107 description = models.TextField(null = True, blank = True)
108 modified = models.CharField(max_length = 255, null = True, blank = True)
109 identifier = models.CharField(max_length = 255, null = True, blank = True, unique = True)
110 uri = models.CharField(max_length = 255, null = True, blank = True, unique = True)
111 source = models.TextField(null = True, blank = True)
112 contributor = models.TextField(null = True, blank = True)
113 subject = models.TextField(null = True, blank = True)
114 publisher = models.TextField(null = True, blank = True)
115 type = models.TextField(null = True, blank = True)
116 format = models.TextField(null = True, blank = True)
117 language = models.TextField(null = True, blank = True)
118
119 listsets = models.ManyToManyField(ListSet, null = True, blank = True)
120
121 #SEP 2 (aucune données récoltées)
122 alt_title = models.TextField(null = True, blank = True)
123 abstract = models.TextField(null = True, blank = True)
124 creation = models.CharField(max_length = 255, null = True, blank = True)
125 issued = models.CharField(max_length = 255, null = True, blank = True)
126 isbn = models.TextField(null = True, blank = True)
127 orig_lang = models.TextField(null = True, blank = True)
128
129 # Metadata AUF multivaluées
130 disciplines = models.ManyToManyField(Discipline)
131 thematiques = models.ManyToManyField(Thematique)
132 pays = models.ManyToManyField(Pays)
133 regions = models.ManyToManyField(Region)
134
135 def est_complet(self,):
136 """teste si le record à toutes les données obligatoires"""
137 return self.disciplines.count() > 0 and \
138 self.thematiques.count() > 0 and \
139 self.pays.count() > 0 and \
140 self.regions.count() > 0
141
142
143 def __unicode__(self):
144 return "[%s] %s" % (self.server, self.title)
145
146 # Ces fonctions sont utilisées pour travailler directement sur les données JSON enregistrées tel quel
147 # sur la base de données. Lorsque le modèle est initialisé, les fields sont décodés, et lorsque l'objet
148 # est sauvegardé, on s'assure de remettre les données encodées en JSON.
149 # TODO : a terme, les données ne seront plus stockées au format JSON dans la BD et ces fonctions seront
150 # donc obsolètes.
151 #
152 # def save(self, *args, **kwargs):
153 #
154 # for field_name in [f for f in self._meta.get_all_field_names() if f in META.keys()]:
155 # v = getattr (self, field_name, None)
156 # setattr(self, field_name, simplejson.dumps(v))
157 #
158 # super(Record, self).save(*args, **kwargs)
159 #
160 #def decode_json(instance, **kwargs):
161 # for field_name in [f for f in instance._meta.get_all_field_names() if f in META.keys()]:
162 # json = getattr(instance, field_name)
163 # data = "-"
164 # v = getattr (instance, field_name, None)
165 # if v is not None:
166 # data = simplejson.loads(v)
167 # if not isinstance(data, basestring):
168 # decoded_value = u",".join(data)
169 # else:
170 # decoded_value = data
171 # setattr(instance, field_name, decoded_value)
172 #
173 #models.signals.post_init.connect(decode_json, Record)
174
175 class Serveur(models.Model):
176 nom = models.CharField(primary_key = True, max_length = 255)
177
178 def __unicode__(self,):
179 return self.nom
180
181 def conf_2_db(self,):
182 for k in RESOURCES.keys():
183 s, created = Serveur.objects.get_or_create(nom=k)
184 s.nom = k
185 s.save()
186
187 class Profile(models.Model):
188 user = models.ForeignKey(User, unique=True)
189 serveurs = models.ManyToManyField(Serveur, null = True, blank = True)
190
191 class HarvestLog(models.Model):
192 context = models.CharField(max_length = 255)
193 name = models.CharField(max_length = 255)
194 date = models.DateTimeField(auto_now = True)
195 added = models.IntegerField(null = True, blank = True)
196 updated = models.IntegerField(null = True, blank = True)
197 processed = models.IntegerField(null = True, blank = True)
198 record = models.ForeignKey(Record, null = True, blank = True)
199
200 @staticmethod
201 def add(message):
202 logger = HarvestLog()
203 if message.has_key('record_id'):
204 message['record'] = Record.objects.get(id=message['record_id'])
205 del(message['record_id'])
206
207 for k,v in message.items():
208 setattr(logger, k, v)
209 logger.save()