"publish" button
[redakcja.git] / apps / apiclient / __init__.py
1 # -*- coding: utf-8 -*-
2 import json
3 import urllib
4
5 import oauth2
6
7 from apiclient.models import OAuthConnection
8 from apiclient.settings import WL_CONSUMER_KEY, WL_CONSUMER_SECRET, WL_API_URL
9 from django.conf import settings
10
11
12 if WL_CONSUMER_KEY and WL_CONSUMER_SECRET:
13     wl_consumer = oauth2.Consumer(WL_CONSUMER_KEY, WL_CONSUMER_SECRET)
14 else:
15     wl_consumer = None
16
17
18 class ApiError(BaseException):
19     pass
20
21
22 class NotAuthorizedError(BaseException):
23     pass
24
25
26 def api_call(user, path, data=None):
27     conn = OAuthConnection.get(user)
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 = urllib.urlencode({"data": data})
35         resp, content = client.request(
36                 "%s%s" % (WL_API_URL, path),
37                 method="POST",
38                 body=data)
39     else:
40         resp, content = client.request("%s%s" % (WL_API_URL, path))
41     status = resp['status']
42
43     if status == '200':
44         return json.loads(content)
45     elif status.startswith('2'):
46         return
47     elif settings.DEBUG:
48         raise ApiError(content)
49     elif status == '401':
50         raise ApiError('User not authorized for publishing.')
51     else:
52         raise ApiError("WL API call error [code %s]" % status)