-
Notifications
You must be signed in to change notification settings - Fork 66
/
carddav_object.py
1547 lines (1443 loc) · 66.1 KB
/
carddav_object.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
# -*- coding: utf-8 -*-
# contact object class
# vcard version 3.0: https://tools.ietf.org/html/rfc2426
# vcard version 4.0: https://tools.ietf.org/html/rfc6350
import datetime
import locale
import os
import re
import sys
from atomicwrites import atomic_write
import vobject
import yaml
from . import helpers
from .object_type import ObjectType
class CarddavObject:
def __init__(self, address_book, filename, supported_private_objects,
vcard_version):
self.vcard = None
self.address_book = address_book
self.filename = filename
self.excluded_data = []
self.supported_private_objects = supported_private_objects
# vcard v3.0 supports the following type values
self.phone_types_v3 = ["bbs", "car", "cell", "fax", "home", "isdn",
"msg", "modem", "pager", "pcs", "video",
"voice", "work"]
self.email_types_v3 = ["home", "internet", "work", "x400"]
self.address_types_v3 = ["dom", "intl", "home", "parcel", "postal",
"work"]
# vcard v4.0 supports the following type values
self.phone_types_v4 = ["text", "voice", "fax", "cell", "video",
"pager", "textphone", "home", "work"]
self.email_types_v4 = ["home", "internet", "work"]
self.address_types_v4 = ["home", "work"]
# load vcard
if self.filename is None:
# create new vcard object
self.vcard = vobject.vCard()
# add uid
self.add_uid(helpers.get_random_uid())
# use uid for vcard filename
self.filename = os.path.join(address_book.get_path(),
self.get_uid() + ".vcf")
# add preferred vcard version
self.add_version(vcard_version)
else:
# create vcard from .vcf file
try:
file = open(self.filename, "r")
contents = file.read()
file.close()
except IOError:
raise
# create vcard object
try:
self.vcard = vobject.readOne(contents)
except Exception:
# due to a bug in the object library 0.9.2 it's possible, that
# the library fails to parse the photo attribute
# workaround: strip photo data from vcard string and add it back
# after editing of vcard file was successful
try:
self.vcard = vobject.readOne(
self.filter_base64_encoded_attributes(contents))
except Exception:
# if creation still fails, try to repair some vcard
# attributes
try:
self.vcard = vobject.readOne(
self.filter_invalid_tags(contents))
except Exception:
raise
# fix organisation values
self.get_organisations()
#######################################
# factory methods to create new contact
#######################################
@classmethod
def new_contact(cls, address_book, supported_private_objects, version):
""" use this to create a new and empty contact """
return cls(address_book, None, supported_private_objects, version)
@classmethod
def from_file(cls, address_book, filename, supported_private_objects):
"""
Use this if you want to create a new contact from an existing .vcf file
"""
return cls(address_book, filename, supported_private_objects, None)
@classmethod
def from_user_input(
cls, address_book, user_input, supported_private_objects, version):
""" Use this if you want to create a new contact from user input """
contact = cls(address_book, None, supported_private_objects, version)
contact.process_user_input(user_input)
return contact
@classmethod
def from_existing_contact_with_new_user_input(cls, contact, user_input):
"""
use this if you want to clone an existing contact and replace its data
with new user input in one step
"""
contact = cls(contact.get_address_book(), contact.get_filename(),
contact.get_supported_private_objects(), None)
contact.process_user_input(user_input)
return contact
######################################
# overwrite some default class methods
######################################
def __str__(self):
return self.get_full_name()
def __eq__(self, other):
if isinstance(other, CarddavObject) and \
self.print_vcard(show_address_book=False, show_uid=False) == \
other.print_vcard(show_address_book=False, show_uid=False):
return True
return False
def __ne__(self, other):
return not self == other
#####################
# getters and setters
#####################
def get_address_book(self):
return self.address_book
def get_filename(self):
return self.filename
def set_filename(self, filename):
self.filename = filename
def get_supported_private_objects(self):
return self.supported_private_objects
def get_rev(self):
"""
:rtype: str
"""
try:
return self.vcard.rev.value
except AttributeError:
return ""
def add_rev(self, dt):
rev_obj = self.vcard.add('rev')
rev_obj.value = "%.4d%.2d%.2dT%.2d%.2d%.2dZ" % (
dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
def get_uid(self):
"""
:rtype: str
"""
try:
return self.vcard.uid.value
except AttributeError:
return ""
def add_uid(self, uid):
uid_obj = self.vcard.add('uid')
uid_obj.value = helpers.convert_to_vcard(
"uid", uid, ObjectType.string)
def get_version(self):
"""
:rtype: str
"""
try:
return self.vcard.version.value
except AttributeError:
return ""
def add_version(self, vcard_version):
version_obj = self.vcard.add('version')
version_obj.value = helpers.convert_to_vcard(
"version", vcard_version, ObjectType.string)
def get_name_prefixes(self):
"""
:rtype: list(str)
"""
try:
prefix_list = self.vcard.n.value.prefix
except AttributeError:
prefix_list = []
else:
# check if list only contains an empty string ([""])
if not ''.join(prefix_list):
prefix_list = []
return prefix_list if isinstance(prefix_list, list) else [prefix_list]
def get_first_names(self):
"""
:rtype: list(str)
"""
try:
first_name_list = self.vcard.n.value.given
except AttributeError:
first_name_list = []
else:
# check if list only contains an empty string ([""])
if not ''.join(first_name_list):
first_name_list = []
return first_name_list if isinstance(first_name_list, list) \
else [first_name_list]
def get_additional_names(self):
"""
:rtype: list(str)
"""
try:
additional_name_list = self.vcard.n.value.additional
except AttributeError:
additional_name_list = []
else:
# check if list only contains an empty string ([""])
if not ''.join(additional_name_list):
additional_name_list = []
return additional_name_list if isinstance(additional_name_list, list) \
else [additional_name_list]
def get_last_names(self):
"""
:rtype: list(str)
"""
try:
last_name_list = self.vcard.n.value.family
except AttributeError:
last_name_list = []
else:
# check if list only contains an empty string ([""])
if not ''.join(last_name_list):
last_name_list = []
return last_name_list if isinstance(last_name_list, list) \
else [last_name_list]
def get_name_suffixes(self):
"""
:rtype: list(str)
"""
try:
suffix_list = self.vcard.n.value.suffix
except AttributeError:
suffix_list = []
else:
# check if list only contains an empty string ([""])
if not ''.join(suffix_list):
suffix_list = []
return suffix_list if isinstance(suffix_list, list) else [suffix_list]
def get_full_name(self):
"""
:rtype: str
"""
try:
return self.vcard.fn.value
except AttributeError:
return ""
def get_first_name_last_name(self):
"""
:rtype: str
"""
names = []
if self.get_first_names():
names += self.get_first_names()
if self.get_additional_names():
names += self.get_additional_names()
if self.get_last_names():
names += self.get_last_names()
if names:
return helpers.list_to_string(names, " ")
else:
return self.get_full_name()
def get_last_name_first_name(self):
"""
:rtype: str
"""
last_names = []
if self.get_last_names():
last_names += self.get_last_names()
first_and_additional_names = []
if self.get_first_names():
first_and_additional_names += self.get_first_names()
if self.get_additional_names():
first_and_additional_names += self.get_additional_names()
if last_names and first_and_additional_names:
return "%s, %s" % (
helpers.list_to_string(last_names, " "),
helpers.list_to_string(first_and_additional_names, " "))
elif last_names:
return helpers.list_to_string(last_names, " ")
elif first_and_additional_names:
return helpers.list_to_string(first_and_additional_names, " ")
else:
return self.get_full_name()
def add_name(self, prefix, first_name, additional_name, last_name, suffix):
# n
name_obj = self.vcard.add('n')
name_obj.value = vobject.vcard.Name(
prefix=helpers.convert_to_vcard(
"name prefix", prefix, ObjectType.string_or_list_with_strings),
given=helpers.convert_to_vcard(
"first name", first_name,
ObjectType.string_or_list_with_strings),
additional=helpers.convert_to_vcard(
"additional name", additional_name,
ObjectType.string_or_list_with_strings),
family=helpers.convert_to_vcard(
"last name", last_name,
ObjectType.string_or_list_with_strings),
suffix=helpers.convert_to_vcard(
"name suffix", suffix, ObjectType.string_or_list_with_strings))
# fn
if not self.vcard.getChildValue("fn") \
and (self.get_first_names() or self.get_last_names()):
names = []
if self.get_name_prefixes():
names += self.get_name_prefixes()
if self.get_first_names():
names += self.get_first_names()
if self.get_last_names():
names += self.get_last_names()
if self.get_name_suffixes():
names += self.get_name_suffixes()
name_obj = self.vcard.add('fn')
name_obj.value = helpers.list_to_string(names, " ")
def get_organisations(self):
"""
:returns: list of organisations, sorted alphabetically
:rtype: list(list(str))
"""
organisations = []
for child in self.vcard.getChildren():
if child.name == "ORG":
if not isinstance(child.value, list):
# some newer versions of vobject module don't split the
# organisation attribute properly at the "," character
# so fix that by splitting at ?; manually and return a list
# whereas ? could be any char except the \ (backslash)
org_list = []
start_index = 0
for match in re.finditer("[^\\\\];", child.value):
org_list.append(
child.value[start_index:match.start()+1])
start_index = match.start()+2
child.value = org_list + [child.value[start_index:]]
# remove all backslashes except \n
organisations.append(
[x.replace("\\n", "bckslshn").replace("\\", "")
.replace("bckslshn", "\n") for x in child.value])
return sorted(organisations)
def add_organisation(self, organisation):
org_obj = self.vcard.add('org')
org_obj.value = helpers.convert_to_vcard(
"organisation", organisation, ObjectType.list_with_strings)
# check if fn attribute is already present
if not self.vcard.getChildValue("fn") \
and self.get_organisations():
# if not, set fn to organisation name
org_value = helpers.list_to_string(self.get_organisations()[0],
", ")
name_obj = self.vcard.add('fn')
name_obj.value = org_value.replace("\n", " ").replace("\\", "")
showas_obj = self.vcard.add('x-abshowas')
showas_obj.value = "COMPANY"
def get_titles(self):
"""
:rtype: list(list(str))
"""
titles = []
for child in self.vcard.getChildren():
if child.name == "TITLE":
titles.append(child.value)
return sorted(titles)
def add_title(self, title):
title_obj = self.vcard.add('title')
title_obj.value = helpers.convert_to_vcard("title", title,
ObjectType.string)
def get_roles(self):
"""
:rtype: list(list(str))
"""
roles = []
for child in self.vcard.getChildren():
if child.name == "ROLE":
roles.append(child.value)
return sorted(roles)
def add_role(self, role):
role_obj = self.vcard.add('role')
role_obj.value = helpers.convert_to_vcard("role", role,
ObjectType.string)
def get_phone_numbers(self):
"""
: returns: dict of type and phone number list
:rtype: dict(str, list(str))
"""
phone_dict = {}
for child in self.vcard.getChildren():
if child.name == "TEL":
type = helpers.list_to_string(
self.get_types_for_vcard_object(child, "voice"), ", ")
if phone_dict.get(type) is None:
phone_dict[type] = []
try:
# detect uri
if child.params.get("VALUE")[0] == "uri":
phone_dict[type].append(child.value.split(":")[1])
except (IndexError, TypeError):
phone_dict[type].append(child.value)
# sort phone number lists
for number_list in phone_dict.values():
number_list.sort()
return phone_dict
def add_phone_number(self, type, number):
standard_types, custom_types, pref = self.parse_type_value(
helpers.string_to_list(type, ","), number, self.phone_types_v4 if
self.get_version() == "4.0" else self.phone_types_v3)
if len(standard_types) == 0 and len(custom_types) == 0 and pref == 0:
raise ValueError("Error: label for phone number " + number +
" is missing.")
elif len(custom_types) > 1:
raise ValueError("Error: phone number " + number + " got more "
"than one custom label: " +
helpers.list_to_string(custom_types, ", "))
else:
phone_obj = self.vcard.add('tel')
if self.get_version() == "4.0":
phone_obj.value = "tel:%s" % helpers.convert_to_vcard(
"phone number", number, ObjectType.string)
phone_obj.params['VALUE'] = ["uri"]
if pref > 0:
phone_obj.params['PREF'] = str(pref)
else:
phone_obj.value = helpers.convert_to_vcard(
"phone number", number, ObjectType.string)
if pref > 0:
standard_types.append("pref")
if standard_types:
phone_obj.params['TYPE'] = standard_types
if custom_types:
number_of_custom_phone_number_labels = 0
for label in self.vcard.getChildren():
if label.name == "X-ABLABEL" \
and label.group.startswith("itemtel"):
number_of_custom_phone_number_labels += 1
group_name = "itemtel%d" % (
number_of_custom_phone_number_labels+1)
phone_obj.group = group_name
label_obj = self.vcard.add('x-ablabel')
label_obj.group = group_name
label_obj.value = custom_types[0]
def get_email_addresses(self):
"""
: returns: dict of type and email address list
:rtype: dict(str, list(str))
"""
email_dict = {}
for child in self.vcard.getChildren():
if child.name == "EMAIL":
type = helpers.list_to_string(
self.get_types_for_vcard_object(child, "internet"), ", ")
if email_dict.get(type) is None:
email_dict[type] = []
email_dict[type].append(child.value)
# sort email address lists
for email_list in email_dict.values():
email_list.sort()
return email_dict
def add_email_address(self, type, address):
standard_types, custom_types, pref = self.parse_type_value(
helpers.string_to_list(type, ","), address, self.email_types_v4 if
self.get_version() == "4.0" else self.email_types_v3)
if len(standard_types) == 0 and len(custom_types) == 0 and pref == 0:
raise ValueError("Error: label for email address " + address +
" is missing.")
elif len(custom_types) > 1:
raise ValueError("Error: email address " + address + " got more "
"than one custom label: " +
helpers.list_to_string(custom_types, ", "))
else:
email_obj = self.vcard.add('email')
email_obj.value = helpers.convert_to_vcard(
"email address", address, ObjectType.string)
if self.get_version() == "4.0":
if pref > 0:
email_obj.params['PREF'] = str(pref)
else:
if pref > 0:
standard_types.append("pref")
if standard_types:
email_obj.params['TYPE'] = standard_types
if custom_types:
number_of_custom_email_labels = 0
for label in self.vcard.getChildren():
if label.name == "X-ABLABEL" \
and label.group.startswith("itememail"):
number_of_custom_email_labels += 1
group_name = "itememail%d" % (number_of_custom_email_labels+1)
email_obj.group = group_name
label_obj = self.vcard.add('x-ablabel')
label_obj.group = group_name
label_obj.value = custom_types[0]
def get_post_addresses(self):
"""
: returns: dict of type and post address list
:rtype: dict(str, list(dict(str,list|str)))
"""
post_adr_dict = {}
for child in self.vcard.getChildren():
if child.name == "ADR":
type = helpers.list_to_string(
self.get_types_for_vcard_object(child, "home"), ", ")
if post_adr_dict.get(type) is None:
post_adr_dict[type] = []
post_adr_dict[type].append(
{
"box": child.value.box,
"extended": child.value.extended,
"street": child.value.street,
"code": child.value.code,
"city": child.value.city,
"region": child.value.region,
"country": child.value.country
})
# sort post address lists
for post_adr_list in post_adr_dict.values():
post_adr_list.sort(key=lambda x: (
helpers.list_to_string(x['city'], " ").lower(),
helpers.list_to_string(x['street'], " ").lower()))
return post_adr_dict
def get_formatted_post_addresses(self):
formatted_post_adr_dict = {}
for type, post_adr_list in self.get_post_addresses().items():
formatted_post_adr_dict[type] = []
for post_adr in post_adr_list:
strings = []
if post_adr.get("street"):
strings.append(
helpers.list_to_string(post_adr.get("street"), "\n"))
if post_adr.get("box") and post_adr.get("extended"):
strings.append("%s %s" % (
helpers.list_to_string(post_adr.get("box"), " "),
helpers.list_to_string(post_adr.get("extended"), " ")))
elif post_adr.get("box"):
strings.append(
helpers.list_to_string(post_adr.get("box"), " "))
elif post_adr.get("extended"):
strings.append(
helpers.list_to_string(post_adr.get("extended"), " "))
if post_adr.get("code") and post_adr.get("city"):
strings.append("%s %s" % (
helpers.list_to_string(post_adr.get("code"), " "),
helpers.list_to_string(post_adr.get("city"), " ")))
elif post_adr.get("code"):
strings.append(
helpers.list_to_string(post_adr.get("code"), " "))
elif post_adr.get("city"):
strings.append(
helpers.list_to_string(post_adr.get("city"), " "))
if post_adr.get("region") and post_adr.get("country"):
strings.append("%s, %s" % (
helpers.list_to_string(post_adr.get("region"), " "),
helpers.list_to_string(post_adr.get("country"), " ")))
elif post_adr.get("region"):
strings.append(
helpers.list_to_string(post_adr.get("region"), " "))
elif post_adr.get("country"):
strings.append(
helpers.list_to_string(post_adr.get("country"), " "))
formatted_post_adr_dict[type].append('\n'.join(strings))
return formatted_post_adr_dict
def add_post_address(
self, type, box, extended, street, code, city, region, country):
standard_types, custom_types, pref = self.parse_type_value(
helpers.string_to_list(type, ","), "%s, %s" % (street, city),
self.address_types_v4 if self.get_version() == "4.0" else
self.address_types_v3)
if len(standard_types) == 0 and len(custom_types) == 0 and pref == 0:
raise ValueError("Error: label for post address " + street +
" is missing.")
elif len(custom_types) > 1:
raise ValueError("Error: post address " + street + " got more "
"than one custom " "label: " +
helpers.list_to_string(custom_types, ", "))
else:
adr_obj = self.vcard.add('adr')
adr_obj.value = vobject.vcard.Address(
box=helpers.convert_to_vcard(
"box address field", box,
ObjectType.string_or_list_with_strings),
extended=helpers.convert_to_vcard(
"extended address field", extended,
ObjectType.string_or_list_with_strings),
street=helpers.convert_to_vcard(
"street", street, ObjectType.string_or_list_with_strings),
code=helpers.convert_to_vcard(
"post code", code, ObjectType.string_or_list_with_strings),
city=helpers.convert_to_vcard(
"city", city, ObjectType.string_or_list_with_strings),
region=helpers.convert_to_vcard(
"region", region, ObjectType.string_or_list_with_strings),
country=helpers.convert_to_vcard(
"country", country,
ObjectType.string_or_list_with_strings))
if self.get_version() == "4.0":
if pref > 0:
adr_obj.params['PREF'] = str(pref)
else:
if pref > 0:
standard_types.append("pref")
if standard_types:
adr_obj.params['TYPE'] = standard_types
if custom_types:
number_of_custom_post_address_labels = 0
for label in self.vcard.getChildren():
if label.name == "X-ABLABEL" \
and label.group.startswith("itemadr"):
number_of_custom_post_address_labels += 1
group_name = "itemadr%d" % (
number_of_custom_post_address_labels+1)
adr_obj.group = group_name
label_obj = self.vcard.add('x-ablabel')
label_obj.group = group_name
label_obj.value = custom_types[0]
def get_categories(self):
"""
:rtype: list(str) or list(list(str))
"""
category_list = []
for child in self.vcard.getChildren():
if child.name == "CATEGORIES":
value = child.value
category_list.append(
value if isinstance(value, list) else [value])
if len(category_list) == 1:
return category_list[0]
return sorted(category_list)
def add_category(self, categories):
""" categories variable must be a list """
categories_obj = self.vcard.add('categories')
categories_obj.value = helpers.convert_to_vcard(
"category", categories, ObjectType.list_with_strings)
def get_nicknames(self):
"""
:rtype: list(list(str))
"""
nicknames = []
for child in self.vcard.getChildren():
if child.name == "NICKNAME":
nicknames.append(child.value)
return sorted(nicknames)
def add_nickname(self, nickname):
nickname_obj = self.vcard.add('nickname')
nickname_obj.value = helpers.convert_to_vcard(
"nickname", nickname, ObjectType.string)
def get_notes(self):
"""
:rtype: list(list(str))
"""
notes = []
for child in self.vcard.getChildren():
if child.name == "NOTE":
notes.append(child.value)
return sorted(notes)
def add_note(self, note):
note_obj = self.vcard.add('note')
note_obj.value = helpers.convert_to_vcard(
"note", note, ObjectType.string)
def get_private_objects(self):
"""
:rtype: dict(str, list(str))
"""
private_objects = {}
for child in self.vcard.getChildren():
if child.name.lower().startswith("x-"):
try:
key_index = [
x.lower() for x in self.supported_private_objects
].index(child.name[2:].lower())
except ValueError:
pass
else:
key = self.supported_private_objects[key_index]
if private_objects.get(key) is None:
private_objects[key] = []
private_objects[key].append(child.value)
# sort private object lists
for value in private_objects.values():
value.sort()
return private_objects
def add_private_object(self, key, value):
private_obj = self.vcard.add('X-' + key.upper())
private_obj.value = helpers.convert_to_vcard(
key, value, ObjectType.string)
def get_webpages(self):
"""
:rtype: list(list(str))
"""
urls = []
for child in self.vcard.getChildren():
if child.name == "URL":
urls.append(child.value)
return sorted(urls)
def add_webpage(self, webpage):
webpage_obj = self.vcard.add('url')
webpage_obj.value = helpers.convert_to_vcard(
"webpage", webpage, ObjectType.string)
def get_birthday(self):
""":returns: contacts birthday or None if not available
:rtype: datetime.datetime or str
"""
# vcard 4.0 could contain a single text value
try:
if self.vcard.bday.params.get("VALUE")[0] == "text":
return self.vcard.bday.value
except (AttributeError, IndexError, TypeError):
pass
# else try to convert to a datetime object
try:
return helpers.string_to_date(self.vcard.bday.value)
except (AttributeError, ValueError):
pass
return None
def get_formatted_birthday(self):
date = self.get_birthday()
if date:
if isinstance(date, str):
return date
elif date.year == 1900 and date.month != 0 and date.day != 0 \
and date.hour == 0 and date.minute == 0 and date.second == 0:
return "--%.2d-%.2d" % (date.month, date.day)
elif (date.tzname() and date.tzname()[3:]) or \
(date.hour != 0 or date.minute != 0 or date.second != 0):
return date.strftime(locale.nl_langinfo(locale.D_T_FMT))
else:
return date.strftime(locale.nl_langinfo(locale.D_FMT))
return ""
def add_birthday(self, date):
if isinstance(date, str):
if self.get_version() == "4.0":
bday_obj = self.vcard.add('bday')
bday_obj.params['VALUE'] = ["text"]
bday_obj.value = date.strip()
elif date.year == 1900 and date.month != 0 and date.day != 0 \
and date.hour == 0 and date.minute == 0 and date.second == 0 \
and self.get_version() == "4.0":
bday_obj = self.vcard.add('bday')
bday_obj.value = "--%.2d%.2d" % (date.month, date.day)
elif date.tzname() and date.tzname()[3:]:
bday_obj = self.vcard.add('bday')
if self.get_version() == "4.0":
bday_obj.value = "%.4d%.2d%.2dT%.2d%.2d%.2d%s" % (
date.year, date.month, date.day, date.hour, date.minute,
date.second, date.tzname()[3:])
else:
bday_obj.value = "%.4d-%.2d-%.2dT%.2d:%.2d:%.2d%s" % (
date.year, date.month, date.day, date.hour, date.minute,
date.second, date.tzname()[3:])
elif date.hour != 0 or date.minute != 0 or date.second != 0:
bday_obj = self.vcard.add('bday')
if self.get_version() == "4.0":
bday_obj.value = "%.4d%.2d%.2dT%.2d%.2d%.2dZ" % (
date.year, date.month, date.day, date.hour, date.minute,
date.second)
else:
bday_obj.value = "%.4d-%.2d-%.2dT%.2d:%.2d:%.2dZ" % (
date.year, date.month, date.day, date.hour, date.minute,
date.second)
else:
bday_obj = self.vcard.add('bday')
if self.get_version() == "4.0":
bday_obj.value = "%.4d%.2d%.2d" % (date.year, date.month,
date.day)
else:
bday_obj.value = "%.4d-%.2d-%.2d" % (date.year, date.month,
date.day)
#######################
# object helper methods
#######################
def filter_base64_encoded_attributes(self, contents):
filtered = []
append_line = True
for line in contents.split("\n"):
if not append_line and \
re.search("^\S.*$", line, re.IGNORECASE):
# skipped all the indented lines and found the next attribute
append_line = True
if append_line and ( \
re.search(
"^\S.*;encoding=base64[;:].*$", line, re.IGNORECASE) \
or re.search(
"^\S.*;encoding=b[;:].*$", line, re.IGNORECASE) \
or re.search(
"^\S.*:data.*[;:]base64,.*$", line, re.IGNORECASE)):
# found an attribute with base64 encoding
# for vcard versions 2.1, 3.0 or 4.0
# skip that due to a bug in the vobject library
# refers to khard issues #80 and #86
append_line = False
if append_line:
filtered.append(line)
else:
self.excluded_data.append(line)
return '\n'.join(filtered)
def filter_invalid_tags(self, contents):
contents = re.sub('(?i)' + re.escape('X-messaging/aim-All'), 'X-AIM',
contents)
contents = re.sub('(?i)' + re.escape('X-messaging/gadu-All'),
'X-GADUGADU', contents)
contents = re.sub('(?i)' + re.escape('X-messaging/groupwise-All'),
'X-GROUPWISE', contents)
contents = re.sub('(?i)' + re.escape('X-messaging/icq-All'), 'X-ICQ',
contents)
contents = re.sub('(?i)' + re.escape('X-messaging/xmpp-All'),
'X-JABBER', contents)
contents = re.sub('(?i)' + re.escape('X-messaging/msn-All'), 'X-MSN',
contents)
contents = re.sub('(?i)' + re.escape('X-messaging/yahoo-All'),
'X-YAHOO', contents)
contents = re.sub('(?i)' + re.escape('X-messaging/skype-All'),
'X-SKYPE', contents)
contents = re.sub('(?i)' + re.escape('X-messaging/irc-All'), 'X-IRC',
contents)
contents = re.sub('(?i)' + re.escape('X-messaging/sip-All'), 'X-SIP',
contents)
return contents
def process_user_input(self, input):
# parse user input string
try:
contact_data = yaml.load(input, Loader=yaml.BaseLoader)
except yaml.parser.ParserError as err:
raise ValueError(err)
except yaml.scanner.ScannerError as err:
raise ValueError(err)
else:
if contact_data is None:
raise ValueError("Error: Found no contact information")
# check for available data
# at least enter name or organisation
if not bool(contact_data.get("First name")) \
and not bool(contact_data.get("Last name")) \
and not bool(contact_data.get("Organisation")):
raise ValueError(
"Error: You must either enter a name or an organisation")
# update rev
self.delete_vcard_object("REV")
self.add_rev(datetime.datetime.now())
# name
self.delete_vcard_object("FN")
self.delete_vcard_object("N")
# although the "n" attribute is not explisitely required by the vcard
# specification,
# the vobject library throws an exception, if it doesn't exist
# so add the name regardless if it's empty or not
self.add_name(
contact_data.get("Prefix") or "",
contact_data.get("First name") or "",
contact_data.get("Additional") or "",
contact_data.get("Last name") or "",
contact_data.get("Suffix") or "")
# nickname
self.delete_vcard_object("NICKNAME")
if bool(contact_data.get("Nickname")):
if isinstance(contact_data.get("Nickname"), str):
self.add_nickname(contact_data.get("Nickname"))
elif isinstance(contact_data.get("Nickname"), list):
for nickname in contact_data.get("Nickname"):
if bool(nickname):
self.add_nickname(nickname)
else:
raise ValueError(
"Error: nickname must be a string or a list of strings")
# organisation
self.delete_vcard_object("ORG")
self.delete_vcard_object("X-ABSHOWAS")
if bool(contact_data.get("Organisation")):
if isinstance(contact_data.get("Organisation"), str):
self.add_organisation([contact_data.get("Organisation")])
elif isinstance(contact_data.get("Organisation"), list):
for organisation in contact_data.get("Organisation"):
if bool(organisation):
if isinstance(organisation, str):
self.add_organisation([organisation])
else:
self.add_organisation(organisation)
else:
raise ValueError("Error: organisation must be a string or a "
"list of strings")
# role
self.delete_vcard_object("ROLE")
if bool(contact_data.get("Role")):
if isinstance(contact_data.get("Role"), str):
self.add_role(contact_data.get("Role"))
elif isinstance(contact_data.get("Role"), list):
for role in contact_data.get("Role"):
if bool(role):
self.add_role(role)
else:
raise ValueError(
"Error: role must be a string or a list of strings")
# title
self.delete_vcard_object("TITLE")
if bool(contact_data.get("Title")):
if isinstance(contact_data.get("Title"), str):
self.add_title(contact_data.get("Title"))
elif isinstance(contact_data.get("Title"), list):
for title in contact_data.get("Title"):
if bool(title):
self.add_title(title)
else:
raise ValueError(
"Error: title must be a string or a list of strings")
# phone
self.delete_vcard_object("TEL")
if bool(contact_data.get("Phone")):
if isinstance(contact_data.get("Phone"), dict):
for type, number_list in contact_data.get("Phone").items():
if isinstance(number_list, list) \
or isinstance(number_list, str):
if isinstance(number_list, str):
number_list = [number_list]
for number in number_list:
if bool(number):
self.add_phone_number(type, number)
else:
raise ValueError(
"Error: got no number or list of numbers for the "
"phone number type " + type)
else:
raise ValueError(
"Error: missing type value for phone number field")
# email
self.delete_vcard_object("EMAIL")
if bool(contact_data.get("Email")):
if isinstance(contact_data.get("Email"), dict):
for type, email_list in contact_data.get("Email").items():
if isinstance(email_list, list) \
or isinstance(email_list, str):
if isinstance(email_list, str):
email_list = [email_list]
for email in email_list: