wcs-dynexport: on renomme aussi le fichier joint indiqué dans le dossier
[progfou.git] / wcs / wcs-extract
CommitLineData
0f48356a
P
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
edf3eba0
P
3"""
4Outil d'export de données w.c.s.
0f48356a 5
edf3eba0
P
6Copyright : Agence universitaire de la Francophonie — www.auf.org
7Licence : GNU General Public Licence, version 2
8Auteur : Jean Christophe André
9Date de création : 15 octobre 2009
10
11Depends: wcs, python-simplejson, python-magic
12"""
0f48356a
P
13import os
14import os.path
a9de62a1
P
15import shutil
16import logging
abdb4a8c 17from time import gmtime, strftime, struct_time
0f48356a 18import simplejson as json
edf3eba0
P
19import magic
20import mimetypes
abdb4a8c 21import unicodedata
0f48356a 22
0cd61ae9
P
23from wcs import publisher
24from wcs.formdef import FormDef
25from wcs.fields import TitleField, CommentField, TextField, \
ee4d6a09 26 StringField, ItemField, ItemsField, EmailField, \
d3a019f6 27 DateField, FileField, BoolField, TableField
0f48356a 28
0f48356a 29
0cd61ae9
P
30def reduce_to_alnum(s, replacement_char='-'):
31 """réduction d'une chaîne de caractères à de l'alpha-numérique"""
32
0f48356a
P
33 if type(s) is not unicode:
34 s = unicode(s, 'utf-8')
abdb4a8c 35 s = unicodedata.normalize('NFKD', s).encode('ASCII', 'ignore')
0f48356a
P
36 r = ''
37 for c in s:
abdb4a8c 38 if ('a' <= c.lower() <= 'z') or ('0' <= c <= '9'):
0f48356a
P
39 r += c
40 elif len(r) > 0 and r[-1] != replacement_char:
41 r += replacement_char
42 else: # r == '' or r[-1] == replacement_char
43 pass
abdb4a8c 44 return r.strip(replacement_char)
0f48356a 45
0f48356a 46
0cd61ae9
P
47def extract_fields(formdef, output_directory):
48 """nommage des champs de façon unique"""
49 # TODO: devrait retourner un résultat, qui serait alors sauvé en dehors
50
36319452
P
51 # XXX: hack temporaire… :-/
52 global field_names
53
0cd61ae9
P
54 f = open(os.path.join(output_directory, 'field-names.txt'), 'w')
55
56 field_names = {}
57 field_names_duplicates = {}
0f48356a 58 for field in formdef.fields:
0f48356a
P
59 if isinstance(field, TitleField) or isinstance(field, CommentField):
60 continue
fa3aa24e
P
61 if field.varname:
62 name = field.varname
63 else:
64 name = reduce_to_alnum(field.label,'_').lower()
0cd61ae9
P
65 if name in field_names.values(): # duplicat
66 field_names_duplicates[name] = field_names_duplicates.get(name, 1) + 1
67 name = '%s_%d' % (name, field_names_duplicates[name])
68 field_names.update({field.id: name})
69 print >>f, "%s:%s:%s" % (field.id, field_names[field.id], field.label)
70
0f48356a
P
71 f.close()
72
0cd61ae9 73 f = open(os.path.join(output_directory, 'field-names.json'), 'wb')
47d9d835 74 f.write(json.dumps(field_names, ensure_ascii=False))
0cd61ae9
P
75 f.close()
76
77
78def extract_data(formdef, output_directory):
79 """extraction des données du formulaire"""
80 # TODO: devrait retourner un résultat, qui serait alors sauvé en dehors
81
e80345a7
P
82 # XXX: hack temporaire… :-/
83 global pub
84
edf3eba0
P
85 # on charge la base des types MIME une fois pour toutes
86 #magicmime = magic.Magic(mime=True) => ce sera pour plus tard…
6244020f 87 magicmime = magic.open(magic.MAGIC_MIME)
dffcfa61 88 magicmime.load()
edf3eba0 89
2e14236b 90 liste_dossiers = []
0cd61ae9 91 for object in formdef.data_class().select():
9d424de0
P
92 if object.user is None:
93 logging.warning("Dossier '%s' sans utilisateur associé ?!?"\
94 " On ignore...", object.id)
95 continue
96
0cd61ae9
P
97 result = {
98 'num_dossier': object.id,
99 'wcs_status': object.status,
fa3aa24e
P
100 'wcs_workflow_status': (object.status.startswith('wf-') and \
101 object.get_workflow_status().name or None),
0cd61ae9
P
102 'wcs_user_email': object.user.email,
103 'wcs_user_display_name': object.user.display_name,
104 #'wcs_last_modified': strftime('%Y-%m-%d %H:%M:%S', gmtime(object.last_modified())),
e80345a7 105 'wcs_comments': [],
0cd61ae9 106 }
e80345a7
P
107
108 if object.evolution is not None:
109 for e in object.evolution:
110 if e.comment is not None:
111 who = pub.user_class.get(e.who).display_name
112 time = strftime('%Y-%m-%d %H:%M:%S', e.time)
113 comment = '%s -- %s %s' % (e.comment, who, time)
114 result['wcs_comments'].append(comment)
115
0cd61ae9
P
116 qfiles = { }
117 for field in formdef.fields:
118 field_id = str(field.id)
119 if not field_id in object.data:
120 continue
121 if isinstance(field, TitleField) or isinstance(field, CommentField):
122 continue
123 field_name = field_names[field_id]
124 data = object.data.get(field_id)
ee4d6a09
P
125 if data is None:
126 result[field_name] = None
127 continue
0cd61ae9
P
128 if isinstance(field, StringField) or isinstance(field, TextField) \
129 or isinstance(field, EmailField) or isinstance(field, ItemField):
130 result[field_name] = data
d3a019f6 131 elif isinstance(field, ItemsField) or isinstance(field, TableField):
ee4d6a09 132 result[field_name] = data # liste => peux-être joindre sur ';'
0cd61ae9
P
133 elif isinstance(field, BoolField):
134 result[field_name] = (data == 'True')
135 elif isinstance(field, DateField):
abdb4a8c 136 if isinstance(data, struct_time):
e2f76bef 137 result[field_name] = '%04d-%02d-%02d' % (data.tm_year,
b182779a 138 data.tm_mon, data.tm_mday)
e2f76bef
P
139 else:
140 result[field_name] = data
791f9873 141 elif isinstance(field, FileField):
edf3eba0
P
142 if '.' in data.orig_filename:
143 extension = data.orig_filename.rpartition('.')[2].lower()
144 else: # il n'y a pas d'extension dans le nom de fichier
145 p = os.path.join(pub.app_dir, 'uploads', data.qfilename)
474e5135
P
146 try:
147 #m = magicmime.from_file(p) => ce sera pour plus tard…
148 m = magicmime.file(p).split()[0].strip(';')
149 extension = mimetypes.guess_extension(m)
150 except:
151 logging.warning("Type de fichier inconnu pour '%s'.", p)
152 extension = None
edf3eba0
P
153 if extension is not None:
154 extension = extension[1:]
155 else:
156 extension = 'unknown'
0cd61ae9
P
157 result[field_name] = "%s.%s" % (field_name, extension)
158 qfiles[field_name] = data.qfilename
159 else:
d3a019f6
P
160 logging.warning("Type de champ inconnu '%s' pour '%s' (%s).",
161 field.__class__.__name__, field_name, field.label)
0cd61ae9
P
162
163 num_dossier = result['num_dossier']
fa3aa24e
P
164 nom = reduce_to_alnum(result.get('nom','sans-nom')).upper()
165 prenom = reduce_to_alnum(result.get('prenom','sans-prenom')).upper()
166 adel = result.get('adresse_electronique','sans-adel').replace('@','-').lower()
0cd61ae9
P
167
168 filename = "%04d-%s-%s-%s" % (num_dossier, nom, prenom, adel)
2e14236b 169 liste_dossiers.append(filename + '.json')
0cd61ae9 170
0cd61ae9
P
171 # copie des fichiers joints
172 for f in qfiles:
173 result[f] = filename + '_' + result[f]
174 src = os.path.join(pub.app_dir, 'uploads', qfiles[f])
a9de62a1 175 dst = os.path.join(output_directory, 'data', result[f])
0cd61ae9 176 if not os.path.exists(dst) or os.path.getmtime(src) > os.path.getmtime(dst):
a9de62a1 177 shutil.copy2(src, dst)
0cd61ae9
P
178 os.chmod(dst, 0644)
179
180 # génération du fichier JSON
a9de62a1
P
181 jsonname = os.path.join(output_directory, 'data', filename + '.json')
182 f = open(jsonname, 'wb')
fa3aa24e 183 f.write(json.dumps(result, ensure_ascii=False).encode('utf-8'))
0cd61ae9
P
184 f.close()
185
a9de62a1
P
186 logging.info("Dossier '%s' : %s.",
187 filename, result['wcs_workflow_status'])
0cd61ae9 188
b35749bb 189 liste_dossiers.sort()
2e14236b 190 f = open(os.path.join(output_directory, 'liste-dossiers.json'), 'wb')
b35749bb 191 f.write(json.dumps(liste_dossiers, ensure_ascii=False))
2e14236b
P
192 f.close()
193
0cd61ae9
P
194
195if __name__ == '__main__':
196 import sys
197
198 if len(sys.argv) != 4:
199 print >>sys.stderr, "Usage : %s <dossier-destination> <site> <formulaire>" % sys.argv[0]
200 sys.exit(1)
201
202 VHOST = sys.argv[2]
203 FORM_NAME = sys.argv[3]
204 OUTPUT_DIRECTORY = os.path.join(sys.argv[1], VHOST, FORM_NAME)
205
206 os.umask(0022)
207 # création du dossier d'extraction, au besoin
9d424de0
P
208 if not os.path.isdir(os.path.join(OUTPUT_DIRECTORY, 'data')):
209 os.makedirs(os.path.join(OUTPUT_DIRECTORY, 'data'), 0755)
0cd61ae9 210
a9de62a1
P
211 logging.basicConfig(level=logging.DEBUG,
212 format='%(asctime)s %(levelname)s %(message)s',
213 filename=os.path.join(OUTPUT_DIRECTORY, 'last-run.log'),
214 filemode='w')
215
216 logging.info('Début.')
217
0cd61ae9
P
218 pub = publisher.WcsPublisher.create_publisher()
219 pub.app_dir = os.path.join(pub.app_dir, VHOST)
220
221 formdef = FormDef.get_by_urlname(FORM_NAME)
222
223 extract_fields(formdef, OUTPUT_DIRECTORY)
224
b182779a
P
225 try:
226 extract_data(formdef, OUTPUT_DIRECTORY)
227 except:
228 logging.exception("Interruption du traitement pour cause d'erreur !")
0cd61ae9 229
a9de62a1 230 logging.info('Fin.')
0f48356a 231