#!/usr/bin/env python
import xmlrpclib
import httplib
import string
import urllib
import base64
import sys

"""

This is a script to interface Jcard2 with mutt's e-mail lookup feature.  It uses the XMLRPC interface of a running jcard server.

Instructions:

Startup a jcard2 server somewhere.  Make sure there is an account listed in the MainServer.cfg file under the "rpc_accounts" section.  Now change the configuration below to match the servername / user and password.  Add the following line to your .muttrc

set query_command = "/home/......./jcard_lookup_mutt.py '%s'"

Now startup mutt and create a new message.  Type part of the email address or name for a user in your jcard database (they must have an email1 field) and press CTRL+T.  voila!

"""

# Configuration #######################################
USER = 'SET THIS'
PASS = 'SET THIS'
SERVER = 'http://localhost'
#######################################################

class AuthenticationException(Exception):
    pass
    
class BasicAuthTransport(xmlrpclib.Transport):
    def __init__(self, username=None, password=None):
        self.username=username
        self.password=password
        self.verbose=None

    def request(self, host, handler, request_body, verbose):
        # issue XML-RPC request
        h = httplib.HTTP(host)
        h.putrequest("POST", handler)

        # required by HTTP/1.1
        h.putheader("Host", host)

        # required by XML-RPC
        h.putheader("User-Agent", self.user_agent)
        h.putheader("Content-Type", "text/xml")
        h.putheader("Content-Length", str(len(request_body)))

        # basic auth
        if self.username is not None and self.password is not None:
            h.putheader("AUTHORIZATION", "Basic %s" % string.replace(
                    base64.encodestring("%s:%s" % (self.username, self.password)),
                    "\012", ""))
        h.endheaders()

        if request_body:
            h.send(request_body)

        errcode, errmsg, headers = h.getreply()

        if errcode == 401:
            raise AuthenticationException('Authorization Required')

        if errcode != 200:
            raise xmlrpclib.ProtocolError(
                host + handler,
                errcode, errmsg,
                headers
                )

        return self.parse_response(h.getfile())

class AuthServer(xmlrpclib.Server):
    def __init__(self, uri, user=None, password=None):
        transport = None
        if user:
            transport = BasicAuthTransport(user, password)
        xmlrpclib.Server.__init__(self, uri, transport)

if __name__=='__main__':
    srch = sys.argv[1].upper()
    s = AuthServer(SERVER,USER,PASS)
    recs = filter(lambda a, srch=srch: a[3], s.rpc.getSummary(srch))
    print "Search for [%s] returned %s records..." % (srch, len(recs))
    for rec in recs:
        print '%s\t%s' % (rec[3], rec[1]) 
    
    

