1 # -*- coding: utf-8 -*-
 
   3 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
 
   4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 
   7    Abstraction over API for wolnelektury.pl
 
  11 import django.utils.simplejson as json
 
  13 logger = logging.getLogger("fnp.lib.wlapi")
 
  16 class APICallException(Exception):
 
  18     def __init__(self, cause=None):
 
  19         super(Exception, self).__init__()
 
  22     def __unicode__(self):
 
  23         return u"%s, cause: %s" % (type(self).__name__, repr(self.cause))
 
  26         return self.__unicode__().encode('utf-8')
 
  29 def api_call(path, format="json"):
 
  32         @functools.wraps(func)
 
  33         def wrapped(self, *args, **kwargs):
 
  34             generator = func(self, *args, **kwargs)
 
  36             data = generator.next()
 
  39             rq = urllib2.Request(self.base_url + path + ".json")
 
  41             # will send POST when there is data, GET otherwise
 
  43                 rq.add_data(json.dumps(data))
 
  44                 rq.add_header("Content-Type", "application/json")
 
  47                 anwser = json.load(self.opener.open(rq))
 
  48                 return generator.send(anwser)
 
  50                 # by default, just return the anwser as a shorthand
 
  52             except urllib2.HTTPError, error:
 
  53                 return self._http_error(error)
 
  54             except Exception, error:
 
  55                 return self._error(error)
 
  63     def __init__(self, **config_dict):
 
  64         self.base_url = config_dict['URL']
 
  65         self.auth_realm = config_dict['AUTH_REALM']
 
  66         self.auth_user = config_dict['AUTH_USER']
 
  68         digest_handler = urllib2.HTTPDigestAuthHandler()
 
  69         digest_handler.add_password(
 
  70                     realm=self.auth_realm, uri=self.base_url,
 
  71                     user=self.auth_user, passwd=config_dict['AUTH_PASSWD'])
 
  73         basic_handler = urllib2.HTTPBasicAuthHandler()
 
  74         basic_handler.add_password(
 
  75                     realm=self.auth_realm, uri=self.base_url,
 
  76                     user=self.auth_user, passwd=config_dict['AUTH_PASSWD'])
 
  78         self.opener = urllib2.build_opener(digest_handler, basic_handler)
 
  80     def _http_error(self, error):
 
  81         message = error.read()
 
  82         logger.debug("HTTP ERROR: %s", message)
 
  83         return self._error(message)
 
  85     def _error(self, error):
 
  86         raise APICallException(error)
 
  93     def publish_book(self, document):
 
  94         yield {"text": document.text, "compressed": False}