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