#!/usr/bin/env python
#-*- coding: UTF-8 -*-

__author__ = 'helljump'


import base64
import urllib
from urllib import unquote, splittype, splithost
import xmlrpclib
import logging


log = logging.getLogger(__name__)


class UrllibTransport(xmlrpclib.Transport):
    """
    >>> p = UrllibTransport()
    >>> p.set_proxy("192.168.1.23:8000")  # username:passwd@
    >>> server = xmlrpclib.ServerProxy("http://wp.localhost/xmlrpc.php", transport=p)
    >>> print server.wp.getOptions(1, "admin", "admin", ["blog_title"] )
    {'blog_title': {'readonly': False, 'value': 'Content Monster 3', 'desc': 'Site Title'}}
    """
    def set_proxy(self, proxy):
        if not proxy.startswith('http'):
            proxy = 'http://%s' % proxy
        log.debug('use proxy %s', proxy)
        self.proxyurl = proxy

    def request(self, host, handler, request_body, verbose=0):
        type_, r_type = splittype(self.proxyurl)  # @UnusedVariable
        phost, XXX = splithost(r_type)  # @UnusedVariable

        puser_pass = None
        if '@' in phost:
            user_pass, phost = phost.split('@', 1)
            if ':' in user_pass:
                user, password = user_pass.split(':', 1)
                puser_pass = base64.encodestring('%s:%s' % (unquote(user),
                                                unquote(password))).strip()

        urlopener = urllib.FancyURLopener({'http': 'http://%s' % phost})
        if not puser_pass:
            urlopener.addheaders = [('User-agent', self.user_agent)]
        else:
            urlopener.addheaders = [('User-agent', self.user_agent),
                                    ('Proxy-authorization', 'Basic ' + puser_pass)]

        host = unquote(host)
        f = urlopener.open("http://%s%s" % (host, handler), request_body)

        self.verbose = verbose
        return self.parse_response(f)

if __name__ == '__main__':
    import doctest
    doctest.testmod()
