75 lines
2.5 KiB
Python
Executable File
75 lines
2.5 KiB
Python
Executable File
#!/usr/bin/python
|
|
# -*- coding: utf-8 -*-
|
|
|
|
import argparse
|
|
import vobject
|
|
import os
|
|
import quopri
|
|
import re
|
|
|
|
def input():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('vcard',
|
|
type=argparse.FileType('r'),
|
|
help='Vcard file to parse')
|
|
args = parser.parse_args()
|
|
return args
|
|
|
|
# Remove FN
|
|
# Add N;CHARSET=ISO-8859-1;ENCODING=QUOTED-PRINTABLE:<familyName>;<Name>
|
|
def legacy_encoding_filter(given_name, family_name, serialized_vcard):
|
|
# Ugly hack to get charset latin-1 + quoted printable syntax
|
|
gname = quopri.encodestring(unicode(quopri.decodestring(given_name), "utf-8").encode('latin-1'))
|
|
fname = quopri.encodestring(unicode(quopri.decodestring(family_name), "utf-8").encode('latin-1'))
|
|
|
|
print "given : %s ; Family : %s" % (gname, fname)
|
|
|
|
ret = re.sub(r'^FN:.*\n',
|
|
r'',
|
|
serialized_vcard,
|
|
flags=re.MULTILINE)
|
|
# Do not forget \r !
|
|
ret = re.sub(r'^N:(.*)',
|
|
r'N;CHARSET=ISO-8859-1;ENCODING=QUOTED-PRINTABLE:%s;%s\r'
|
|
% (fname, gname),
|
|
ret,
|
|
flags=re.MULTILINE)
|
|
return ret
|
|
|
|
if __name__ == "__main__":
|
|
args = input()
|
|
print("*** Parsing Vcard : ***")
|
|
|
|
vlist = vobject.readComponents(args.vcard)
|
|
|
|
print("Creating output directory :")
|
|
try:
|
|
os.mkdir("out/")
|
|
except OSError:
|
|
print "Output directory already exist"
|
|
|
|
for i, vcard in enumerate(vlist):
|
|
try:
|
|
print "*** VCARD number %d ***" % i
|
|
try:
|
|
if vcard.tel:
|
|
print "Creating single vcard file"
|
|
filename = quopri.decodestring(str(vcard.n.value).strip().replace(" ", "_"))
|
|
print "filename : '%s'" % filename
|
|
# Save to file
|
|
with open("out/%s.vcf" % filename, 'w') as f:
|
|
f.write(legacy_encoding_filter(vcard.n.value.given,
|
|
vcard.n.value.family,
|
|
vcard.serialize()))
|
|
except (AttributeError) as e:
|
|
# print "No vcard.tel for vcard number %d" % i
|
|
continue
|
|
except:
|
|
print "Uncatched exception"
|
|
except (vobject.base.ValidateError) as e:
|
|
# print "VCARD not valid : %s" % e
|
|
continue
|
|
except:
|
|
print "Uncatched exception"
|
|
args.vcard.close()
|