feat: use argparse for CLI

This commit is contained in:
relikd
2023-02-21 20:11:02 +01:00
parent 768b9c09fc
commit 4e9e70f341
2 changed files with 75 additions and 53 deletions

View File

@@ -1,21 +1,43 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
'''
Extract data from AddressBook database (.abcddb) to Contacts VCards file (.vcf)
'''
import os
import sys import sys
from ABCDDB import ABCDDB from ABCDDB import ABCDDB
from pathlib import Path from pathlib import Path
from argparse import ArgumentParser
if len(sys.argv) != 2:
print(' Usage:', Path(__file__).name, 'outfile.vcf')
exit(0)
outfile = Path(sys.argv[1]) DB_FILE = str(Path.home().joinpath(
if not outfile.parent.exists(): 'Library', 'Application Support', 'AddressBook', 'AddressBook-v22.abcddb'))
print('Output directory does not exist.', file=sys.stderr)
cli = ArgumentParser(description=__doc__)
cli.add_argument('output', type=str, metavar='outfile.vcf',
help='VCard output file.')
cli.add_argument('-f', '--force', action='store_true',
help='Overwrite existing output file.')
cli.add_argument('-i', '--input', type=str, metavar='AddressBook.abcddb',
default=DB_FILE, help='Specify another abcddb input file.'
' Default: ' + DB_FILE)
args = cli.parse_args()
# check input args
if not os.path.isfile(args.input):
print('AddressBook "{}" does not exist.'.format(args.input),
file=sys.stderr)
exit(1)
elif not os.path.isdir(os.path.dirname(args.output) or os.curdir):
print('Output parent directory does not exist.', file=sys.stderr)
exit(1)
elif os.path.isfile(args.output) and not args.force:
print('Output file already exist. Use -f to force overwrite.',
file=sys.stderr)
exit(1) exit(1)
contacts = ABCDDB.load(Path.home().joinpath( # perform export
'Library/Application Support/AddressBook/AddressBook-v22.abcddb')) contacts = ABCDDB.load(args.input)
# contacts = [list(contacts)[-1]] # test on last imported contact with open(args.output, 'w') as f:
with open(outfile, 'w') as f:
for rec in contacts: for rec in contacts:
f.write(rec.makeVCard()) f.write(rec.makeVCard())
print(len(contacts), 'contacts.') print(len(contacts), 'contacts.')

View File

@@ -1,53 +1,53 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
'''
Extract all profile pictures from a Contacts VCards file (.vcf)
'''
import os import os
import sys import sys
from base64 import b64decode from base64 import b64decode
from pathlib import Path from argparse import ArgumentParser, FileType
if len(sys.argv) != 3: cli = ArgumentParser(description=__doc__)
print(' Usage:', Path(__file__).name, 'infile.vcf', 'outdir/') cli.add_argument('input', type=FileType('r'), metavar='infile.vcf',
exit(0) help='VCard input file.')
cli.add_argument('outdir', type=str, help='Output directory.')
args = cli.parse_args()
infile = Path(sys.argv[1]) # check input args
outdir = Path(sys.argv[2]) if not os.path.isdir(os.path.dirname(args.outdir) or os.curdir):
if not infile.exists(): print('Output parent directory does not exist.', file=sys.stderr)
print('Does not exist: ', infile, file=sys.stderr)
exit(1) exit(1)
elif not outdir.exists():
if not outdir.parent.exists():
print('Output directory does not exist.', file=sys.stderr)
exit(1)
else:
os.mkdir(outdir)
with open(infile, 'r') as f: os.makedirs(args.outdir, exist_ok=True)
c1 = 0
c2 = 0 # perform export
name = '' c1 = 0
img = '' c2 = 0
collect = False name = ''
for line in f.readlines(): img = ''
line = line.rstrip() collect = False
if line == 'BEGIN:VCARD': for line in args.input.readlines():
c1 += 1 line = line.rstrip()
name = '' if line == 'BEGIN:VCARD':
img = '' c1 += 1
name = ''
img = ''
collect = False
elif line.startswith('FN:'):
name = line.split(':', 1)[1]
elif line.startswith('PHOTO;'):
img = line.split(':', 1)[1]
collect = True
elif collect:
if line[0] == ' ':
img += line[1:]
else:
collect = False collect = False
elif line.startswith('FN:'): if line == 'END:VCARD' and img:
name = line.split(':', 1)[1] c2 += 1
elif line.startswith('PHOTO;'): name = name.replace('\\,', ',').replace('\\;', ';').replace(
img = line.split(':', 1)[1] '/', '-')
collect = True with open(os.path.join(args.outdir, name + '.jpg'), 'wb') as fw:
elif collect: fw.write(b64decode(img))
if line[0] == ' ':
img += line[1:]
else:
collect = False
if line == 'END:VCARD' and img:
c2 += 1
name = name.replace('\\,', ',').replace('\\;', ';').replace(
'/', '-')
with open(outdir.joinpath(name + '.jpg'), 'wb') as fw:
fw.write(b64decode(img))
print(c1, 'contacts.', c2, 'images.') print(c1, 'contacts.', c2, 'images.')