-
Notifications
You must be signed in to change notification settings - Fork 9
/
vcardlib.py
1638 lines (1375 loc) · 70.1 KB
/
vcardlib.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 -*-
"""Library to fix, convert, split, normalize, group, merge, deduplicate
vCard and VCF files from version 2.1 to 3.0 (even large ones)."""
# pylint: disable=too-many-lines
# TODO
# * Write doctest for each functions
# @see : https://docs.python.org/3/library/doctest.html#module-doctest
# * Write classes?
# * Write like reactive (map, filter, etc.)?
# * Remove all the arguments type checks?
import logging
import re
import warnings
import binascii
from os.path import exists, basename
from email.utils import parseaddr
# @see: https://eventable.github.io/vobject/
from vobject import vCard, readComponents
from vobject.vcard import Name
from vobject.base import Component, ContentLine, ParseError
# prevent the import of fuzzywuzzy to raise a UserWarning
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# @see: https://github.com/seatgeek/fuzzywuzzy
from fuzzywuzzy.fuzz import token_sort_ratio
# when building a name from an email,
# if the email left part (of '@') startswith one of the following
# then add the domain name as a prefix for the name
EMAIL_USERS_ADD_DOMAIN = (\
# universal \
'contact', 'info', 'admin', 'hello', 'job', 'question', 'support', 'service', \
# english words \
'sales', 'deal', 'unsubscribe', 'return', \
# french words \
'credit', 'recrute', 'desinscription', 'sav', 'servicecommercial', 'relationclient'\
)
# pre-compile regex
REGEX_ANYTHING_BETWEEN_PARENTH_OR_BRACES = re.compile(' *(\\([^)]*\\)|\\[[^]]*\\]) *')
REGEX_ANYTHING_BUT_INDEX = re.compile('(.*)\\([0-9]+\\)$')
REGEX_ICE = re.compile(r'\b(ICE[0-9]*)\b', re.IGNORECASE)
REGEX_ANY_DASH_OR_UNDERSCORE = re.compile('[_-]')
REGEX_ANY_NUMBER = re.compile('[0-9]')
REGEX_WITHOUT_EXTENSION = re.compile('(.+)\\.[a-zA-Z]+$')
REGEX_NAME_IN_EMAIL = re.compile('^ *"(?P<name>[^"]+)" *<[^>]+> *$')
REGEX_EMAIL_SURROUNDINGS = [
re.compile(
'(?P<space_before>\\s*)\\[(?P<local>[^@]]+)@(?P<domain>[^]]+)\\](?P<space_after>\\s*)'),
re.compile(
'(?P<space_before>\\s*)\\((?P<local>[^@)]+)@(?P<domain>[^)]+)\\)(?P<space_after>\\s*)'),
re.compile(
'(?P<space_before>\\s*)"(?P<local>[^@"]+)@(?P<domain>[^"]+)"(?P<space_after>\\s*)'),
re.compile(
'(?P<space_before>\\s*)\'(?P<local>[^@\']+)@(?P<domain>[^\']+)\'(?P<space_after>\\s*)')]
REGEX_EMAIL_WITH_NAME = re.compile('^ *"[^"]+" *<(?P<email>[^>]+)> *$')
REGEX_INVALID_MAIL = re.compile('^nobody[a-z0-9]*@nowhere.invalid$')
REGEX_ONY_NON_ALPHANUM = re.compile('^[ ]*[^\\w]*[ ]*$')
# global options that can be changed by invoking the command line
OPTION_MATCH_ATTRIBUTES = ['names', 'tel_!work', 'email']
OPTION_NO_MATCH_APPROX = False
OPTION_MATCH_APPROX_SAME_FIRST_LETTER = True
OPTION_MATCH_APPROX_STARTSWITH = False
OPTION_MATCH_APPROX_MIN_LENGTH = 5
OPTION_MATCH_APPROX_MAX_DISTANCE = range(-3, 3)
OPTION_MATCH_APPROX_RATIO = 100
OPTION_UPDATE_GROUP_KEY = True
OPTION_FRENCH_TWEAKS = False
OPTION_DO_NOT_FORCE_ESCAPE_COMMAS = False
SINGLE_INSTANCE_PROPERTIES = {'prodid', 'rev', 'uid'}
def add_attributes(attributes, attr_to_add): # pylint: disable=too-many-branches
"""
Return void
Add an attribute to the attributes list,
checking if the attribute is not already there,
and if it is the case, only append missing parameters
attributes -- the list of attributes
attr_to_add -- the attribute to add
"""
if not isinstance(attributes, list):
raise TypeError("parameter 'attributes' must be a list "
"(type: '" + str(type(attributes)) + "')")
if attr_to_add is None:
raise TypeError("trying to add an undefined attribute")
# TODO: check the attribute type of instance
# note: normalization should have been done before
# search for existing attribute with the same value
existing = False
for attr in attributes: # pylint: disable=too-many-nested-blocks
# found same attribute value
if attr.value == attr_to_add.value:
# append parameters
if hasattr(attr_to_add, 'params') and attr_to_add.params:
if not hasattr(attr, 'params'): # should not happen
raise RuntimeError(
"Attribute '" + attr_to_add.name + "' has no key 'params'")
# for each parameter
for p_name, p_value in attr_to_add.params.items():
# if the value is not empty
if p_value:
# if the parameter is not already registered : add it
if not p_name in attr.params:
setattr(attr, p_name + '_param', p_value)
logging.debug(
"\t\t\tadded param '%s[%s] to '%s'",
p_name, p_value, attr_to_add.value)
# if the parameter exists
else:
# compare the values and append missing ones
p_values = getattr(attr, p_name + '_paramlist')
for pv_to_add in p_value:
if not pv_to_add in p_values:
p_values.append(pv_to_add)
logging.debug(
"\t\t\tadded param '%s[%s] to '%s'",
p_name, pv_to_add, attr_to_add.value)
existing = True
break
# new attribute
if not existing:
# add it to the list
attributes.append(attr_to_add)
logging.debug("\t\t\tadded '%s'", attr_to_add.value)
def collect_attributes(vcards): # pylint: disable=too-many-branches
"""
Return a dict containing all attributes collected from the vCards
Format is attributes_dict[attribute_name] = attribute_value
attribute_value can be a string, a ContentLine or a list of both mixed
vcards -- a dict or list of vcards
"""
if not isinstance(vcards, dict):
if not isinstance(vcards, list):
raise TypeError("parameter 'vcards' must be a dict or list "
"(type: '" + str(type(vcards)) + "')")
# build a lists of ordered vcards
if isinstance(vcards, dict):
vcards_sorted = [v for v in vcards.values()]
elif isinstance(vcards, list):
vcards_sorted = vcards.copy()
logging.debug("Collecting attributes ...")
attributes = {}
# for every vCard in the list
for i in range(len(vcards_sorted)): # pylint: disable=unused-variable,too-many-nested-blocks
vcard1 = vcards_sorted[0]
logging.debug("\tprocessing vcard '%s'", vcard1.fn.value)
# for every attribute of the vCard
for child1 in vcard1.getChildren():
attr1 = child1.name.lower()
if attr1 == 'version':
logging.debug("\t\tskipping VERSION attribute")
continue
# if the attribute has not already been collected
if not attr1 in attributes:
logging.debug("\t\tcollecting attribute '%s'", attr1)
# collect all vCards values for this attribute
for vcard2 in vcards_sorted:
if hasattr(vcard2, attr1):
attrlist = getattr(vcard2, attr1 + '_list')
if attrlist:
if attr1 not in attributes:
attributes[attr1] = []
for attr in attrlist:
add_attributes(attributes[attr1], attr)
# prevent the vcard from being processed again
del vcards_sorted[0]
return attributes
def build_name_from_email(email):
""" Return a string containing a name built from an email """
if not isinstance(email, str):
raise TypeError("parameter 'email' must be a string (type: '" + str(type(email)) + "')")
# don't use a thunderbird invalid email
if email.lower().strip().endswith('nowhere.invalid'):
raise ValueError(
"Trying to extract a name from a Thunderbird invalid email (" + email + ")")
# split both side of the @
email_user, email_domain = email.strip().rsplit("@")
# remove any dash or underscore, or any number
name = REGEX_ANY_DASH_OR_UNDERSCORE.sub(' ', REGEX_ANY_NUMBER.sub('', email_user))
# specific cases where we add the domain as a prefix (without the extension)
if name.lower().startswith(EMAIL_USERS_ADD_DOMAIN):
name = REGEX_WITHOUT_EXTENSION.sub(
'\\1', REGEX_ANY_DASH_OR_UNDERSCORE.sub(' ', email_domain)) + " - " + name
# remove dots
name = name.replace('.', ' ')
# return a sanitized name
return sanitize_name(name)
def sanitize_name(name):
"""
Return a name string with some sanitizing and formatting done.
Sanitizing is:
- removing ICE (In Case of Emergency)
- removing dots
- replacing double spaces by one
- triming edge spaces
- capitalizing the first letter of each word and lowercase the rest
"""
if not isinstance(name, str):
raise TypeError("parameter 'name' must be a string (type: '" + str(type(name)) + "')")
# remove ICE (In Case of Emergency)
# remove dots
# replace double spaces by one
# trim side spaces
# capitalize the first letter of each word and lowercase the rest
sanitized = (REGEX_ICE.sub('', name)
.replace('.', ' ').replace(' ', ' ').replace(' ', ' ').strip()
.title())
# remove data in parentheses/braces if they are equals to the outer data
if REGEX_ANYTHING_BETWEEN_PARENTH_OR_BRACES.search(name):
inner = (
re.sub(
r'[\(\)\[\]]', '',
' '.join(REGEX_ANYTHING_BETWEEN_PARENTH_OR_BRACES.search(name).groups()).strip())
.title())
outer = REGEX_ANYTHING_BETWEEN_PARENTH_OR_BRACES.sub('', name).strip().title()
# match even words in a different order
if inner == outer or token_sort_ratio(inner, outer) == 100:
sanitized = outer
return sanitized
def len_without_parenth_or_braces(string):
""" Return the length with anything between parentheses or braces removed """
if not isinstance(string, str):
raise TypeError("parameter 'string' must be a string (type: '" + str(type(string)) + "')")
return len(REGEX_ANYTHING_BETWEEN_PARENTH_OR_BRACES.sub('', string))
def len_without_index(string):
""" Return the length with the index number in parentheses removed """
if not isinstance(string, str):
raise TypeError("parameter 'string' must be a string (type: '" + str(type(string)) + "')")
return len(REGEX_ANYTHING_BUT_INDEX.sub('\\1', string))
def build_formatted_name(name):
"""
Return a dict with the following keys: 'family', 'given', and optionaly 'suffix'.
The dict return should be used to build a n.value.
name -- a string
"""
if not isinstance(name, str):
raise TypeError("parameter 'name' must be a string (type: '" + str(type(name)) + "')")
name_suffix = None
# the name has parentheses or braces that has to be put as a suffix
if REGEX_ANYTHING_BETWEEN_PARENTH_OR_BRACES.search(name):
name_suffix = ','.join(
REGEX_ANYTHING_BETWEEN_PARENTH_OR_BRACES.search(name).groups()).strip()
name = REGEX_ANYTHING_BETWEEN_PARENTH_OR_BRACES.sub('', name)
# the name has been structured properly to be splitted
if ' - ' in name:
name_splitted = name.split(' - ')
name_family = name_splitted[0]
del name_splitted[0]
# french tweak to handle particle names
elif OPTION_FRENCH_TWEAKS and ' de ' in name.lower():
name_splitted = name.lower().split(' de ')
name_family = 'De ' + name_splitted[0]
del name_splitted[0]
# normal cases
else:
name_splitted = name.split(' ')
name_family = name_splitted[-1]
name_splitted.pop()
name_given = ' '.join(name_splitted)
if name_suffix:
return Name(family=name_family, given=name_given, suffix=name_suffix)
return Name(family=name_family, given=name_given)
def set_name(attributes):
"""
Return void
Collect names values from 'fn' and 'n' fields and the filenames in key 'names'.
Select he longuest one.
Remove keys 'fn', 'n' and 'names'
Rebuild field 'fn' and 'n' from the selected name
attributes -- a dict of attributes
"""
if not isinstance(attributes, dict):
raise TypeError("parameter 'attributes' must be a dict "
"(type: '" + str(type(attributes)) + "')")
logging.debug("Setting name ...")
# collect names
logging.debug("\tcollecting names ...")
available_names = []
if 'fn' in attributes:
for attr_fn in attributes['fn']:
name = sanitize_name(attr_fn.value)
if not name in available_names:
available_names.append(name)
if 'n' in attributes:
for attr_n in attributes['n']:
name = sanitize_name(str(attr_n.value))
if not name in available_names:
available_names.append(name)
if 'email' in attributes:
for attr_m in attributes['email']:
n_matches = REGEX_NAME_IN_EMAIL.match(attr_m.value.strip())
if n_matches:
name = sanitize_name(n_matches.group('name'))
if not name in available_names:
available_names.append(name)
logging.debug("\tnames collected:")
for name in available_names:
logging.debug("\t\t'%s'", name)
# select the most relevant name
selected_name = select_most_relevant_name(available_names)
# delete names attributes
del attributes['fn']
del attributes['n']
# rebuild them from the name selected
attributes['fn'] = selected_name
attributes['n'] = build_formatted_name(selected_name)
def select_most_relevant_name(names):
""" Return the longuest name (without parenthese or braces). """
if not isinstance(names, list):
raise TypeError("parameter 'names' must be a list (type: '" + str(type(names)) + "')")
if not names:
raise ValueError("Trying to select a name from an empty list of names")
logging.debug("\t\tselecting the most relevant name from:")
logging.debug("\t\t\t%s", ', '.join(names))
selected_name = None
longuest_length = 0
pos = 0
for name in names:
if name == "":
continue
if not name:
raise TypeError("parameter 'names[" + str(pos) + "]' is undefined")
length = len_without_parenth_or_braces(name)
# longuer
if length > longuest_length:
longuest_length = length
selected_name = name
# equal length
elif length == longuest_length:
# longuer without index
if len_without_index(name) > len_without_index(selected_name):
selected_name = name
# equal length without index
elif len_without_index(name) == len_without_index(selected_name):
# if no index and the selected has one
if len_without_index(name) == len(name) \
and len_without_index(selected_name) != len(selected_name):
longuest_length = length
selected_name = name
pos += 1
logging.debug("\t\tselected: '%s'", selected_name)
if not selected_name: # should not happen
raise RuntimeError("Failed to select a name")
elif '=' in selected_name:
raise RuntimeError("Invalid selected name '" + selected_name + "' "
"(contains an equals sign: maybe an undecoded string)")
return selected_name
def build_vcard(attributes): #pylint: disable=too-many-statements,too-many-branches
"""
Return a vcard build from the attributes list
attributes -- a dict of attributes
"""
if not isinstance(attributes, dict):
raise TypeError("parameter 'attributes' must be a dict "
"(type: '" + str(type(attributes)) + "')")
logging.debug("Building vcard ...")
vcard = vCard()
single_inst_props = set()
for a_name, attr in attributes.items(): # pylint: disable=too-many-nested-blocks
#logging.debug("\tprocessing '%s' -> '%s'", a_name, attr)
if attr:
if a_name == 'n':
if hasattr(attr, 'suffix'):
vcard.add('n').value = Name( \
family=attr.family, \
given=attr.given, \
suffix=attr.suffix \
)
else:
vcard.add('n').value = Name(\
family=attr.family, \
given=attr.given \
)
logging.debug("\t%s: %s", a_name, str(vcard.n.value).replace(' ', '').strip())
elif a_name == 'org':
if not isinstance(attr, list):
raise RuntimeError("'org' collected attributes should be a list, "
"'" + str(type(attr)) + "' found")
org = vcard.add('org')
org.value = []
for attr_org in attr:
if isinstance(attr_org, str):
org.value.append(attr_org)
elif isinstance(attr_org, ContentLine):
org.value += attr_org.value
else:
raise RuntimeError("'org' value should be string or ContentLine, "
"'" + str(type(attr_org)) + "' found")
logging.debug("\t%s: %s", a_name, vcard.org.value)
else:
if isinstance(attr, str):
vcard.add(a_name).value = attr
logging.debug("\t%s: %s", a_name, attr)
elif isinstance(attr, ContentLine):
item_added = vcard.add(a_name)
logging.debug("\t%s: %s", a_name, str(attr.value))
item_added.value = attr.value
if hasattr(attr, 'params') and attr.params:
for p_name, p_value in attr.params.items():
setattr(item_added, p_name + '_param', p_value)
logging.debug("\t\twith param '%s': '%s'", p_name, p_value)
else:
for a_item in attr:
if a_item:
if isinstance(a_item, str):
vcard.add(a_name).value = a_item
logging.debug("\t%s: %s", a_name, a_item)
elif isinstance(a_item, ContentLine):
if a_name in SINGLE_INSTANCE_PROPERTIES:
if a_name in single_inst_props:
continue
else:
single_inst_props.add(a_name)
item_added = vcard.add(a_name)
logging.debug("\t%s: %s", a_name, a_item.value)
item_added.value = a_item.value
if hasattr(a_item, 'params') and a_item.params:
for p_name, p_value in a_item.params.items():
setattr(item_added, p_name + '_param', p_value)
logging.debug("\t\twith param '%s': '%s'", p_name, p_value)
logging.debug("vcard built:\n%s", vcard.serialize())
return vcard
def close_parentheses_or_braces(string):
"""
Add a missing parenthese or brace to close one open
If the paranethese or brace is at the begining of the string,
it will be removed instead. That's because if it was closed with a pair
at the end of the string, the whole string will be contained in
parentheses or braces which will be ignored in the processing.
"""
if '(' in string and not ')' in string:
if re.match('^ *\\(', string):
string = re.sub('^ *\\(', '', string)
else:
string += ')'
elif '[' in string and not ']' in string:
if re.match('^ *\\[', string):
string = re.sub('^ *\\[', '', string)
else:
string += ']'
return string
def collect_vcard_names(vcard): # pylint: disable=too-many-statements,too-many-branches
""" Collect all vcard possible names in fields 'fn', 'n' and 'email' """
if not isinstance(vcard, Component):
raise TypeError("parameter 'vcard' must be a vobject.base.Component "
"(type: '" + str(type(vcard)) + "')")
# collect names
logging.debug("\tcollecting names %s ...",
"for '" + vcard.fn.value + "'" if hasattr(vcard, 'fn') else '')
available_names = []
for name_key in ['fn', 'n']: # pylint: disable=too-many-nested-blocks
if hasattr(vcard, name_key):
for attr_n in getattr(vcard, name_key + '_list'):
value = close_parentheses_or_braces(str(attr_n.value).strip())
if not REGEX_ONY_NON_ALPHANUM.match(value):
if '@' in value:
normalized_value = value.strip()
for regex in REGEX_EMAIL_SURROUNDINGS:
normalized_value = regex.sub(
'\\g<space_before><\\g<local>@\\g<domain>>\\g<space_after>',
normalized_value).replace('<<', '<').replace('>>', '>')
logging.debug("\t\tnormalized value '%s' from '%s'",
normalized_value, value)
realname, email = parseaddr(normalized_value)
logging.debug("\t\tparsed email: '%s', '%s' from '%s'",
realname, email, normalized_value)
if realname or email:
# Special case to be able to process value with double email like:
# In this case, the parsing will return an empty name, and the 1st
# email as email, ignoring the second one.
# In order to force the processing of the second email, we remove
# the 1st email from the original value and re-parse to get the 2nd
# one.
if not realname and email and normalized_value.count('@') == 2:
realname = email
_, email = parseaddr(normalized_value.replace(email, ''))
logging.debug("\t\tforce parsed email: '%s', '%s' from '%s'",
realname, email, normalized_value)
if realname:
if '@' in realname:
normalized_realname = realname.strip()
for regex in REGEX_EMAIL_SURROUNDINGS:
normalized_realname = regex.sub(
'\\g<space_before><\\g<local>@'
'\\g<domain>>\\g<space_after>',
normalized_realname).\
replace('<<', '<').replace('>>', '>')
logging.debug("\t\tnormalized sub-value '%s' from '%s'",
normalized_realname, realname)
_realname, _email = parseaddr(normalized_realname)
logging.debug("\t\tparsed email: '%s', '%s' from '%s'",
_realname, _email, normalized_realname)
if _realname or _email:
if _realname:
name = sanitize_name(_realname)
if not name in available_names:
available_names.append(name)
logging.debug(
"\t\tadding '%s' from built email for '%s'",
name, name_key)
if _email:
name = build_name_from_email(_email)
if not name in available_names:
available_names.append(name)
logging.debug(
"\t\tadding '%s' from built email for '%s'",
name, name_key)
elif normalized_realname.count('@') == 1:
name = build_name_from_email(normalized_realname)
if not name in available_names:
available_names.append(name)
logging.debug(
"\t\tadding '%s' from built email for '%s'",
name, name_key)
else:
logging.debug(
"\t\tcan't parse name value containing email '%s'",
normalized_realname)
if email:
name = build_name_from_email(email)
if not name in available_names:
available_names.append(name)
logging.debug("\t\tadding '%s' from built email for '%s'",
name, name_key)
elif normalized_value.count('@') == 1:
name = build_name_from_email(normalized_value)
if not name in available_names:
available_names.append(name)
logging.debug("\t\tadding '%s' from built email for '%s'",
name, name_key)
else:
logging.debug("\t\tcan't parse name value containing email '%s'",
normalized_value)
else:
name = sanitize_name(value)
if not name in available_names:
available_names.append(name)
logging.debug("\t\tadding '%s' from '%s'", name, name_key)
else:
logging.debug("\t\tskipping non-alphanum name value: '%s'", value)
if hasattr(vcard, 'email'):
for email in vcard.email_list:
# not a thunderbird invalid email
if not email.value.lower().strip().endswith('nowhere.invalid'):
n_matches = REGEX_NAME_IN_EMAIL.match(email.value)
if n_matches:
name = sanitize_name(n_matches.group('name'))
if not name in available_names:
available_names.append(name)
logging.debug("\t\tadding '%s' from 'email'", name)
# no name found, but there is an email : build a name from it
if not available_names and hasattr(vcard, 'email'):
for email in vcard.email_list:
name = build_name_from_email(email.value)
if not name in available_names:
available_names.append(name)
logging.debug("\t\tadding '%s' from built 'email'", name)
# no name found, but there is an org : use it as name
if not available_names and hasattr(vcard, 'org'): # pylint: disable=too-many-nested-blocks
for org in vcard.org_list:
if org.value:
if isinstance(org.value, list):
for org_item in org.value:
if not REGEX_ONY_NON_ALPHANUM.match(org_item.strip()):
name = sanitize_name(org_item)
if not name in available_names:
available_names.append(name)
logging.debug("\t\tadding '%s' from 'org' list", name)
elif not REGEX_ONY_NON_ALPHANUM.match(org.value.strip()):
name = sanitize_name(org.value)
if not name in available_names:
available_names.append(name)
logging.debug("\t\tadding '%s' from 'org'", name)
# no name found, but there is a tel : build a name from it
if not available_names and hasattr(vcard, 'tel'):
name = 'tel_' + str(vcard.tel.value).strip()
if name not in available_names:
available_names.append(name)
logging.debug("\t\tadding '%s' from built 'tel'", name)
# what we have found
logging.debug("\tnames collected:")
for name in available_names:
logging.debug("\t\t'%s'", name)
return available_names
def write_vcard_to_file(vcard, file_path):
"""
Return void.
Serialize the vcard then write it to the specified file.
vcard -- the vcard
file_path -- the file path
"""
if not isinstance(vcard, Component):
raise TypeError("parameter 'vcard' must be a vobject.base.Component "
"(type: '" + str(type(vcard)) + "')")
if not isinstance(file_path, str):
raise TypeError("parameter 'file_path' must be a string "
"(type: '" + str(type(file_path)) + "')")
# serialize the vcard to produce a string content
file_content = vcard.serialize()
# check if the file already exists
if exists(file_path): # should not happen
raise RuntimeError("Failed to write vcard to file '" + file_path + "' : "
"file already exists.")
# open file in write mode
with open(file_path, 'w') as c_file:
try:
# write to it
c_file.write(file_content)
logging.debug("Writen vCard file '%s'", file_path)
except OSError as err:
logging.error("Failed to write file '%s'", file_path)
logging.error(err)
raise
logging.debug("\tWriten vCard to file '%s'", file_path)
def normalize(vcard, selected_name, \
do_not_overwrite_names=False, \
mv_name_parenth_braces_to_note=False, \
do_not_remove_name_in_email=False \
): # pylint: disable=too-many-statements,too-many-branches
"""
Return void.
Normalize a vcard.
Normalizing consist of :
- removing 'version' attribute
- overwriting names attributes 'fn' and 'n' with the one specified (if not disabled by option)
- adding missing names attributes 'fn' and 'n'
- moving name's content inside parenth or braces into the note attribute (if enabled by option)
- removing thunderbird invalid email form emails
- removing name in email (if not disabled by option)
- removing space in tels numbers
- replacing '+33' by '0' in tels numbers (if french tweaks are enabled)
Arguments:
vcard -- the vcard
selected_name -- a name for the vcard (used to overwrite existing ones)
Options:
do_not_overwrite_names
mv_name_parenth_braces_to_note
do_not_remove_name_in_email
Global options used:
OPTION_FRENCH_TWEAKS
"""
if not isinstance(vcard, Component):
raise TypeError("parameter 'vcard' must be a vobject.base.Component "
"(type: '" + str(type(vcard)) + "')")
if not isinstance(selected_name, str):
raise TypeError("parameter 'selected_name' must be a string "
"(type: '" + str(type(selected_name)) + "')")
# remove vCard version
if hasattr(vcard, 'version'):
del vcard.version
logging.debug("\t\tremoved VERSION attribute")
# overwrite names with the selected one
if not do_not_overwrite_names:
# remove all name fields
if hasattr(vcard, 'fn'):
del vcard.fn
logging.debug("\t\tremoved 'fn' attribute")
if hasattr(vcard, 'n'):
del vcard.n
logging.debug("\t\tremoved 'n' attribute")
# add missing required name fields 'fn' and 'n'
if not hasattr(vcard, 'fn'):
vcard.add('fn').value = selected_name
#vcard.add('fn').value = (
# REGEX_ANYTHING_BETWEEN_PARENTH_OR_BRACES.sub('', selected_name).strip())
logging.debug("\t\tadded missing 'fn' attribute with value '%s'", vcard.fn.value)
if not hasattr(vcard, 'n'):
vcard.add('n').value = build_formatted_name(selected_name)
logging.debug("\t\tadded missing 'n' attribute with value '%s'",
str(vcard.n.value).replace(' ', ' ').strip())
# move name's content inside parentheses (or braces) into the note attribute
if mv_name_parenth_braces_to_note:
for name_key in ['fn', 'n']:
for attr_n in getattr(vcard, name_key + '_list'):
value = close_parentheses_or_braces(str(attr_n.value).replace(' ', ' ').strip())
if REGEX_ANYTHING_BETWEEN_PARENTH_OR_BRACES.search(value):
logging.debug("\t\tname['%s'] '%s' has parentheses or braces", name_key, value)
inner = re.sub(
r'[\(\)\[\]]', '',
(' '.join(REGEX_ANYTHING_BETWEEN_PARENTH_OR_BRACES.search(value).groups())
.strip()))
outer = REGEX_ANYTHING_BETWEEN_PARENTH_OR_BRACES.sub('', value).strip()
if name_key == 'n':
attr_n.value = build_formatted_name(outer)
logging.debug("\t\tname['%s'] is now: '%s'",
name_key, str(attr_n.value).replace(' ', ' ').strip())
else:
attr_n.value = outer
logging.debug("\t\tname['%s'] is now: '%s'", name_key, attr_n.value)
if hasattr(vcard, 'note'):
vcard.note.value += '\n' + inner
else:
vcard.add('note').value = inner
logging.debug("\t\t'note' is now: '%s'", vcard.note.value)
# normalize email
if hasattr(vcard, 'email') and vcard.email_list:
number_of_email = len(vcard.email_list)
index = 0
while index < number_of_email:
email = vcard.email_list[index]
email.value = email.value.strip().lower()
# filter out thunderbird invalid email
if email.value.endswith('@nowhere.invalid'):
del vcard.email_list[index]
number_of_email -= 1
# normal email
else:
m_match = REGEX_EMAIL_WITH_NAME.match(email.value)
if m_match and not do_not_remove_name_in_email:
email.value = ''.join(m_match.group('email'))
index += 1
if not vcard.email_list:
del vcard.email_list
# normalize tel
if hasattr(vcard, 'tel') and vcard.tel_list:
for tel in vcard.tel_list:
tel.value = tel.value.strip().replace(' ', '')
if OPTION_FRENCH_TWEAKS:
# re-localize
if tel.value.startswith('+33'):
tel.value = tel.value.replace('+33', '0')
# TODO: strip all values
def get_vcards_from_files(files, \
do_not_fix_and_convert=False, \
do_not_overwrite_names=False, \
mv_name_parenth_braces_to_note=False, \
do_not_remove_name_in_email=False \
): # pylint: disable=too-many-locals
"""
Return a dict of vobject.vcard.
vCards will be normalized.
arguments:
files -- a list of the vcf/vcard files to read from
options:
do_not_overwrite_names -- do not overwrite existing field names with the one selected
do_not_remove_name_from_email -- do not remove name from email (like: "John Doe" <[email protected]>)
"""
if not isinstance(files, list):
raise TypeError("parameter 'files' must be a list (type: '" + str(type(files)) + "')")
# read all files
logging.info("Reading/parsing individual vCard files ...")
vcards = {}
file_names_max_length = max([len(basename(x)) for x in files])
selected_name = None
logging.debug("file names max length: %d", file_names_max_length)
for f_path in files:
f_name = basename(f_path)
# read the file content and fix it + converting vCard from 2.1 to 3.0
if not do_not_fix_and_convert:
content = fix_and_convert_to_v3(f_path)
else:
with open(f_path, 'r') as vfile:
content = vfile.read()
try:
# parse the content and create a vcard list
vcard_list = readComponents(content)
# add the vcards to the global vcards list
count = 0
for vcard in vcard_list:
count += 1
# collect names
available_names = collect_vcard_names(vcard)
# select the most relevant name
selected_name = select_most_relevant_name(available_names)
# normalize the fields
normalize(vcard, selected_name, do_not_overwrite_names,
mv_name_parenth_braces_to_note, do_not_remove_name_in_email)
# force the full parsing of the vcard to prevent further crash
try:
vcard.serialize()
except TypeError as err:
logging.error("Failed to parse vCard [%d] '%s' of file '%s'",
count, selected_name, f_path)
logging.error(err)
raise
# increment the name if already used
if selected_name in vcards:
index = 0
name_indexed = selected_name
while name_indexed in vcards:
index += 1
name_indexed = selected_name + "(" + str(index) + ")"
selected_name = name_indexed
# add the card to the list
vcards[selected_name] = vcard
# sum up the parsing for that file
logging.info(
('\t{0:<' + str(file_names_max_length) + '} : {1:>5} vCards parsed').format(
f_name, count))
# parsing failure (advenced)
except (TypeError, UnicodeDecodeError, binascii.Error) as err:
logging.error("Failed to parse vCard [%d] (after '%s') of file '%s'",
count, selected_name, f_path)
logging.error(err)
raise
# parsing failure (raw)
except ParseError as err:
logging.error("Failed to parse vCard [%d] of file '%s'", count, f_path)
logging.error(err)
raise
# any other exception
except Exception as err:
logging.error(
"An exception occured when processing vCard [%d] of file '%s'", count, f_path)
logging.error(err)
logging.error(
"Maybe the file is invalid ? "
"Please ensure it is not empty nor contains weird data "
"and if needed exclude it from the batch and re-run it.")
raise
return vcards
def deduplicate(vcard):
""" Remove duplicated fields and merge their parameters """
if not isinstance(vcard, Component):
raise TypeError("parameter 'vcard' must be a vobject.base.Component "
"(type: '" + str(type(vcard)) + "')")
# collect attributes for all vCards
attributes = collect_attributes([vcard])
# select a name (filter 'fn' and 'n' attributes)
set_name(attributes)
# save the remaining attributes to the merged vCard
return build_vcard(attributes)
def merge(vcard, *vcards_to_merge):
""" Merge vcards into one by just appending all attributes """
if not isinstance(vcard, Component):
raise TypeError("parameter 'vcard' must be a vobject.base.Component "
"(type: '" + str(type(vcard)) + "')")
if vcards_to_merge:
pos = 0
for vcard_to_merge in vcards_to_merge:
if not isinstance(vcard_to_merge, Component):
raise TypeError(
"parameter 'vcard_to_merge[" + str(pos) + "]' must be a vobject.base.Component "
"(type: '" + str(type(vcard_to_merge)) + "')")
pos += 1
for vcard_to_merge in vcards_to_merge:
for vcard_child in vcard_to_merge.getChildren():
for attr in getattr(vcard_to_merge, vcard_child.name + '_list'):
attribute = vcard.add(vcard_child.name)
attribute.value = attr.value
attribute.params = attr.params
def fix_and_convert_to_v3(file_path): # pylint: disable=too-many-statements,too-many-branches,too-many-locals
"""
Return a string containing the file content fixed and converted to vcard 3.0
Fixes:
* remove DOS CRLF and Apple CR
* concatenation of multilines quoted-printable value (not the binary data)
* convert keys to upper case
* remove double QUOTED-PRINTABLE
* factorize TYPE parameters