#!/usr/bin/python """Read a vcard file (RFC 2426) and generate Archos PMA430 Addressbook XML""" import optparse import sys import time # from pyxmpp.jabber import vcard from pycocumalib import vcard try: import cElementTreexx as etree except ImportError: import elementtree.ElementTree as etree # old pyxmpp.jabber version def split_vcards(inputfile): """Split an input file into vcards. File should be open(U)'ed.""" card = [] for line in inputfile: card.append(line.strip()) if not line.strip(): yield "\r\n".join(card) card = [] assert not card, "excess content in vcard file" # old pyxmpp.jabber version def parse_vcard(vcardtxt): card = vcard.VCard(vcardtxt) return card # old pyxmpp.jabber version def print_name(card): print card.fn # old pyxmpp.jabber version def test_vcard(card): for card in split_vcards(open(opts.vcf,"rU")): print repr(card) try: print_name(parse_vcard(card)) except AttributeError: pass # def emit_contact(card, uid=None): attrs = {} # # filter... for k in attrs.keys(): if not attrs[k]: del attrs[k] return attrs def add_contact(xmltree, attrs): """Add a with the given attributes""" contact = etree.Element("Contact", attrib=attrs) xmltree.find("Contacts").insert(1, contact) # yes, the doctype is Addressbook and the tag is AddressBook. # we'll hope the parser is "real XML" enough to not care... addressbook_xml_template = ''' ''' if __name__ == "__main__": parser = optparse.OptionParser(usage=__doc__) parser.add_option("--vcf") parser.add_option("--xml") parser.add_option("--test", action="store_true") opts, args = parser.parse_args() if args: parser.print_help() sys.exit("no args") if not opts.vcf: parser.print_help() sys.exit("--vcf input VCard File") if not opts.xml and not opts.test: parser.print_help() sys.exit("--xml output Addressbook XML file") if opts.test: cards = vcard.vCardList() cards.LoadFromFile(opts.vcf) for card in cards.sortedlist(): emit_contact(cards[card]) sys.exit() etree.fromstring cards = vcard.vCardList() cards.LoadFromFile(opts.vcf) xmlout = etree.fromstring(addressbook_xml_template) for card in cards.sortedlist(): add_contact(xmlout, emit_contact(cards[card])) print etree.tostring(xmlout) print >> file(opts.xml, "w"), etree.tostring(xmlout, encoding="UTF-8") # "version", "n", "fn", "nickname", "bday", "tel", "adr", "label", "email", # "mailer", "org", "title", "role", "note", "categories", "sort_string", # "url", "key", "rev", "uid", "tz", "geo", "photo", "logo"