class CompaniaUpdate(LoginRequiredMixin, UpdateView): form_class = CompaniaUpdateForm template_name = 'actualizar_compania.html' success_url =reverse_lazy('conectores:registrar_compania') model = Compania decode_encode = DecodeEncodeChain() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print(self.kwargs) context['form']=CompaniaUpdateForm(instance=Compania.objects.get(pk=self.kwargs['pk'])) context['object'] = Compania.objects.get(pk=self.kwargs['pk']) context['companias']=Compania.objects.filter(owner=self.request.user) return context def form_valid(self,form): compania = get_object_or_404(self.model, pk=self.kwargs['pk']) if not str(form.cleaned_data['logo']) == str(compania.logo) and str(compania.logo) != '': files = self.request.FILES ruta_archivo = settings.MEDIA_ROOT+str(compania.logo) ruta = '/'.join(ruta_archivo.split('/')[:-1]) if os.path.exists(ruta): shutil.rmtree(ruta) if not str(form.cleaned_data['certificado']) == str(compania.certificado): if form.cleaned_data['pass_certificado'] == '': msg = "Necesitas ingresar la contraseña del certificado" messages.error(self.request, msg) return super().form_invalid(form) ruta_archivo = settings.MEDIA_ROOT+str(compania.certificado) ruta = '/'.join(ruta_archivo.split('/')[:-1]) if os.path.exists(ruta): shutil.rmtree(ruta) if form.cleaned_data['pass_certificado'] != '': try: instance = form.save(commit=False) pfx = instance.certificado.read() clave_privada, certificado, clave_publica = \ Compania.validar_certificado(pfx, form.cleaned_data['pass_certificado']) except ContrasenaDeCertificadoIncorrecta: messages.error(self.request, "Contraseña del certificado incorrecta") return super().form_invalid(form) try: update_compania = form.save(commit=False) update_compania.pass_correo_sii = self.decode_encode.encrypt(update_compania.pass_correo_sii) if update_compania.pass_correo_sii is not None else compania.pass_correo_sii update_compania.pass_correo_intercambio = self.decode_encode.encrypt(update_compania.pass_correo_intercambio) if update_compania.pass_correo_intercambio is not None else compania.pass_correo_intercambio update_compania.pass_certificado = self.decode_encode.encrypt(update_compania.pass_certificado) if update_compania.pass_certificado != '' else compania.pass_certificado update_compania.save() msg = "Se Actualizo la Compañia con éxito" messages.info(self.request, msg) except Exception as e: msg = "Ocurrio un problema al guardar la información: "+str(e) messages.error(self.request, msg) return super().form_invalid(form) def form_invalid(self, form): """! Form Invalid Method @param form Recives form object @return errors on form """ messages.error(self.request, form.errors) return super().form_invalid(form)
class ConectorViews(LoginRequiredMixin, FormView): """ """ form_class = FormConector template_name = 'registrar_conector.html' success_url = reverse_lazy('conectores:registrar_conector') model = Conector hasher = PBKDF2PasswordHasher decode_encode = DecodeEncodeChain() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) try: record = Conector.objects.filter(pk=1).first() if record: form = FormConector(instance=record) else: form = FormConector() context['form']=form except Exception as e: raise e return context def form_valid(self,form): """! Form Valid Method @param form Recives form object @return validate True """ try: transaction = Conector.objects.update_or_create( empresa=form['empresa'].value(), defaults={ 'usuario': form['usuario'].value(), 'url_erp': form['url_erp'].value(), 'url_sii': form['url_sii'].value(), #'password': self.hasher().encode(password=form['password'].value(), salt='salt', iterations=50000), 'password': self.decode_encode.encrypt(str(form['password'].value())), 'time_cron': form['time_cron'].value(), 'certificado': form['certificado'].value(), 't_documento': form['t_documento'].value(), 'empresa': Compania.objects.get(pk=form['empresa'].value()) }) msg = "Se configuro el Conector con éxito" messages.info(self.request, msg) except Exception as e: print(e) msg = "Ocurrio un problema al guardar la información" messages.error(self.request, msg) return super().form_valid(form) def form_invalid(self, form): """! Form Invalid Method @param form Recives form object @return errors on form """ messages.error(self.request, form.errors) return super().form_invalid(form) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs
def sycnInbox(comp, mail, refresh): """ Sincronizar el inbox @author Rodrigo A. Boet (rodrigo.b at timgla.com) @date 16-07-2019 @version 1.0.0 """ last_email = 0 local_last_email_code = last_email decode_encode = DecodeEncodeChain() assert comp.correo_intercambio, "No hay correo" assert comp.pass_correo_intercambio, "No hay password" correo = comp.correo_intercambio.strip() passw = comp.pass_correo_intercambio.strip() passw = decode_encode.decrypt(passw).decode("utf-8") try: mail.login(correo, passw) except imaplib.IMAP4.error as e: logger.warning( "Hubo un error al conectarse al correo: {0} error: {1}".format( correo, e)) pass mail.list() mail.select("inbox") result, data = mail.search(None, "ALL") id_list = data[0].split() if len(id_list) >= 1: last_email_code = int(id_list[-1].decode()) else: last_email_code = 0 if last_email_code > local_last_email_code: new_elements = last_email_code - local_last_email_code else: logger.warning("No posee nuevos correos") return False if new_elements == 1: latest_emails = [id_list[-1]] else: latest_emails = id_list[-new_elements:] #latest_emails = latest_emails[0:50] for element in latest_emails: result, email_data = mail.fetch(element, "(RFC822)") raw_email = email_data[0][1] raw_multipart = email.message_from_bytes(raw_email) try: raw_email_string = raw_email.decode('utf-8') except Exception as e: raw_email_string = raw_email.decode('latin-1') email_message = email.message_from_string(raw_email_string) attachment_count, attachments = refresh.get_attachment(raw_multipart) remisor_name, remisor_email = refresh.get_remisor( str( email.header.make_header( email.header.decode_header(email_message['From'])))) try: date = refresh.get_received_time( str( email.header.make_header( email.header.decode_header( email_message['Received'])))) except: date = None pass try: titulo = str( email.header.make_header( email.header.decode_header(email_message['Subject']))) except: titulo = "No se pudo obtener el titulo" pass obj, created = Intercambio.objects.update_or_create( #codigo_email = element.decode(), receptor=comp, email_remisor=remisor_email, fecha_de_recepcion=date, defaults={ "remisor": remisor_name, "cantidad_dte": attachment_count, "titulo": titulo, "contenido": str(refresh.get_body(raw_multipart).decode('latin-1')) }) if attachment_count > 0: for attach in attachments: filename = attach download_folder = obj.receptor.rut initial_route = os.path.join(settings.MEDIA_ROOT, 'intercambio_dte') if not os.path.isdir(initial_route): os.mkdir(initial_route) relative_path = os.path.join(initial_route, download_folder) if not os.path.isdir(relative_path): os.mkdir(relative_path) att_path = os.path.join(filename) fp = open(os.path.join(initial_route, relative_path, att_path), 'wb') fp.write(attachments[attach]) fp.close() fp = open(os.path.join(initial_route, relative_path, att_path), 'rb') attach_dte = DteIntercambio(id_intercambio=obj) attach_dte.dte_attachment.save(att_path, fp) fp.close() if comp.borrar_correo_intercambio: mail.store(element, '+FLAGS', r'(\Deleted)') logger.info("Cantidad de correos nuevos: {}".format(new_elements))