view plugins/ @ 44:bfa7086d26d6

plugin XEP-0054: fixed forgotten copy/paste change
author Goffi <>
date Mon, 21 Dec 2009 15:36:28 +1100
parents 8a438a6ff587
children 4392f1fdb064
line wrap: on
line source

# -*- coding: utf-8 -*-

SAT plugin for managing xep-0054
Copyright (C) 2009  Jérôme Poisson (

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <>.

from logging import debug, info, error
from twisted.words.xish import domish
from twisted.internet import protocol, defer, threads, reactor
from twisted.words.protocols.jabber import client, jid, xmlstream
from twisted.words.protocols.jabber import error as jab_error
from twisted.words.protocols.jabber.xmlstream import IQ
import os.path
import pdb

from zope.interface import implements

from wokkel import disco, iwokkel

from base64 import b64decode
from hashlib import sha1
from time import sleep

AVATAR_PATH = "/avatars"

IQ_GET = '/iq[@type="get"]'
NS_VCARD = 'vcard-temp'
VCARD_REQUEST = IQ_GET + '/vCard[@xmlns="' + NS_VCARD + '"]'  #TODO: manage requests

"name": "XEP 0054 Plugin",
"import_name": "XEP_0054",
"type": "XEP",
"dependencies": [],
"main": "XEP_0054",
"description": """Implementation of vcard-temp"""

class XEP_0054():

    def __init__(self, host):
        info("Plugin XEP_0054 initialization") = host
        self.avatar_path = os.path.expanduser('local_dir') + AVATAR_PATH)
        if not os.path.exists(self.avatar_path):
        host.bridge.addMethod("getProfile", ".communication", in_sign='s', out_sign='s', method=self.getProfile)
        host.bridge.addMethod("getAvatarFile", ".communication", in_sign='s', out_sign='s', method=self.getAvatarFile)
    def getDiscoInfo(self, requestor, target, nodeIdentifier=''):
        return [disco.DiscoFeature(NS_VCARD)]

    def getDiscoItems(self, requestor, target, nodeIdentifier=''):
        return []

    def save_photo(self, photo_xml):
        """Parse a <PHOTO> elem and save the picture"""
        print "save_photo result"
        for elem in photo_xml.elements():
            if == 'TYPE':
                info('Photo of type [%s] found' % str(elem))
            if == 'BINVAL':
                debug('Decoding binary')
                decoded = b64decode(str(elem))
                hash = sha1(decoded).hexdigest()
                filename = self.avatar_path+'/'+hash
                if not os.path.exists(filename):
                    with open(filename,'wb') as file:
                    debug("file saved to %s" % hash)
                    debug("file [%s] already in cache" % hash)
                return hash

    def vCard2Dict(self, vcard):
        """Convert a VCard to a dict, and save binaries"""
        debug ("parsing vcard")
        dictionary = {}
        d = defer.Deferred()
        for elem in vcard.elements():
            if == 'FN':
                dictionary['fullname'] = unicode(elem)
            elif == 'NICKNAME':
                dictionary['nick'] = unicode(elem)
            elif == 'URL':
                dictionary['website'] = unicode(elem)
            elif == 'EMAIL':
                dictionary['email'] = unicode(elem)
            elif == 'BDAY':
                dictionary['birthday'] = unicode(elem) 
            elif == 'PHOTO':
                debug('photo deferred')
                d2 = defer.waitForDeferred(
                            threads.deferToThread(self.save_photo, elem))
                yield d2
                dictionary["avatar"] = d2.getResult()
                info ('FIXME: [%s] VCard tag is not managed yet' %

        yield dictionary

    def vcard_ok(self, answer):
        """Called after the first get IQ"""
        debug ("VCard found")

        if answer.firstChildElement().name == "vCard":
            d = self.vCard2Dict(answer.firstChildElement())
            d.addCallback(lambda data:"RESULT", answer['id'], data))
            error ("FIXME: vCard not found as first child element")
  "SUPPRESS", answer['id'], {}) #FIXME: maybe an error message would be best

    def vcard_err(self, failure):
        """Called when something is wrong with registration"""
        error ("Can't find VCard of %s" % failure.value.stanza['from'])"SUPPRESS", failure.value.stanza['id'], {}) #FIXME: maybe an error message would be best
    def getProfile(self, target):
        """Ask server for VCard
        @param target: jid from which we want the VCard
        @result: id to retrieve the profile"""
        to_jid = jid.JID(target)
        debug("Asking for %s's VCard" % to_jid.full())
        reg_request["to"] = to_jid.full()
        query=reg_request.addElement('vCard', NS_VCARD)
        reg_request.send(to_jid.full()).addCallbacks(self.vcard_ok, self.vcard_err)
        return reg_request["id"] 

    def getAvatarFile(self, hash):
        """Give the full path of avatar from hash
        @param hash: SHA1 hash
        @return full_path
        filename = self.avatar_path+'/'+hash
        if not os.path.exists(filename):
            error ("Asking for an uncached avatar [%s]" %  hash)
            return ""
        return filename