palmagent / hipg.py

"""hipg.py -- upload hiptop data to gdata services

cribbed from...
http://code.google.com/apis/contacts/docs/1.0/developers_guide_python.html
"""

import getpass

import atom
import gdata.contacts
import gdata.contacts.service

from hipwsgi import AccountData
import dngr_contact

def main(argv):
    if '--convert' in argv:
        sk = AccountData(argv[2])
        cat = argv[3]

        convert_contacts(sk.records('contact'), cat)

    if '--feed' in argv:
        email = argv[2]
        pw=getpass.getpass()

        gcontacts = svc(email, pw)
        DumpFeed(sys.stdout, gcontacts)

    else:
        email = argv[1]
        sk = AccountData(argv[2])
        pw=getpass.getpass()

        gcontacts = svc(email, pw)
        batch_contacts(gcontacts, sk.records('contact'))


def svc(email, pw):
    gd_client = gdata.contacts.service.ContactsService()

    gd_client.email = email
    gd_client.password = pw
    gd_client.source = 'connolly-palmagent-1'
    gd_client.ProgrammaticLogin()
    return gd_client

def DumpFeed(outfp, gcontacts):
    def raw(body):
        return body

    query = gdata.contacts.service.ContactsQuery()
    query.start_index = 1
    query.max_results = 25 # kinda arbitrary?

    while 1:
        #@@ converter=raw ?
        feed = gcontacts.GetContactsFeed(query.ToUri())
        query.start_index += query.max_results
        outfp.write(str(feed))

def PrintFeed(feed):
  for i, entry in enumerate(feed.entry):
      print entry.ToString()

def convert_contacts(contacts, cat=None):
    for k in contacts.keys():
        cand = contacts[k]
        if not cat or cat == cand['category']:
            g = gcontact(cand)
            print g.ToString() #@@

def batch_contacts(gcontacts, contacts, cat=None):
    # can't figure out docs for batching
    for k in contacts.keys():
        cand = contacts[k]
        if not cat or cat == cand['category']:
            g = gcontact(cand)
            try:
                gcontacts.CreateContact(g)
            except gdata.service.RequestError, e:
                if e.args[0]['status'] == 409: # already exists
                    pass
                else:
                    print "problem creating:", cand, e.args
            else:
                print "created contact:", str(cand)[:40]

Labels = {
    gdata.contacts.REL_HOME: ('Personal', 'Home'),
    gdata.contacts.REL_WORK: ('Office', 'Work'),
    gdata.contacts.PHONE_FAX: ('Fax',),
    gdata.contacts.PHONE_MOBILE: ('Mobile',),
    gdata.contacts.IM_AIM: ('AIM',),
    gdata.contacts.IM_MSN: ('MSN',),
    gdata.contacts.IM_JABBER: ('Jabber',),
    }

dummy=[
    u'Unlabeled',
    u'Toll Free',
    u'Wrong',
    u'Yahoo!'
    u'w3t-dir',
    u'Itin',
    ]


def find_rel(label):
    for k, v in Labels.iteritems():
        if label in v: return k
    return None # defaults to gdata.contacts.REL_OTHER

def gcontact(d):
    # based on
    # http://code.google.com/apis/contacts/docs/1.0/developers_guide_python.html#Creating
    vcard = dngr_contact.stdContact(d)


    g = gdata.contacts.ContactEntry(title=atom.Title(text=vcard['fn']))
    g.extended_property.append(gdata.ExtendedProperty(
            name='hiptop_source',
            value="%s %s %s " % (vcard['rev'], d['category'], d['id'])))

    if 'notes' in d and d['notes']:
        g.content = atom.Content(text=d['notes'])

    if 'company' in d:
        org = gdata.contacts.Organization(org_name =
                                          gdata.contacts.OrgName(d['company']))
        if 'job_title' in d:
            org.title = gdata.contacts.OrgTitle(d['job_title'])

    # skipping icon.

    for item in d['email_addresses']:
        # Exactly one of non-empty rel, label is required for email address.

        # Illegal rel value: http://schemas.google.com/g/2005#mobile
        lbl = item['label']
        if lbl == 'Mobile': r = None
        else: r= find_rel(lbl)

        g.email.append(gdata.contacts.Email(address=item['address'],
                                            rel=r))

    for item in d['phone_numbers']:
        g.phone_number.append(gdata.contacts.PhoneNumber(
                text=item['number'], # throw away label?
                rel=find_rel(item['label'])))

    for item in d['im_addresses']:
        g.im.append(gdata.contacts.IM(
                address=item['address'],
                protocol=find_rel(item['label'])))

    for item in d['addresses']:
        g.postal_address.append(gdata.contacts.PostalAddress(
                text=postal(item),
                rel=find_rel(item['label'])))


    if 'urls' in d:
        g.extended_property.append(gdata.ExtendedProperty(
                name='urls', value=str(d['urls'])))
    if 'bday' in vcard:
        g.extended_property.append(gdata.ExtendedProperty(
                name='bday', value=vcard['bday']))
    if 'nickname' in vcard:
        g.extended_property.append(gdata.ExtendedProperty(
                name='nickname', value=vcard['nickname']))

    return g

def postal(item):
    return "%s\n%s, %s %s %s" % (
        item['street'],
        item['city'], item['state'], item['zip'], item['country'])

if __name__ == '__main__':
    import sys
    main(sys.argv)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.