1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
|
# -*- encoding: utf-8 -*-
import time
import json
import os
import shutil
import re
import Image
import base64
from exceptions import *
from bson import ObjectId, DBRef
from django.conf import settings
from django.forms.fields import ImageField
from django.core.exceptions import ValidationError as DjangoValidationError
from django.core.files.uploadedfile import InMemoryUploadedFile
from utils.mongo_connection import get_db
WIDGET_TYPES = (
('TextInput', 'Respuesta en texto'),
('MultipleCheckBox', 'Respuesta con checks (multiple selección)'),
('RadioButton', 'Respuesta con radios (Solo una selección)'),
('DropDownList', 'Respuesta con lista de opciones'),
('ImageCheckBox', 'Respuesta con imagenes tipo checks'),
('ImageRadioButton', 'Respuesta con imagenes tipo radios'),
)
WITH_OPTIONS = [
"MultipleCheckBox",
"DropDownList",
"RadioButton",
"ImageCheckBox",
"ImageRadioButton",
]
WITH_IMAGES = ["ImageCheckBox", "ImageRadioButton"]
class ComponentStructure(ObjectId):
def __init__(self, poll=None, *args, **kwargs):
super(ComponentStructure, self).__init__(*args, **kwargs)
self.poll = poll
class AbstracErrorObject(object):
ValidationError = ValidationError
errors = []
dict_errors = {}
class Poll(AbstracErrorObject):
collection_name = 'polls'
UniqueNameError = UniqueNameError
OPEN = "Abierta"
CLOSED = "Cerrada"
def __init__(self, data={}, *args, **kwargs):
super(Poll, self).__init__(*args, **kwargs)
self.id = None
_id = data.get('id', None) or data.get('_id', None)
if _id and (isinstance(_id, str) or isinstance(_id, unicode)):
self.id = ObjectId(_id)
elif _id and isinstance(_id, ObjectId):
self.id = _id
self.name = data.get('name', None)
self.status = data.get('status', Poll.OPEN)
@property
def structure(self):
structure_data = get_db().structures.find_one(
{'poll.$id': self.id})
structure_data = structure_data if structure_data else {}
return Structure(data=structure_data, poll=self)
@staticmethod
def status_choices():
return (
(Poll.OPEN, 'Abierta'),
(Poll.CLOSED, 'Cerrada'),
)
def is_open(self):
return self.status == Poll.OPEN
def to_dict(self):
_dict = {}
if self.id:
_dict.update({'_id': self.id})
if self.name:
_dict.update({'name': self.name})
if self.status:
_dict.update({'status': self.status})
return _dict
def validate(self):
self.errors = []
if not self.name:
msg = "Necesita ingresar un nombre de encuesta."
self.errors.append(msg)
else:
# Check unique name key, Important !!!
existing = get_db().polls.find_one(
{'name': re.compile("^%s$" % self.name, re.IGNORECASE)})
if existing and existing.get("_id", None) != self.id:
msg = u"Poll name '%s' already in use." % self.name
self.errors.append(msg)
raise Poll.ValidationError(msg)
if len(self.errors):
raise Poll.ValidationError(str(self.errors))
def save(self):
self.validate()
poll_id = None
poll_id = get_db().polls.save(self.to_dict())
return poll_id
@staticmethod
def get(id=None):
poll = None
objects = get_db().polls.find({'_id': ObjectId(id)})
if objects.count():
obj = objects[0]
poll = Poll(obj)
return poll
# TODO: Test
@staticmethod
def all(*args, **kwargs):
_all = []
for poll_data in get_db().polls.find(**kwargs):
_all.append(Poll(poll_data))
return _all
def to_json(self):
structure_data = get_db().structures.find_one(
{'poll.$id': self.id}, fields={'poll': False})
structure = Structure(structure_data, poll=self)
_json = json.dumps(
structure.to_python(with_errors=False, img_serialize=True),
sort_keys=True,
indent=4,
separators=(',', ': '),
ensure_ascii=False
)
return _json
class AbstractObject(AbstracErrorObject):
@staticmethod
def get_offset_id():
return int(time.time() * 1000)
class Option(AbstractObject, ComponentStructure):
def __init__(self, data={}, *args, **kwargs):
super(Option, self).__init__(*args, **kwargs)
self.id = data.get('id', None)
self.text = data.get('text', None)
self.img = data.get('img', None)
self.img_name = data.get('img_name', None)
weight = data.get('weight', None)
self.weight = int(weight) if weight else weight
if not self.img_name and isinstance(self.img, InMemoryUploadedFile):
fileExtension = os.path.splitext(self.img.name)[1]
self.img_name = '%s%s' % (self.id, fileExtension)
def get_absolute_path(self):
return "%s/%s/%s" % (
settings.IMAGE_OPTIONS_ROOT, str(self.poll.id), self.img_name
)
def validate(self):
self.dict_errors = {}
self.errors = []
if self.img and isinstance(self.img, InMemoryUploadedFile):
try:
img = ImageField().to_python(self.img)
except DjangoValidationError, e:
self.dict_errors.update(
{'img': '%s: %s' % (self.img.name, e.messages[0])})
else:
width, height = Image.open(img).size
if width > 250 or height > 250:
msg = u"Se necesita una imagen menor a 250x250."
self.dict_errors.update(
{'img': '%s: %s' % (self.id, msg)})
if 'img' in self.dict_errors.keys():
self.img_name = None
self.img = None
else:
self.img.seek(0)
if self.weight is None or self.weight == '':
msg = u"opcion %s: ponderación requerida." % self.id
self.dict_errors.update({'weight': msg})
self.errors = self.dict_errors.values()
if len(self.errors):
raise Option.ValidationError(str(self.errors))
def to_python(self, with_errors=False, img_serialize=False):
data = {'%s' % self.id: {}}
if self.text:
data[self.id].update({'text': self.text})
if self.img_name:
if img_serialize:
img_path = self.get_absolute_path()
img_file = open(img_path, 'rb')
image_string = base64.b64encode(img_file.read())
img_file.close()
data[self.id].update({'img': image_string})
else:
data[self.id].update({'img_name': self.img_name})
if self.weight is not None and self.weight != '':
data[self.id].update({'weight': self.weight})
return data
class Field(AbstractObject, ComponentStructure):
TextInput = 'TextInput'
MultipleCheckBox = 'MultipleCheckBox'
RadioButton = 'RadioButton'
DropDownList = 'DropDownList'
ImageCheckBox = 'ImageCheckBox'
ImageRadioButton = 'ImageRadioButton'
VALIDATION_RULES = {
'MultipleCheckBox': (
lambda f: f.options and len(f.options) > 0,
"Respuesta con checks (multiple selección): necesita "
"al menos una opción."
),
'RadioButton': (
lambda f: f.options and len(f.options) > 1,
"Respuesta con radios (Solo una selección): necesita "
"al menos dos opciones."
),
'DropDownList': (
lambda f: f.options and len(f.options) > 0,
"Respuesta con lista de opciones: necesita "
"al menos una opción."
),
'ImageCheckBox': (
lambda f: f.options and len(f.options) > 0,
"Respuesta con checks (multiple selección): necesita "
"al menos una imagen de opción."
),
'ImageRadioButton': (
lambda f: f.options and len(f.options) > 1,
"Respuesta con radios (Solo una selección): necesita "
"al menos dos imagenes de opciones."
),
'TextInput': (lambda f: True, ""),
}
def __init__(self, data={}, *args, **kwargs):
super(Field, self).__init__(*args, **kwargs)
order = data.get('order', None)
self.order = int(order) if order else order
self.name = data.get('name', None)
self.dependence = data.get('dependence', None)
self.options = []
widget_type = data.get('widget_type', None)
if widget_type and widget_type not in dict(WIDGET_TYPES).keys():
raise AttributeError(
'valid widget types are %s' % WIDGET_TYPES.keys().join(', ')
)
self.widget_type = widget_type
def add_options(self, data):
for id, info in data.iteritems():
opt_data = {'id': id}
opt_data.update(info)
opt = Option(opt_data, poll=self.poll)
self.options = self.options if self.options is not None else []
if opt_data.get('text', None) and opt not in self.options:
self.options.append(opt)
img = opt_data.get('img', None) or opt_data.get('img_name', None)
if img and opt not in self.options:
self.options.append(opt)
def validate(self, options=[]):
self.errors = []
rule, msg = Field.VALIDATION_RULES.get(self.widget_type)
if not rule(self):
self.errors.append(msg)
# Validate option of current field
for opt in self.options:
# TODO: Refactoring this.
# HORRIBLE path to avoid validation for TextInput options.
if self.widget_type != Field.TextInput:
try:
opt.validate()
except Option.ValidationError:
self.errors += opt.errors
# TODO: Test
if not self.name:
msg = "Necesita ingresar una pregunta"
self.errors.append(msg)
if len(self.errors):
raise Field.ValidationError(str(self.errors))
def to_python(self, with_errors=False, img_serialize=False):
data = {}
data.update({
'name': self.name,
'widget_type': self.widget_type,
'options': {}
})
if self.dependence:
data.update({'dependence': self.dependence})
if with_errors:
data.update({'errors': self.errors})
options = self.options if self.options else []
for option in options:
data['options'].update(option.to_python(
with_errors=with_errors, img_serialize=img_serialize)
)
return {'%d' % self.order: data}
class Group(AbstractObject, ComponentStructure):
def __init__(self, data={}, *args, **kwargs):
super(Group, self).__init__(*args, **kwargs)
order = data.get('order', None)
self.order = int(order) if order else order
self.name = data.get('name', None)
self.fields = data.get('fields', [])
def add_field(self, field, order):
order = int(order)
field.order = order
fields_pre = self.fields[:order]
fields_post = self.fields[order:]
self.fields = fields_pre + [field] + fields_post
return field
def validate(self):
self.errors = []
if not self.name:
msg = "Necesita ingresar un nombre para el grupo."
self.errors.append(msg)
if not self.fields:
msg = "Necesita al menos una pregunta para un grupo."
self.errors.append(msg)
if len(self.errors):
raise Group.ValidationError(str(self.errors))
def to_python(self, with_errors=False, img_serialize=False):
data = {'name': self.name, 'fields': {}}
if with_errors:
data.update({'errors': self.errors})
for field_obj in self.fields:
field_data = field_obj.to_python(
with_errors=with_errors, img_serialize=img_serialize
)
data['fields'].update(field_data)
return {'%d' % self.order: data}
class Structure(AbstractObject, ComponentStructure):
"""
{
'groups': {
'0': {
'name': 'group name',
'fields': {
'0': {
'widget_type': ...,
'name': ...,
'options': ...,
'dependence': ...,
},
'1' ...
}
},
'1' ...
...
}
}
"""
def __init__(self, data=None, poll=None, *args, **kwargs):
super(Structure, self).__init__(poll, *args, **kwargs)
self.data = data
self.groups = []
self.poll = poll
self.id = None
# Getting parent poll id
self._poll_id = getattr(poll, 'id', None)
if self.data and self._poll_id is None:
poll_dbref = data.get('poll', None)
poll_id = poll_dbref.id if poll_dbref else None
self._poll_id = str(poll_id) if poll_id else self._poll_id
self._poll_id = self.data.get('poll_id', self._poll_id)
# Build model Structure obj based in dict data
if self.data:
# Getting id
_id = data.get('id', None) or data.get('_id', None)
if _id and (isinstance(_id, str) or isinstance(_id, unicode)):
self.id = ObjectId(_id)
elif _id and isinstance(_id, ObjectId):
self.id = _id
groups_info = data['groups']
for group_order, group_data in groups_info.iteritems():
group = Group({
'order': group_order,
'name': group_data['name']
}, poll=self.poll)
fields_info = group_data.get('fields', {})
for field_order, field_data in fields_info.iteritems():
field_data.update({'order': field_order})
field = Field(field_data, poll=self.poll)
field.add_options(field_data.get('options', {}))
group.add_field(field, field_order)
self.add_group(group, group_order)
# Require: parent poll id !!!
if not self._poll_id:
raise Exception('INTERNAL ERROR: A structure need a poll id!')
@property
def poll_id(self):
return self._poll_id
def add_group(self, group, order):
order = int(order)
group.order = order
groups_pre = self.groups[:order]
groups_post = self.groups[order:]
self.groups = groups_pre + [group] + groups_post
return group
def get_options(self):
fields = reduce(
lambda x, y: x + y, [g.fields for g in self.groups], [])
options = reduce(
lambda x, y: x + y, [f.options or [] for f in fields], [])
return options
def get_image_options(self):
options = self.get_options()
return filter(lambda opt: opt.img_name is not None, options)
def validate(self):
self.errors = []
if not self.data.get('groups', {}):
msg = "Necesita al menos un grupo con preguntas."
self.errors.append(msg)
if len(self.errors):
raise Group.ValidationError(str(self.errors))
def is_valid(self):
valid = True
options = self.get_options()
for group in self.groups:
try:
group.validate()
except Group.ValidationError:
valid = False
for field in group.fields:
try:
field.validate(options)
except Field.ValidationError:
valid = False
try:
self.validate()
except Structure.ValidationError:
valid = False
return valid
def to_python(self, with_errors=False, img_serialize=False):
data = {'groups': {}}
for group_obj in self.groups:
data['groups'].update(
group_obj.to_python(
with_errors=with_errors, img_serialize=img_serialize
)
)
return data
def save(self):
structure_id = None
self.validate()
_dict = self.to_python()
# Prepare dbref to poll object
if not self.poll:
raise ValidationError("Need a parent poll.")
else:
dbref = DBRef(Poll.collection_name, ObjectId(self.poll.id))
_dict.update({'poll': dbref})
# Prepare id if is a existing Structure object
if self.id:
_dict.update({'_id': ObjectId(self.id)})
# Save process -> Update if it have id, else insert
structure_id = get_db().structures.save(_dict)
# Removing older img options files
current_options = self.get_image_options()
current_opts_file_name = [opt.img_name for opt in current_options]
path = self.get_image_options_path()
for file in os.listdir(path):
if file not in current_opts_file_name:
try:
os.remove("%s/%s" % (path, file))
except:
pass
return structure_id
@staticmethod
def get(id=None):
structure = None
objects = get_db().structures.find({'_id': ObjectId(id)})
if objects.count():
obj = objects[0]
poll_id = obj['poll'].id
structure = Structure(obj)
structure.poll = Poll.get(poll_id)
return structure
def get_image_options_tmp_path(self):
path = settings.IMAGE_OPTIONS_ROOT + '/%s/tmp' % self.poll_id
try:
os.makedirs(path)
except OSError:
pass
return path
def get_image_options_path(self):
path = settings.IMAGE_OPTIONS_ROOT + '/%s' % self.poll_id
try:
os.makedirs(path)
except OSError:
pass
return path
def get_image_options_tmp_media_url(self):
media_url = None
media_url = settings.IMAGE_OPTIONS_MEDIA_URL + '/%s/tmp' % self.poll_id
return media_url
def rollback(self):
tmp_path = self.get_image_options_tmp_path()
path = self.get_image_options_path()
for file in os.listdir(path):
if file != "tmp":
src_file = os.path.join(path, file)
dst_file = os.path.join(tmp_path, file)
shutil.move(src_file, dst_file)
def storing_image_options(self, path, options):
for img_opt in options:
if isinstance(img_opt.img, InMemoryUploadedFile):
with open(path + '/%s' % img_opt.img_name, 'wb+') as dst:
for chunk in img_opt.img.chunks():
dst.write(chunk)
dst.close()
def save_image_options(self, tmp=False):
options = self.get_options()
valid_img_options = filter(
lambda opt: not 'img' in opt.dict_errors.keys(), options)
tmp_path = self.get_image_options_tmp_path()
if len(valid_img_options):
if tmp:
self.storing_image_options(tmp_path, valid_img_options)
else:
path = self.get_image_options_path()
self.storing_image_options(path, valid_img_options)
# Moving tmp images options to the final place for store them
for img_opt in valid_img_options:
src = '%s/%s' % (tmp_path, img_opt.img_name)
dst = '%s/%s' % (path, img_opt.img_name)
try:
shutil.move(src, dst)
except Exception:
# TODO: LOG orphan img options
pass
try:
os.removedirs(tmp_path)
except:
# TODO: tmp must be empty,
# if raise exception here is someting bad
# TODO: LOG!
pass
|