w.c.s. : nouvelle mouture des outils suite à discussions avec Davin
[progfou.git] / wcs / wcs-extract.py
CommitLineData
0f48356a
P
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4import os
5import os.path
a9de62a1
P
6import shutil
7import logging
0f48356a
P
8from time import gmtime, strftime
9import simplejson as json
10
0cd61ae9
P
11from wcs import publisher
12from wcs.formdef import FormDef
13from wcs.fields import TitleField, CommentField, TextField, \
14 StringField, ItemField, EmailField, \
15 DateField, FileField, BoolField
0f48356a 16
0f48356a 17
0cd61ae9
P
18def reduce_to_alnum(s, replacement_char='-'):
19 """réduction d'une chaîne de caractères à de l'alpha-numérique"""
20
0f48356a
P
21 avec_accent = u'çÇáàâÁÀÂéèêëÉÈÊËíìîïÍÌÎÏóòôöÓÒÔÖúùûüÚÙÛÜýỳyÿÝỲYŸ'
22 sans_accent = u'cCaaaAAAeeeeEEEEiiiiIIIIooooOOOOuuuuUUUUyyyyYYYY'
23 if type(s) is not unicode:
24 s = unicode(s, 'utf-8')
25 u = False
26 r = ''
27 for c in s:
28 index = avec_accent.find(c)
29 if index >= 0:
30 r += sans_accent[index]
31 elif ('a' <= c.lower() <= 'z') or ('0' <= c <= '9'):
32 r += c
33 elif len(r) > 0 and r[-1] != replacement_char:
34 r += replacement_char
35 else: # r == '' or r[-1] == replacement_char
36 pass
37 r = r.strip(replacement_char)
38 if not u:
39 r = r.encode('utf-8')
40 return r
41
0f48356a 42
0cd61ae9
P
43def extract_fields(formdef, output_directory):
44 """nommage des champs de façon unique"""
45 # TODO: devrait retourner un résultat, qui serait alors sauvé en dehors
46
36319452
P
47 # XXX: hack temporaire… :-/
48 global field_names
49
0cd61ae9
P
50 f = open(os.path.join(output_directory, 'field-names.txt'), 'w')
51
52 field_names = {}
53 field_names_duplicates = {}
0f48356a 54 for field in formdef.fields:
0f48356a
P
55 if isinstance(field, TitleField) or isinstance(field, CommentField):
56 continue
0cd61ae9
P
57 name = reduce_to_alnum(field.label,'_').lower()
58 if name in field_names.values(): # duplicat
59 field_names_duplicates[name] = field_names_duplicates.get(name, 1) + 1
60 name = '%s_%d' % (name, field_names_duplicates[name])
61 field_names.update({field.id: name})
62 print >>f, "%s:%s:%s" % (field.id, field_names[field.id], field.label)
63
0f48356a
P
64 f.close()
65
0cd61ae9
P
66 f = open(os.path.join(output_directory, 'field-names.json'), 'wb')
67 f.write(json.dumps(field_names, ensure_ascii=False))
68 f.close()
69
70
71def extract_data(formdef, output_directory):
72 """extraction des données du formulaire"""
73 # TODO: devrait retourner un résultat, qui serait alors sauvé en dehors
74
75 for object in formdef.data_class().select():
76 result = {
77 'num_dossier': object.id,
78 'wcs_status': object.status,
79 'wcs_workflow_status': object.get_workflow_status().name,
80 'wcs_user_email': object.user.email,
81 'wcs_user_display_name': object.user.display_name,
82 #'wcs_last_modified': strftime('%Y-%m-%d %H:%M:%S', gmtime(object.last_modified())),
83 }
84 qfiles = { }
85 for field in formdef.fields:
86 field_id = str(field.id)
87 if not field_id in object.data:
88 continue
89 if isinstance(field, TitleField) or isinstance(field, CommentField):
90 continue
91 field_name = field_names[field_id]
92 data = object.data.get(field_id)
93 if isinstance(field, StringField) or isinstance(field, TextField) \
94 or isinstance(field, EmailField) or isinstance(field, ItemField):
95 result[field_name] = data
96 elif isinstance(field, BoolField):
97 result[field_name] = (data == 'True')
98 elif isinstance(field, DateField):
99 result[field_name] = strftime('%Y-%m-%d', data)
100 elif isinstance(field, FileField):
101 extension = data.orig_filename.rpartition('.')[2].lower()
102 result[field_name] = "%s.%s" % (field_name, extension)
103 qfiles[field_name] = data.qfilename
104 else:
a9de62a1
P
105 logging.error("Type de champ inconnu '%s' pour '%s'.",
106 field.__class__.__name__, field.label)
0cd61ae9
P
107 raise RuntimeError
108
109 num_dossier = result['num_dossier']
110 nom = reduce_to_alnum(result['nom']).upper()
111 prenom = reduce_to_alnum(result['prenom']).upper()
112 adel = result['adresse_electronique'].replace('@','-').lower()
113
114 filename = "%04d-%s-%s-%s" % (num_dossier, nom, prenom, adel)
115
0cd61ae9
P
116 # copie des fichiers joints
117 for f in qfiles:
118 result[f] = filename + '_' + result[f]
119 src = os.path.join(pub.app_dir, 'uploads', qfiles[f])
a9de62a1 120 dst = os.path.join(output_directory, 'data', result[f])
0cd61ae9 121 if not os.path.exists(dst) or os.path.getmtime(src) > os.path.getmtime(dst):
a9de62a1 122 shutil.copy2(src, dst)
0cd61ae9
P
123 os.chmod(dst, 0644)
124
125 # génération du fichier JSON
a9de62a1
P
126 jsonname = os.path.join(output_directory, 'data', filename + '.json')
127 f = open(jsonname, 'wb')
0cd61ae9
P
128 f.write(json.dumps(result, ensure_ascii=False))
129 f.close()
130
a9de62a1
P
131 logging.info("Dossier '%s' : %s.",
132 filename, result['wcs_workflow_status'])
0cd61ae9
P
133
134
135if __name__ == '__main__':
136 import sys
137
138 if len(sys.argv) != 4:
139 print >>sys.stderr, "Usage : %s <dossier-destination> <site> <formulaire>" % sys.argv[0]
140 sys.exit(1)
141
142 VHOST = sys.argv[2]
143 FORM_NAME = sys.argv[3]
144 OUTPUT_DIRECTORY = os.path.join(sys.argv[1], VHOST, FORM_NAME)
145
146 os.umask(0022)
147 # création du dossier d'extraction, au besoin
148 if not os.path.isdir(OUTPUT_DIRECTORY):
149 os.makedirs(OUTPUT_DIRECTORY, 0755)
150
a9de62a1
P
151 logging.basicConfig(level=logging.DEBUG,
152 format='%(asctime)s %(levelname)s %(message)s',
153 filename=os.path.join(OUTPUT_DIRECTORY, 'last-run.log'),
154 filemode='w')
155
156 logging.info('Début.')
157
0cd61ae9
P
158 pub = publisher.WcsPublisher.create_publisher()
159 pub.app_dir = os.path.join(pub.app_dir, VHOST)
160
161 formdef = FormDef.get_by_urlname(FORM_NAME)
162
163 extract_fields(formdef, OUTPUT_DIRECTORY)
164
165 extract_data(formdef, OUTPUT_DIRECTORY)
166
a9de62a1 167 logging.info('Fin.')
0f48356a 168