xmpp (jabber) photo module

I made a Google Talk and Google Maps mashup a while back. I could not find a xmpp module that gave access to the person’s picture, so I had to write one that extracts it from the vcard.

import base64, hashlib
from os import path
import xmpp

def photo_update_handler(session, stanza):
    JID = stanza['from'].getStripped()
    vupdate = stanza.getTag('x',namespace='vcard-temp:x:update')
    if not vupdate:return
    photo = vupdate.getTag('photo')
    if not photo:return
    photo = photo.getPayload()
    if not photo:return
    photo = photo[0]
    session._owner.Roster._data[JID]['photo'] = photo
    #download the photo only if we don't have a photo with that hash
    if not get_photo(photo) and 'summona' not in JID:
        #a quick fix to an unkonwn bug with andy's picture
        request_vcard(session, JID)

def register_handler(session):
    session.RegisterHandler(
        'presence',
        photo_update_handler,
        '',
        'jabber:client',
        )

def recieve_vcard(session, stanza):
    vcard = stanza.getTag('vCard')
    #name = vcard.getTags('FN')[0].getPayload()[0]
    photo = vcard.getTag('PHOTO')
    if not photo: return
    photo_type = photo.getTag('TYPE').getPayload()[0]
    photo_bin = photo.getTag('BINVAL').getPayload()[0]
    photo_bin = base64.b64decode(photo_bin)
    if photo_type == 'image/png':
        ext = '.png'
    elif photo_type == 'image/jpeg':
        ext = '.jpg'
    elif photo_type == 'image/gif':
        ext = '.gif'
    elif photo_type == 'image/bmp':
        ext = '.bmp'
    else:
        print "Unknown file type: %s" % photo_type
        ext = ''
    sha1sh = hashlib.sha1()
    sha1sh.update(photo_bin)
    sha1sh = sha1sh.hexdigest()
    f = file(sha1sh + ext,'wb')
    f.write(photo_bin)
    f.close()
    #JID = stanza['from'].getStripped()

def request_vcard(session, JID):
    n = xmpp.Node('vCard', attrs={'xmlns':xmpp.NS_VCARD})
    i = xmpp.Protocol('iq', JID, 'get', payload=[n])
    return session.SendAndCallForResponse(i, recieve_vcard)

def get_photo(sha1sh):
    ext = ['.jpg','.png','.gif','.bmp']
    for x in ext:
        if path.exists(sha1sh + x):
            return sha1sh + x
Advertisements