forked from LinuxCabal/admin-cfdi
-
Notifications
You must be signed in to change notification settings - Fork 2
/
pyutil.py
1652 lines (1512 loc) · 57.9 KB
/
pyutil.py
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#! coding: utf-8
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
import os
import sys
import re
import csv
import glob
import json
import ftplib
import time
import calendar
import imaplib
import email
import hashlib
import shutil
import subprocess
import tempfile
import signal
import pyqrcode
from datetime import datetime
from string import Template
from xml.etree import ElementTree as ET
import tkinter as tk
from tkinter.filedialog import askdirectory
from tkinter.filedialog import askopenfilename
from tkinter import messagebox
from pysimplesoap.client import SoapClient, SoapFault
try:
from subprocess import DEVNULL
except ImportError:
DEVNULL = open(os.devnull, 'wb')
WIN = 'win32'
MAC = 'darwin'
LINUX = 'linux'
if sys.platform == WIN:
from win32com.client import Dispatch
elif sys.platform == LINUX:
import uno
from com.sun.star.beans import PropertyValue
from com.sun.star.beans.PropertyState import DIRECT_VALUE
from com.sun.star.awt import Size
class SAT(object):
_webservice = 'https://consultaqr.facturaelectronica.sat.gob.mx/' \
'consultacfdiservice.svc?wsdl'
def __init__(self):
self.error = ''
self.msg = ''
def get_estatus(self, data):
try:
args = '?re={emisor_rfc}&rr={receptor_rfc}&tt={total}&id={uuid}'
client = SoapClient(wsdl = self._webservice)
fac = args.format(**data)
res = client.Consulta(fac)
if 'ConsultaResult' in res:
self.msg = res['ConsultaResult']['Estado']
return True
return False
except SoapFault as sf:
self.error = sf.faultstring
return False
class ValidCFDI(object):
WIN = 'win32'
def __init__(self, path_xml, g):
self.path_xml = path_xml
self.g = g
self.error = ''
self.msg = ''
self.PATHS = {}
self.xml = ET.parse(path_xml).getroot()
self.ver = self.xml.attrib['version']
self._config()
def _config(self):
self.g.PATHS['XSLT_CADENA'] = self._join(
self.g.PATHS['XSLT_CADENA'].format(self.ver))
self.PATHS['KEY'] = self._get_path_temp('key')
self.PATHS['SELLO'] = self._get_path_temp('stamp')
self.PATHS['CADENA'] = self._get_path_temp('cadena')
self.PATHS['CER'] = ''
return
def _join(self, *paths):
return os.path.join(*paths)
def _get_path_temp(self, name=''):
if sys.platform == self.WIN:
return tempfile.TemporaryFile(mode='w').name
if name:
return self._join(tempfile.gettempdir(), name)
else:
return tempfile.mkstemp()[1]
def _exists(self, path):
return os.path.exists(path)
def _get_file_size(self, path):
try:
return os.path.getsize(path)
except:
return 0
def _file_kill(self, path):
try:
os.remove(path)
except:
pass
def _get_cer_sat(self):
timbre = '{}Complemento/{}TimbreFiscalDigital'.format(
self.g.PREFIX[self.ver], self.g.PREFIX['TIMBRE'])
node = self.xml.find(timbre)
cer_sat = node.attrib['noCertificadoSAT']
self.PATHS['CER'] = self._join(
self.g.PATHS['CER'], cer_sat + self.g.EXT_CER)
if self._exists(self.PATHS['CER']):
return True
for i in range(5):
if self._get_cer_ftp_sat(cer_sat, self.PATHS['CER']):
return True
else:
time.sleep(1)
return False
def _get_cer_ftp_sat(self, cer, path_cer):
ftp = ftplib.FTP(self.g.SAT['ftp'], timeout=5)
folder = self._join(
self.g.SAT['folder'],
cer[0:6],
cer[6:12],
cer[12:14],
cer[14:16],
cer[16:18]
)
try:
ftp.login('anonymous', '')
ftp.cwd(folder)
ftp.retrbinary(
'RETR {}.cer'.format(cer), open(path_cer, 'wb').write)
return True
except ftplib.all_errors as e:
if str(e) == 'timed out':
self.error = 'Se agoto el tiempo de espera. asegurate de ' \
'tener conexión a Internet activa'
else:
code = str(e).split(None, 1)
if isinstance(code, list):
code = int(code[0])
if code == 550:
self.error = 'Servidor FTP del SAT fuera de línea'
else:
self.error = str(code)
self.g.LOG.error(self.error)
return False
finally:
ftp.close()
return False
def _cadena_hex(self, cadena):
return hashlib.sha1(cadena.encode('utf-8')).hexdigest()
def _make_files(self, sat=False):
xslt_sello = self.g.PATHS['XSLT_SELLO']
xslt_cadena = self.g.PATHS['XSLT_CADENA']
msg1 = 'No fue posible obtener la llave del certificado del CFDI'
msg2 = 'No fue posible obtener el sello del CFDI'
if sat:
msg1 = 'No fue posible obtener la llave del certificado del SAT'
msg2 = 'No fue posible obtener el sello del SAT'
xslt_sello = self.g.PATHS['XSLT_SELLO_SAT']
xslt_cadena = self.g.PATHS['XSLT_TIMBRE']
if not self._get_cer_sat():
return False
# Generamos la llave publica del certificado SAT
args = '"{}" x509 -inform DER -in "{}" -pubkey > "{}"'.format(
self.g.PATHS['OPENSSL'],
self.PATHS['CER'],
self.PATHS['KEY'],
)
else:
# Generamos la llave publica del certificado CFDI
args = '"{}" "{}" "{}" | "{}" x509 -inform PEM -pubkey > ' \
'"{}"'.format(
self.g.PATHS['XSLTPROC'],
self.g.PATHS['XSLT_CER'],
self.path_xml,
self.g.PATHS['OPENSSL'],
self.PATHS['KEY'],
)
try:
subprocess.check_output(args, shell=True, stderr=DEVNULL).decode()
except subprocess.CalledProcessError as e:
self.g.LOG.error(e)
self.error = msg1
return False
# Generamos el sello
args = '"{}" "{}" "{}" | "{}" enc -base64 -d -A -out "{}"'.format(
self.g.PATHS['XSLTPROC'],
xslt_sello,
self.path_xml,
self.g.PATHS['OPENSSL'],
self.PATHS['SELLO'],
)
try:
res = subprocess.check_output(
args, shell=True, stderr=DEVNULL).decode()
except subprocess.CalledProcessError as e:
self.g.LOG.error(e)
self.error = msg2
return False
if not self._get_file_size(self.PATHS['SELLO']):
self.g.LOG.error(msg2)
self.error = msg2
return False
# Generamos la cadena original del CFDI
args = '"{}" "{}" "{}" > "{}"'.format(
self.g.PATHS['XSLTPROC'],
xslt_cadena,
self.path_xml,
self.PATHS['CADENA'],
)
try:
res = subprocess.check_output(
args, shell=True, stderr=DEVNULL).decode()
except subprocess.CalledProcessError as e:
self.g.LOG.error(e)
self.error = msg2
return False
if not self._get_file_size(self.PATHS['CADENA']):
self.g.LOG.error(msg2)
self.error = msg2
return False
return True
def _valid_sello(self, sat=True):
args = '"{}" dgst -sha1 -verify "{}" -signature "{}" "{}"'.format(
self.g.PATHS['OPENSSL'],
self.PATHS['KEY'],
self.PATHS['SELLO'],
self.PATHS['CADENA'],
)
try:
valid = subprocess.check_output(
args, shell=True, stderr=DEVNULL).decode()
except subprocess.CalledProcessError as e:
self.g.LOG.error(e)
self.error = 'Documento inválido'
return False
msg = 'del CFDI'
if sat:
msg = 'del SAT'
if valid.strip() != 'Verified OK':
self.error = 'Documento inválido, sello {} inválido'.format(msg)
self.g.LOG.error(self.error)
return False
return True
def _delete(self):
self._file_kill(self.PATHS['KEY'])
self._file_kill(self.PATHS['SELLO'])
self._file_kill(self.PATHS['CADENA'])
return
def verify_cfdi(self):
if not self._make_files():
return False
if not self._valid_sello():
return False
#~ Obtenemos los archivos necesarios para validar el sello del SAT
if not self._make_files(True):
return False
#~ Validamos el sello del SAT
if not self._valid_sello(True):
return False
self._delete()
self.msg = 'Documento válido'
return True
class Util(object):
WIN = 'win32'
MAC = 'darwin'
def __init__(self):
self.OS = sys.platform
def get_folder(self, parent):
return askdirectory(parent=parent)
def get_file(self, parent, ext='', title='Factura Libre'):
filetypes = [(ext, ext)]
return askopenfilename(
parent=parent,
title=title,
defaultextension=ext,
filetypes=filetypes)
def dir_current(self):
return os.getcwd()
def get_path_info(self, path, index=-1):
path, filename = os.path.split(path)
name, extension = os.path.splitext(filename)
data = (path, filename, name, extension)
if index == -1:
return data
else:
return data[index]
def path_join(self, *paths):
return os.path.join(*paths)
def path_config(self, path):
target = path
if sys.platform == self.WIN:
target = path.replace('/', '\\')
return target
def get_files(self, path, ext='*.xml'):
files = []
for folder,_,_ in os.walk(path):
files.extend(glob.glob(os.path.join(folder, ext.lower())))
return tuple(files)
def join(self, *paths):
return os.path.join(*paths)
def exists(self, path):
return os.path.exists(path)
def makedirs(self, path):
if not self.exists(path):
os.makedirs(path)
return
def move(self, src, dest):
try:
shutil.move(src, dest)
return True
except:
return False
def copy(self, src, dest):
try:
shutil.copy(src, dest)
return True
except:
return False
def validate_dir(self, path, access='e'):
if access == 'e':
return self.exists(path)
if access == 'r':
return os.access(path, os.R_OK)
if access == 'w':
return os.access(path, os.W_OK)
def msgbox(self, msg, icon=1):
title = 'Factura Libre'
if icon == 1:
messagebox.showerror(title, msg)
elif icon == 2:
messagebox.showinfo(title, msg)
else:
messagebox.showwarning(title, msg)
return
def question(self, msg):
return messagebox.askyesno('Factura Libre', msg)
def sleep(self, sec=1):
time.sleep(sec)
return
def load_config(self, path):
data = {}
try:
with open(path, 'r') as f:
data = json.loads(f.read())
except:
pass
return data
def save_config(self, path, key, value):
data = self.load_config(path)
data[key] = value
try:
with open(path, 'w') as f:
data = json.dumps(data, indent=4)
f.write(data)
except:
pass
return
def now(self):
return datetime.now()
def get_dates(self, year, month):
days = calendar.monthrange(year, month)[1]
d1 = '01/{:02d}/{}'.format(month, year)
d2 = '{}/{:02d}/{}'.format(days, month, year)
return d1, d2
def get_days(self, year, month):
if isinstance(year, str):
year = int(year)
if isinstance(month, str):
month = int(month)
return calendar.monthrange(year, month)[1]
def combo_values(self, combo, values, select_pos=-1):
if isinstance(values, tuple):
combo['values'] = values
else:
combo['values'] = tuple(values)
if select_pos == -1:
combo.current(len(combo['values']) - 1)
elif select_pos > -1:
combo.current(select_pos)
return
def listbox_insert(self, listbox, value, pos=tk.END):
listbox.insert(pos, value)
return
def listbox_delete(self, listbox, pos=-1):
if pos == -2:
listbox.delete(0, tk.END)
elif pos == -1:
listbox.delete(listbox.curselection()[0])
else:
listbox.delete(pos)
return
def listbox_selection(self, listbox):
selection = listbox.curselection()
if selection:
selection = listbox.get(tk.ACTIVE)
return selection
def get_info_xml(self, path, PRE):
data = {}
try:
xml = ET.parse(path).getroot()
except Exception as e:
#~ self.debug(path)
#~ self.debug(e)
return {}
ver = xml.attrib['version']
node = xml.find('{}Emisor'.format(PRE[ver]))
if node is None:
log = 'El documento no tiene el nodo requerido Emisor: {}'
#~ self.debug(log.format(path))
return {}
data['emisor_rfc'] = node.attrib['rfc']
node = xml.find('{}Receptor'.format(PRE[ver]))
if node is None:
log = 'El documento no tiene el nodo requerido Receptor: {}'
#~ self.debug(log.format(path))
return {}
data['receptor_rfc'] = node.attrib['rfc']
node = xml.find('{}Complemento/{}TimbreFiscalDigital'.format(
PRE[ver], PRE['TIMBRE']))
if node is None:
log = 'El documento no esta timbrado: {}'
#~ self.debug(log.format(path))
return {}
data['uuid'] = node.attrib['UUID']
data['year'] = node.attrib['FechaTimbrado'][0:4]
data['month'] = node.attrib['FechaTimbrado'][5:7]
return data
def get_name(self, path, PRE, format1='', format2=''):
xml = ET.parse(path).getroot()
data = xml.attrib.copy()
del data['sello']
del data['certificado']
pre = PRE[data['version']]
if not 'serie' in data:
data['serie'] = ''
data['fecha'] = data['fecha'].partition('T')[0]
if 'folio' in data:
data['folio'] = int(data['folio'])
else:
data['folio'] = 0
node = xml.find('{}Emisor'.format(pre))
data['emisor_rfc'] = node.attrib['rfc']
data['emisor_nombre'] = ''
if 'nombre' in node.attrib:
data['emisor_nombre'] = node.attrib['nombre'].replace('/', '_')
node = xml.find('{}Receptor'.format(pre))
data['receptor_rfc'] = node.attrib['rfc']
data['receptor_nombre'] = ''
if 'nombre' in node.attrib:
data['receptor_nombre'] = node.attrib['nombre'].replace('/', '_')
node = xml.find('{}Complemento/{}TimbreFiscalDigital'.format(
pre, PRE['TIMBRE']))
data['uuid'] = node.attrib['UUID']
if format1:
try:
name = format1.format(**data)
name = name.replace("'", "").replace(" ", "_").replace(
",", "").replace(".", "")
return os.path.normpath(name)
except:
return os.path.normpath(format2.format(**data))
else:
return os.path.normpath(format2.format(**data))
def parse(self, path):
try:
xml = ET.parse(path).getroot()
return xml
except:
return None
def get_qr(self, data):
scale = 10
path = self.get_path_temp('cbb.png')
code = pyqrcode.QRCode(data, mode='binary')
code.png(path, scale)
return path
def get_path_temp(self, name=''):
if name:
return self.join(tempfile.gettempdir(), name)
if sys.platform == self.WIN:
return tempfile.TemporaryFile(mode='w').name
return tempfile.mkstemp()[1]
def get_info_report(self, path, options, g):
PRE = g.PREFIX
data = {}
try:
xml = ET.parse(path).getroot()
except Exception as e:
g.LOG.error(path)
g.LOG.error(e)
return False
ver = xml.attrib['version']
data = xml.attrib.copy()
del data['sello']
del data['certificado']
node = xml.find('{}Emisor'.format(PRE[ver]))
if node is None:
log = 'El documento no tiene el nodo requerido Emisor: {}'
g.LOG.error(log.format(path))
return False
data['emisor_rfc'] = node.attrib['rfc']
data['emisor_nombre'] = ''
if 'nombre' in node.attrib:
data['emisor_nombre'] = node.attrib['nombre']
node = xml.find('{}Receptor'.format(PRE[ver]))
if node is None:
log = 'El documento no tiene el nodo requerido Receptor: {}'
g.LOG.error(log.format(path))
return False
data['receptor_rfc'] = node.attrib['rfc']
data['receptor_nombre'] = ''
if 'nombre' in node.attrib:
data['receptor_nombre'] = node.attrib['nombre']
node = xml.find('{}Impuestos'.format(PRE[ver]))
if node is not None:
data.update(node.attrib)
imp = node.find('{}Traslados'.format(PRE[ver]))
if imp is not None:
for n in list(imp):
key = 'traslado_{}_{}'.format(
n.attrib['impuesto'].lower(),
int(float(n.attrib['tasa'])))
data[key] = float(n.attrib['importe'])
imp = node.find('{}Retenciones'.format(PRE[ver]))
if imp is not None:
for n in list(imp):
key = 'retencion_{}'.format(n.attrib['impuesto'].lower())
data[key] = float(n.attrib['importe'])
node = xml.find('{}Complemento/{}TimbreFiscalDigital'.format(
PRE[ver], PRE['TIMBRE']))
if node is None:
log = 'El documento no esta timbrado: {}'
g.LOG.error(log.format(path))
return False
data['UUID'] = node.attrib['UUID'].upper()
data['FechaTimbrado'] = node.attrib['FechaTimbrado'].replace('T', ' ')
data['fecha'] = data['fecha'].replace('T', ' ')
fields_details = (
'noIdentificacion',
'descripcion',
'unidad',
'cantidad',
'valorUnitario',
'importe'
)
details = []
if any(d in options['fields_report'] for d in fields_details):
node = xml.find('{}Conceptos'.format(PRE[ver]))
for n in node.getchildren():
details.append(n.attrib.copy())
atr = (
'serie',
'folio',
'Moneda',
'TipoCambio',
'validacion',
'validacion_sat',
'totalImpuestosRetenidos',
'totalImpuestosTrasladados',
'descuento',
'traslado_iva_0',
'traslado_iva_16',
'retencion_iva',
'retencion_isr',
) + fields_details
for a in atr:
if not a in data:
data[a] = ''
tmpl = Template(options['fields_report'].replace('{', '${'))
if details:
info = []
for d in details:
new_data = data.copy()
new_data.update(d)
info.append(tmpl.safe_substitute(**new_data).split('|'))
return tuple(info)
info = tmpl.safe_substitute(**data).split('|')
if options['validate_fac']:
cfdi = ValidCFDI(path, g)
if cfdi.verify_cfdi():
info.append(cfdi.msg)
else:
info.append(cfdi.error)
if options['validate_sat']:
data_sat = {
'emisor_rfc': data['emisor_rfc'],
'receptor_rfc': data['receptor_rfc'],
'total': data['total'],
'uuid': data['UUID']
}
sat = SAT()
if sat.get_estatus(data_sat):
info.append(sat.msg)
else:
info.append(sat.error)
return tuple((info,))
def save_csv(self, data, path=''):
if not path:
path = self.get_path_temp('reporte.csv')
with open(path, 'w', newline='\n') as csvfile:
datawriter = csv.writer(csvfile, delimiter='|',
quotechar='"', quoting=csv.QUOTE_MINIMAL)
for l in data:
datawriter.writerow(l)
if self.OS == self.WIN:
os.startfile(path)
elif self.OS == self.MAC:
subprocess.call(['open', path])
else:
subprocess.call(['xdg-open', path])
return
class Mail(object):
PREFIX = {
'3.0': '{http://www.sat.gob.mx/cfd/3}',
'3.2': '{http://www.sat.gob.mx/cfd/3}',
'TIMBRE': '{http://www.sat.gob.mx/TimbreFiscalDigital}',
}
def __init__(self, data):
self.error = ''
self.target = data['mail_target']
self.con = self._connection(data)
self.type_xml = ('text/xml', 'application/xml')
self.type_pdf = ('application/pdf',)
self.type_other = (
'application/octet-stream', 'application/x-zip-compressed')
self.types = self.type_xml + self.type_pdf + self.type_other
self.ext = ('.xml', '.pdf', '.zip')
def _connection(self, data):
try:
if data['mail_ssl']:
M = imaplib.IMAP4_SSL(data['mail_server'], data['mail_port'])
else:
M = imaplib.IMAP4(data['mail_server'], data['mail_port'])
M.login(data['mail_user'], data['mail_password'])
M.select()
return M
except imaplib.IMAP4.error as e:
self.error = str(e)
return None
except Exception as e:
self.error = str(e)
return None
def _join(self, *paths):
return os.path.join(*paths)
def __del__(self):
try:
self.con.close()
self.con.logout()
except:
pass
def down_all_mails(self, pb, info, options):
i = 0
folders = self._get_folders(options['mail_subfolder'])
mails = self._get_mails(folders)
total = len(mails)
pb['maximum'] = total
pb.start()
for f in folders:
mails = self._get_mails((f,))
for m in mails:
i += 1
pb['value'] = i
pb.update_idletasks()
msg = 'Correo {} de {}'.format(i, total)
info.set(msg)
message = self._get_mail(m)
if not message:
continue
files = self._get_files(message)
if files:
self._save_files(files, options['mail_name'])
if options['mail_delete2']:
self.con.uid('STORE', m, '+FLAGS', '\\Deleted')
else:
if options['mail_delete1']:
self.con.uid('STORE', m, '+FLAGS', '\\Deleted')
self.con.expunge()
return
def _get_mails(self, folders):
mails = []
for f in folders:
self.con.select(f)
typ, data = self.con.uid('search', None, 'ALL')
mails.extend(data[0].split())
return mails
def _get_folders(self, subfolders):
folders = ['INBOX']
if subfolders:
typ, subdir = self.con.list()
for s in subdir:
name = s.decode('utf8').rpartition('"."')[-1].strip()
if name in ('INBOX', 'INBOX.Trash', 'INBOX.Drafts',
'INBOX.Junk', 'INBOX.Sent'):
continue
folders.append(name)
return folders
def _get_mail(self, uid):
result, data = self.con.uid('fetch', uid, '(RFC822)')
if not data[0]:
return
raw_email = data[0][1].decode('utf8', 'ignore')
email_message = email.message_from_string(raw_email)
return email_message
def _get_files(self, message):
sha_tmp = []
files = {}
for part in message.walk():
#~ print ('part CMT', part.get_content_maintype())
if part.get_content_maintype() == 'multipart':
continue
#~ print ('part CMT', part.get_content_maintype())
#~ if part.get('Content-Disposition') is None:
#~ continue
file_name = part.get_filename()
if not file_name:
continue
#~ print (file_name)
content_type = part.get_content_type()
if content_type in self.types:
#~ print ('get', file_name, content_type)
content = part.get_payload(decode=True)
sha = hashlib.sha1(content).hexdigest()
if sha in sha_tmp:
continue
sha_tmp.append(sha)
#~ files.append((file_name, content))
name = file_name[:-4].replace(' ', '_').upper()
ext = file_name[-4:].lower()
# ToDo and delete
if ext == '.zip':
continue
if not ext in self.ext:
continue
if not name in files:
files[name] = {'xml': '', 'pdf': ''}
#~ print ('ext', ext)
if content_type in self.type_xml:
files[name]['xml'] = content
elif content_type in self.type_pdf:
files[name]['pdf'] = content
elif content_type in self.type_other:
if ext == '.xml':
files[name]['xml'] = content
elif ext == '.pdf':
files[name]['pdf'] = content
elif ext == '.zip':
# ToDo ZIP
pass
return files
def _save_files(self, files, original):
for k, v in files.items():
if not v['xml'] and not v['pdf']:
continue
#~ print ('save', k)
file_name = k
if v['xml'] and v['pdf'] and not original:
#~ xml = v['xml'].decode('utf8')
tree = ET.fromstring(v['xml'])
ver = tree.attrib['version']
if float(ver) >= 3.0:
timbre = '{}Complemento/{}TimbreFiscalDigital'.format(
self.PREFIX[ver], self.PREFIX['TIMBRE'])
node = tree.find(timbre)
if node is not None:
file_name = node.attrib['UUID'].upper()
name_xml = '{}_ORIGINAL.xml'
name_pdf = '{}_ORIGINAL.pdf'
if original:
name_xml = '{}.xml'
name_pdf = '{}.pdf'
if v['xml'] and not v['pdf']:
path = self._join(self.target, name_xml.format(file_name))
with open(path, 'wb') as fd:
fd.write(v['xml'])
elif not v['xml'] and v['pdf']:
path = self._join(self.target, name_pdf.format(file_name))
with open(path, 'wb') as fd:
fd.write(v['pdf'])
else:
path = self._join(self.target, '{}.xml'.format(file_name))
with open(path, 'wb') as fd:
fd.write(v['xml'])
path = self._join(self.target, name_pdf.format(file_name))
with open(path, 'wb') as fd:
fd.write(v['pdf'])
return
class LibO(object):
WIN = 'win32'
WIN_SM = 'com.sun.star.ServiceManager'
OS = sys.platform
SM = None
def __init__(self):
self._aoo = None
self._run()
self._init_var()
def __del__(self):
try:
self.desktop.terminate()
except Exception as e:
print (e)
if self._aoo:
self._aoo.kill()
if self.OS != self.WIN:
ps = subprocess.Popen(['ps', '-e'], stdout=subprocess.PIPE)
grep = subprocess.Popen(['grep', 'soffice'],
stdin=ps.stdout, stdout=subprocess.PIPE)
p = grep.communicate()[0]
if p:
pid = p.split()[0].strip()
try:
os.kill(int(pid), signal.SIGKILL)
except Exception as e:
print (e)
def _init_var(self):
try:
self.desktop = self._create_instance('com.sun.star.frame.Desktop')
if self.OS == self.WIN:
self.SM._FlagAsMethod("Bridge_GetStruct")
self.fcp = self._create_instance(
'com.sun.star.ucb.FileContentProvider')
except:
pass
def _run(self):
if self.OS == self.WIN:
self.SM = Dispatch(self.WIN_SM)
else:
ps = subprocess.Popen(['ps', '-e'], stdout=subprocess.PIPE)
grep = subprocess.Popen(
['grep', 'soffice'],
stdin=ps.stdout,
stdout=subprocess.PIPE)
if not grep.communicate()[0]:
args = '--accept=socket,host=localhost,port=8100;urp;'
args += 'StarOffice.ComponentContext'
self._aoo = subprocess.Popen(['soffice', '--headless', args])
time.sleep(3)
lc = uno.getComponentContext()
local_resolver = lc.ServiceManager.createInstanceWithContext(
'com.sun.star.bridge.UnoUrlResolver', lc )
try:
args = 'uno:socket,host=localhost,port=8100;urp;'
args += 'StarOffice.ComponentContext'
context = local_resolver.resolve(args)
self.SM = context.ServiceManager
except Exception as e:
pass
def _create_instance(self, name):
return self.SM.createInstance(name)
#~ def get_propertyvalue(self):
#~ return self.SM.Bridge_GetStruct('com.sun.star.beans.PropertyValue')
def _make_property(self, args):
if self.OS == self.WIN:
pv = []
for a in args:
p = self.SM.Bridge_GetStruct('com.sun.star.beans.PropertyValue')
p.Name = a[0]
p.Value = a[1]
pv.append(p)
else:
pv = [PropertyValue(a[0], 0, a[1], DIRECT_VALUE) for a in args]
return tuple(pv)
def path_to(self, path, url=True):
new_path = path
if url:
if not path.startswith('file:///'):
new_path = self.fcp.getFileURLFromSystemPath('', path)
else:
if path.startswith('file:///'):
new_path = self.fcp.getSystemPathFromFileURL(path)
return new_path
def size(self, obj, width, height):
if self.OS == self.WIN:
tam = self.SM.Bridge_GetStruct('com.sun.star.awt.Size')
else:
tam = Size()
tam.Width = width
tam.Height = height
obj.setSize(tam)
return
def doc_open(self, path, pv=None):
path = self.path_to(path)
if pv is None:
pv = (
('Hidden', True),
('AsTemplate', True),
)
pv = self._make_property(pv)
doc = None
try:
doc = self.desktop.loadComponentFromURL(path, '_default', 0, pv)
except Exception as e:
print (e)
return doc