style
[redakcja.git] / lib / wlapi / __init__.py
1 # -*- coding: utf-8 -*-
2 #
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.
5 #
6 """
7    Abstraction over API for wolnelektury.pl
8 """
9 import urllib2
10 import functools
11 import json
12 import logging
13 logger = logging.getLogger("fnp.lib.wlapi")
14
15
16 class APICallException(Exception):
17
18     def __init__(self, cause=None):
19         super(Exception, self).__init__()
20         self.cause = cause
21
22     def __unicode__(self):
23         return u"%s, cause: %s" % (type(self).__name__, repr(self.cause))
24
25     def __str__(self):
26         return self.__unicode__().encode('utf-8')
27
28
29 def api_call(path, format="json"):
30     def wrapper(func):
31
32         @functools.wraps(func)
33         def wrapped(self, *args, **kwargs):
34             generator = func(self, *args, **kwargs)
35
36             data = generator.next()
37
38             # prepare request
39             rq = urllib2.Request(self.base_url + path + ".json")
40
41             # will send POST when there is data, GET otherwise
42             if data is not None:
43                 rq.add_data(json.dumps(data))
44                 rq.add_header("Content-Type", "application/json")
45
46             try:
47                 anwser = json.load(self.opener.open(rq))
48                 try:
49                     return generator.send(anwser)
50                 except StopIteration:
51                     # by default, just return the anwser as a shorthand
52                     return anwser
53             except urllib2.HTTPError, error:
54                 return self._http_error(error)
55             except Exception, error:
56                 return self._error(error)
57         return wrapped
58
59     return wrapper
60
61
62 class WLAPI(object):
63
64     def __init__(self, **config_dict):
65         self.base_url = config_dict['URL']
66         self.auth_realm = config_dict['AUTH_REALM']
67         self.auth_user = config_dict['AUTH_USER']
68
69         digest_handler = urllib2.HTTPDigestAuthHandler()
70         digest_handler.add_password(
71                     realm=self.auth_realm, uri=self.base_url,
72                     user=self.auth_user, passwd=config_dict['AUTH_PASSWD'])
73
74         basic_handler = urllib2.HTTPBasicAuthHandler()
75         basic_handler.add_password(
76                     realm=self.auth_realm, uri=self.base_url,
77                     user=self.auth_user, passwd=config_dict['AUTH_PASSWD'])
78
79         self.opener = urllib2.build_opener(digest_handler, basic_handler)
80
81     def _http_error(self, error):
82         message = error.read()
83         logger.debug("HTTP ERROR: %s", message)
84         return self._error(message)
85
86     def _error(self, error):
87         raise APICallException(error)
88
89     @api_call("books")
90     def list_books(self):
91         yield
92
93     @api_call("books")
94     def publish_book(self, document):
95         yield {"text": document.text, "compressed": False}