/
vcard.py
executable file
·179 lines (145 loc) · 5.96 KB
/
vcard.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
"""Definitions and behavior for vCard 3.0"""
import behavior
import itertools
from vobject import VObjectError, NativeError, ValidateError, ParseError, \
VBase, Component, ContentLine, logger, defaultSerialize, \
registerBehavior, backslashEscape
from icalendar import TextBehavior
#------------------------ vCard structs ----------------------------------------
class Name(object):
def __init__(self, family = '', given = '', additional = '', prefix = '',
suffix = ''):
"""Each name attribute can be a string or a list of strings."""
self.family = family
self.given = given
self.additional = additional
self.prefix = prefix
self.suffix = suffix
@staticmethod
def toString(val):
"""Turn a string or array value into a string."""
if type(val) in (list, tuple):
return ' '.join(val)
return val
def __str__(self):
eng_order = ('prefix', 'given', 'additional', 'family', 'suffix')
return ' '.join(self.toString(getattr(self, val)) for val in eng_order)
def __repr__(self):
return "<Name: %s>" % self.__str__()
class Address(object):
def __init__(self, street = '', city = '', region = '', code = '',
country = '', box = '', extended = ''):
"""Each name attribute can be a string or a list of strings."""
self.box = box
self.extended = extended
self.street = street
self.city = city
self.region = region
self.code = code
self.country = country
@staticmethod
def toString(val, join_char='\n'):
"""Turn a string or array value into a string."""
if type(val) in (list, tuple):
return join_char.join(val)
return val
lines = ('box', 'extended', 'street')
one_line = ('city', 'region', 'code')
def __str__(self):
lines = '\n'.join(self.toString(getattr(self, val)) for val in self.lines if getattr(self, val))
one_line = tuple(self.toString(getattr(self, val), ' ') for val in self.one_line)
lines += "\n%s, %s %s" % one_line
if self.country:
lines += '\n' + self.toString(self.country)
return lines
def __repr__(self):
return "<Address: %s>" % self.__str__().replace('\n', '\\n')
#------------------------ Registered Behavior subclasses -----------------------
class VCardBehavior(behavior.Behavior):
allowGroup = True
class VCard3_0(VCardBehavior):
"""vCard 3.0 behavior."""
name = 'VCARD'
description = 'vCard 3.0, defined in rfc2426'
versionString = '3.0'
isComponent = True
sortFirst = ('version', 'prodid', 'uid')
knownChildren = {'N': (1, 1, None),#min, max, behaviorRegistry id
'FN': (1, 1, None),
'VERSION': (1, 1, None),#required, auto-generated
'PRODID': (0, 1, None),
'LABEL': (0, None, None),
'UID': (0, None, None),
'ADR': (0, None, None)
}
@classmethod
def generateImplicitParameters(cls, obj):
"""Create PRODID, VERSION, and VTIMEZONEs if needed.
VTIMEZONEs will need to exist whenever TZID parameters exist or when
datetimes with tzinfo exist.
"""
if len(getattr(obj, 'version', [])) == 0:
obj.add(ContentLine('VERSION', [], cls.versionString))
registerBehavior(VCard3_0, default=True)
class VCardTextBehavior(TextBehavior):
allowGroup = True
base64string = 'B'
class FN(VCardTextBehavior):
name = "FN"
description = 'Formatted name'
registerBehavior(FN)
class Label(VCardTextBehavior):
name = "Label"
description = 'Formatted address'
registerBehavior(FN)
def toListOrString(string):
if string.find(',') >= 0:
return string.split(',')
return string
def splitFields(string):
"""Return a list of strings or lists from a Name or Address."""
return [toListOrString(i) for i in string.split(';')]
def toList(stringOrList):
if isinstance(stringOrList, basestring):
return [stringOrList]
return stringOrList
def serializeFields(obj, order):
"""Turn an object's fields into a ';' and ',' seperated string."""
return ';'.join([','.join(toList(getattr(obj, val))) for val in order])
NAME_ORDER = ('family', 'given', 'additional', 'prefix', 'suffix')
class NameBehavior(VCardBehavior):
"""A structured name."""
hasNative = True
@staticmethod
def transformToNative(obj):
"""Turn obj.value into a Name."""
if obj.isNative: return obj
obj.isNative = True
obj.value = Name(**dict(zip(NAME_ORDER, splitFields(obj.value))))
return obj
@staticmethod
def transformFromNative(obj):
"""Replace the Name in obj.value with a string."""
obj.isNative = False
obj.value = serializeFields(obj.value, NAME_ORDER)
return obj
registerBehavior(NameBehavior, 'N')
ADDRESS_ORDER = ('box', 'extended', 'street', 'city', 'region', 'code',
'country')
class AddressBehavior(VCardBehavior):
"""A structured address."""
hasNative = True
@staticmethod
def transformToNative(obj):
"""Turn obj.value into an Address."""
if obj.isNative: return obj
obj.isNative = True
obj.value = Address(**dict(zip(ADDRESS_ORDER, splitFields(obj.value))))
return obj
@staticmethod
def transformFromNative(obj):
"""Replace the Address in obj.value with a string."""
obj.isNative = False
obj.value = serializeFields(obj.value, ADDRESS_ORDER)
return obj
registerBehavior(AddressBehavior, 'ADR')