Some housekeeping
[redakcja.git] / src / apiclient / __init__.py
1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 import json
5 from urllib.parse import urlencode
6 import oauth2
7 from apiclient.settings import WL_CONSUMER_KEY, WL_CONSUMER_SECRET, WL_API_URL, BETA_API_URL
8
9
10 if WL_CONSUMER_KEY and WL_CONSUMER_SECRET:
11     wl_consumer = oauth2.Consumer(WL_CONSUMER_KEY, WL_CONSUMER_SECRET)
12 else:
13     wl_consumer = None
14
15
16 class ApiError(BaseException):
17     pass
18
19
20 class NotAuthorizedError(BaseException):
21     pass
22
23
24 def api_call(user, path, data=None, beta=False):
25     from .models import OAuthConnection
26     api_url = BETA_API_URL if beta else WL_API_URL
27     conn = OAuthConnection.get(user=user, beta=beta)
28     if not conn.access:
29         raise NotAuthorizedError("No WL authorization for user %s." % user)
30     token = oauth2.Token(conn.token, conn.token_secret)
31     client = oauth2.Client(wl_consumer, token)
32     if data is not None:
33         data = json.dumps(data)
34         data = urlencode({"data": data})
35         resp, content = client.request(
36             "%s%s" % (api_url, path),
37             method="POST",
38             body=data)
39     else:
40         resp, content = client.request(
41             "%s%s" % (api_url, path))
42     status = resp['status']
43
44     if status == '200':
45         return json.loads(content)
46     elif status.startswith('2'):
47         return
48     elif status == '401':
49         raise ApiError('User not authorized for publishing.')
50     else:
51         raise ApiError("WL API call error %s, path: %s" % (status, path))