def create_image_from_b64(contact, d, user): image_b64 = d.pop('image', None) if image_b64 is not None: contact_has_img = contact.image is not None if image_b64 == "": if contact_has_img: contact.image.delete() return if contact_has_img: img_entity = contact.image img_entity.image.delete() # Deleting the old file else: # img_entity = Image() img_entity = Document() image_data = base64.decodestring(image_b64) image_format = get_image_format(image_data) # img_entity.image = handle_uploaded_file(ContentFile(base64.decodestring(image_b64)), path=['upload','images'], name='file_%08x.%s' % (randint(0, MAXINT), image_format)) img_entity.image = handle_uploaded_file(ContentFile(image_data), path=['upload', 'documents'], name='file_%08x.%s' % (randint(0, MAXINT), image_format), ) img_entity.folder = Folder.objects.get_or_create(title=_('Images'), parent_folder=None, defaults={'user': user}, )[0] img_entity.description = _('Imported by activesync') img_entity.user = user img_entity.save() contact.image = img_entity
def save(self, *args, **kwargs): instance = self.instance instance.filedata = fpath = handle_uploaded_file( self.cleaned_data['filedata'], path=['upload', 'documents'], max_length=Document._meta.get_field('filedata').max_length, ) assign_2_charfield(instance, 'title', basename(fpath)) return super().save(*args, **kwargs)
def save(self, *args, **kwargs): instance = self.instance file_data = self.cleaned_data.get('filedata') if file_data: file_field = type(instance)._meta.get_field('filedata') instance.filedata = handle_uploaded_file( file_data, path=file_field.upload_to.split('/'), max_length=file_field.max_length, ) return super().save(*args, **kwargs)
def _create_image(self, contact): cleaned_data = self.cleaned_data image_encoded = cleaned_data['image_encoded'] if image_encoded: img_name = secure_filename('{}_{}_{}'.format( contact.last_name, contact.first_name, contact.id)) img_path = None if image_encoded.startswith(URL_START): tmp_img_path = None try: if int(urlopen(image_encoded).info() ['content-length']) <= settings.VCF_IMAGE_MAX_SIZE: tmp_img_path = path.normpath( path.join(IMG_UPLOAD_PATH, img_name)) urlretrieve( image_encoded, path.normpath( path.join(settings.MEDIA_ROOT, tmp_img_path))) except: logger.exception('Error with image') else: img_path = tmp_img_path else: # TODO: manage urls encoded in base64 ?? try: # TODO: factorise with activesync ?? img_data = base64.decodebytes(image_encoded.encode()) img_path = handle_uploaded_file( ContentFile(img_data), path=IMG_UPLOAD_PATH.split('/'), name='{}.{}'.format( img_name, get_image_format(img_data), ), ) except Exception: logger.exception('VcfImportForm.save()') if img_path: return Document.objects.create( user=cleaned_data['user'], title=gettext('Image of {contact}').format( contact=contact), filedata=img_path, linked_folder=Folder.objects.get(uuid=UUID_FOLDER_IMAGES), description=gettext('Imported by VCFs'), )
def save(self, *args, **kwargs): instance = self.instance instance.filedata = fpath = handle_uploaded_file( self.cleaned_data['filedata'], path=['upload', 'documents'], max_length=Document._meta.get_field('filedata').max_length, ) if not instance.title: # TODO: truncate but keep extension if possible ? assign_2_charfield(instance, 'title', basename(fpath)) # return super(_DocumentBaseForm, self).save(*args, **kwargs) return super().save(*args, **kwargs)
def _create_instance_n_history(self, data, user=None, source='', action=''): # TODO: remove 'action' is_created = True instance = self.model() model_get_field = self.model._meta.get_field try: with atomic(): for field_name, field_value in [ *data.items() ]: # NB: we build a list to modify "data" try: field = model_get_field(field_name) except FieldDoesNotExist: # TODO: data.pop(field_name) when virtual fields are added in crudity, # because for example user_id is not a "real field" (model._meta.get_field) continue # TODO: exclude not editable fields ?? if field_value is None: data[field_name] = field.to_python(None) continue # if isinstance(field_value, basestring) and not isinstance(field_value, unicode): # field_value = field_value.decode('utf8') if not isinstance(field, TextField) and isinstance( field_value, str): data[field_name] = field_value = field_value.replace( '\n', ' ') if isinstance(field, DateTimeField): data[field_name] = field_value = dt_from_str( field_value.strip()) elif isinstance(field, DateField): data[field_name] = field_value = date_from_str( field_value.strip()) elif isinstance(field, BooleanField) and isinstance( field_value, str): data[field_name] = field_value = field.to_python( field_value.strip() [0:1].lower()) #Trick to obtain 't'/'f' or '1'/'0' elif isinstance(field, ForeignKey) and issubclass( field.remote_field.model, Document): filename, blob = field_value # Should be pre-processed by the input upload_path = Document._meta.get_field( 'filedata').upload_to.split('/') if user is None: shift_user_id = data.get('user_id') User = get_user_model( ) # TODO: use first() instead if shift_user_id is None: try: # Not as the default value of data.get because a query is # always done even the default value is not necessary shift_user_id = User.objects.filter( is_superuser=True)[0].id except IndexError: continue # There is really nothing we can do else: shift_user_id = user.id doc_entity = Document( user_id=shift_user_id, filedata=handle_uploaded_file(ContentFile(blob), path=upload_path, name=filename), # folder=Folder.objects.get_or_create( linked_folder=Folder.objects.get_or_create( title=_('External data'), parent_folder=None, defaults={'user_id': shift_user_id}, )[0], description=_('Imported from external data.'), ) assign_2_charfield(doc_entity, 'title', filename) doc_entity.save() setattr(instance, field_name, doc_entity) data.pop(field_name) continue elif issubclass( field.__class__, FileField ): # TODO: why not isinstance(field, FileField) ?? filename, blob = field_value # Should be pre-processed by the input upload_path = field.upload_to.split('/') setattr( instance, field_name, handle_uploaded_file(ContentFile(blob), path=upload_path, name=filename)) data.pop(field_name) continue data[field_name] = field.to_python(field_value) # setattr(instance, field_name, field.to_python(field_value)) TODO (instead of for ..: setattr()... ?? instance.__dict__.update(data) # for k, v in data.iteritems(): #TODO: (but fix bug with ManyToManyField) # setattr(instance, k, v) self._create_instance_before_save(instance, data) instance.save() need_new_save = self._create_instance_after_save( instance, data) if need_new_save: instance.save() history = History( ) # TODO: History.objects.create(entity=intance [...]) history.entity = instance history.action = 'create' history.source = source history.user = user history.description = _('Creation of {entity}').format( entity=instance) history.save() except IntegrityError as e: logger.error( '_create_instance_n_history() : error when try to create instance [%s]', e) is_created = False return is_created, instance
def fetcher_fallback(self, email, current_user, *args, **kwargs): if not CrudityInput().authorize_senders(self, email.senders): return if is_sandbox_by_user(): current_user = CreateEmailInput.get_owner(True, sender=email.senders[0]) current_user_id = current_user.id # TODO: only if at least one attachment folder = Folder.objects.get_or_create( title=_("{username}'s files received by email").format( username=current_user.username, ), category=FolderCategory.objects.get(pk=DOCUMENTS_FROM_EMAILS), parent_folder=None, defaults={'user': current_user}, )[0] mail = EntityEmail( # status=MAIL_STATUS_SYNCHRONIZED_WAITING, status=EntityEmail.Status.SYNCHRONIZED_WAITING, body=email.body, body_html=email.body_html, sender=', '.join({*email.senders}), recipient=', '.join({*email.tos, *email.ccs}), subject=email.subject, user_id=current_user_id, ) if email.dates: mail.reception_date = email.dates[0] mail.genid_n_save() attachment_path = self.attachment_path # TODO: only if at least one attachment create_relation = partial( Relation.objects.create, type_id=REL_OBJ_RELATED_2_DOC, object_entity=mail, user_id=current_user_id, ) create_doc = partial( Document.objects.create, user_id=current_user_id, linked_folder=folder, description=_('Received with the mail {}').format(mail), ) for attachment in email.attachments: filename, file_ = attachment path = handle_uploaded_file(file_, path=attachment_path, name=filename) doc = create_doc( title=f'{basename(path)} (mail {mail.id})', filedata=path, ) create_relation(subject_entity=doc) History.objects.create( entity=mail, action='create', source='email - raw', description=_('Creation of {entity}').format(entity=mail), user=current_user, )