-
Notifications
You must be signed in to change notification settings - Fork 22
/
carddav-util.py
executable file
·213 lines (183 loc) · 7.48 KB
/
carddav-util.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
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Copyright (c) 2013, 2022 by Lukasz Janyst <[email protected]>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#-------------------------------------------------------------------------------
import sys
import uuid
import getopt
import getpass
import carddav
import vobject
#-------------------------------------------------------------------------------
# Fix FN
#-------------------------------------------------------------------------------
def fixFN( url, filename, user, passwd, auth, verify ):
print( '[i] Editing at', url, '...' )
print( '[i] Listing the addressbook...' )
dav = carddav.PyCardDAV( url, user=user, passwd=passwd, auth=auth,
write_support=True, verify=verify )
abook = dav.get_abook()
nCards = len( abook.keys() )
print( '[i] Found', nCards, 'cards.' )
curr = 1
for href, etag in abook.items():
print( "\r[i] Processing", curr, "of", nCards, )
sys.stdout.flush()
curr += 1
card = dav.get_vcard( href )
card = card.split( '\r\n' )
cardFixed = []
for l in card:
if not l.startswith( 'FN:' ):
cardFixed.append( l )
cardFixed = '\r\n'.join( cardFixed )
c = vobject.readOne( cardFixed )
n = [c.n.value.prefix, c.n.value.given, c.n.value.additional,
c.n.value.family, c.n.value.suffix]
name = ''
for part in n:
if part:
name += part + ' '
name = name.strip()
if not hasattr( c, 'fn' ):
c.add('fn')
c.fn.value = name
try:
dav.update_vcard( c.serialize(), href, etag )
except Exception as e:
print( '' )
raise
print( '' )
print( '[i] All updated' )
#-------------------------------------------------------------------------------
# Download
#-------------------------------------------------------------------------------
def download( url, filename, user, passwd, auth, verify ):
print( '[i] Downloading from', url, 'to', filename, '...' )
print( '[i] Downloading the addressbook...' )
dav = carddav.PyCardDAV( url, user=user, passwd=passwd, auth=auth,
verify=verify )
abook = dav.get_abook()
nCards = len( abook.keys() )
print( '[i] Found', nCards, 'cards.' )
f = open( filename, 'w' )
curr = 1
for href, etag in abook.items():
print( '\r[i] Fetching', curr, 'of', nCards, )
sys.stdout.flush()
curr += 1
card = dav.get_vcard( href )
f.write( card.decode('utf-8') + '\n' )
print( '' )
f.close()
print( '[i] All saved to:', filename )
#-------------------------------------------------------------------------------
# Upload
#-------------------------------------------------------------------------------
def upload( url, filename, user, passwd, auth, verify ):
if not url.endswith( '/' ):
url += '/'
print( '[i] Uploading from', filename, 'to', url, '...' )
print( '[i] Processing cards in', filename, '...' )
f = open( filename, 'r' )
cards = []
for card in vobject.readComponents( f, validate=True ):
cards.append( card )
nCards = len(cards)
print( '[i] Successfuly read and validated', nCards, 'entries' )
print( '[i] Connecting to', url, '...' )
dav = carddav.PyCardDAV( url, user=user, passwd=passwd, auth=auth,
write_support=True, verify=verify )
curr = 1
for card in cards:
print( '\r[i] Uploading', curr, 'of', nCards, )
sys.stdout.flush()
curr += 1
if hasattr( card, 'prodid' ):
del card.prodid
if not hasattr( card, 'uid' ):
card.add('uid')
card.uid.value = str( uuid.uuid4() )
try:
dav.upload_new_card( card.serialize() )
except Exception as e:
print( '' )
raise
print( '' )
f.close()
print( '[i] All done' )
#-------------------------------------------------------------------------------
# Print help
#-------------------------------------------------------------------------------
def printHelp():
print( 'carddav-util.py [options]' )
print( ' --url=http://your.addressbook.com CardDAV addressbook ' )
print( ' --file=local.vcf local vCard file ' )
print( ' --user=username username ' )
print( ' --passwd=password password, if absent will ' )
print( ' prompt for it in the console ' )
print( ' --download copy server -> file ' )
print( ' --upload copy file -> server ' )
print( ' --fixfn regenerate the FN tag ' )
print( ' --digest use digest authentication ' )
print( ' --no-cert-verify skip certificate verification ' )
print( ' --help this help message ' )
#-------------------------------------------------------------------------------
# Run the show
#-------------------------------------------------------------------------------
def main():
try:
params = ['url=', 'file=', 'download', 'upload', 'help',
'user=', 'passwd=', 'digest', 'no-cert-verify', 'fixfn']
optlist, args = getopt.getopt( sys.argv[1:], '', params )
except getopt.GetoptError as e:
print( '[!]', e )
return 1
opts = dict(optlist)
if '--help' in opts or not opts:
printHelp()
return 0
if '--upload' in opts and '--download' in opts and '--fixfn' in opts:
print( '[!] You can only choose one action at a time' )
return 2
if '--url' not in opts or '--file' not in opts:
print( '[!] You must specify both the filename and the url' )
return 3
url = opts['--url']
filename = opts['--file']
user = None
passwd = None
auth = 'basic'
verify = True
if '--digest' in opts:
auth = 'digest'
if '--no-cert-verify' in opts:
verify = False
if '--user' in opts:
user = opts['--user']
if '--passwd' in opts:
passwd = opts['--passwd']
else:
passwd = getpass.getpass( user+'\'s password (won\'t be echoed): ')
commandMap = {'--upload': upload, '--download': download, '--fixfn': fixFN}
for command in commandMap:
if command in opts:
i = 0
try:
i = commandMap[command]( url, filename, user, passwd, auth, verify )
except Exception as e:
print( '[!]', e )
if __name__ == '__main__':
sys.exit(main())