Improve exception handling
[diaspy.git] / diaspy / client.py
1 import requests
2 import re
3 import json
4
5
6 class Client:
7 """This is the client class to connect to diaspora.
8
9 """
10
11 def __init__(self, pod, username, password):
12 """
13 :param pod: The complete url of the diaspora pod to use.
14 :type pod: str
15 :param username: The username used to log in.
16 :type username: str
17 :param password: The password used to log in.
18 :type password: str
19
20 """
21 self._token_regex = re.compile(r'content="(.*?)"\s+name="csrf-token')
22 self.pod = pod
23 self.session = requests.Session()
24 self._login(username, password)
25
26 def get_token(self):
27 """This function gets a token needed for authentication in most cases
28
29 :returns: string -- token used to authenticate
30
31 """
32
33 r = self.session.get(self.pod + '/stream')
34 token = self._token_regex.search(r.text).group(1)
35 return token
36
37 def _login(self, username, password):
38 """This function is used to connect to the pod and log in.
39 .. note::
40 This function shouldn't be called manually.
41 """
42 self._username = username
43 self._password = password
44 r = self.session.get(self.pod + '/users/sign_in')
45 token = self._token_regex.search(r.text).group(1)
46
47 data = {'user[username]': self._username,
48 'user[password]': self._password,
49 'authenticity_token': token,
50 'commit': ''}
51
52 r = self.session.post(self.pod +
53 '/users/sign_in',
54 data=data,
55 headers={'accept': 'application/json'})
56
57 if r.status_code != 201:
58 raise Exception(str(r.status_code) + ': Login failed.')
59
60 def post(self, text, aspect_id='public'):
61 """This function sends a post to an aspect
62
63 :param text: Text to post.
64 :type text: str
65 :param aspect_id: Aspect id to send post to.
66 :type aspect_id: str
67
68 """
69 data = {'aspect_ids': aspect_id,
70 'status_message[text]': text,
71 'authenticity_token': self.get_token()}
72 r = self.session.post(self.pod +
73 "/status_messages",
74 data=data,
75 headers={'accept': 'application/json'})
76 if r.status_code != 201:
77 raise Exception(str(r.status_code) + ': Post could not be posted.')
78
79 return r.json()
80
81 def get_user_info(self):
82 """This function returns the current user's attributes.
83
84 :returns: dict -- json formatted user info.
85
86 """
87 r = self.session.get(self.pod + '/stream')
88 regex = re.compile(r'window.current_user_attributes = ({.*})')
89 userdata = json.loads(regex.search(r.text).group(1))
90 return userdata