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.
5 from urllib.parse import urlencode
7 from apiclient.settings import WL_CONSUMER_KEY, WL_CONSUMER_SECRET, WL_API_URL, BETA_API_URL
10 if WL_CONSUMER_KEY and WL_CONSUMER_SECRET:
11 wl_consumer = oauth2.Consumer(WL_CONSUMER_KEY, WL_CONSUMER_SECRET)
16 class ApiError(BaseException):
20 class NotAuthorizedError(BaseException):
24 def api_call(user, path, data=None, beta=False, method=None, as_json=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)
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)
33 data = json.dumps(data)
36 headers["Content-Type"] = 'application/json'
38 data = urlencode({"data": data})
39 data = data.encode('utf-8')
41 resp, content = client.request(
42 "%s%s" % (api_url, path),
43 method=method or 'POST',
47 resp, content = client.request(
48 "%s%s" % (api_url, path),
49 method=method or 'GET'
51 status = resp['status']
53 if status in ('200', '201'):
54 return json.loads(content)
55 elif status.startswith('2'):
58 raise ApiError('User not authorized for publishing.')
60 raise ApiError("WL API call error %s, path: %s, body: %s" % (status, path, content))