Improvements to the documentation and style fixes
[diaspy.git] / diaspy / client.py
CommitLineData
a993a4b6
MK
1import requests
2import re
3import json
4
5
6class Client:
7 """This is the client class to connect to diaspora.
8
9 .. note::
10
11 Before calling any other function
12 you have to call :func:`diaspy.Client.login`.
13
14 """
15
16 def __init__(self, pod):
17 self._token_regex = re.compile(r'content="(.*?)"\s+name="csrf-token')
18 self.pod = pod
19 self.session = requests.Session()
20
21 def get_token(self):
ae221396
MK
22 """This function gets a token needed for authentication in most cases
23
24 :returns: string -- token used to authenticate
25
26 """
27
a993a4b6
MK
28 r = self.session.get(self.pod + "/stream")
29 token = self._token_regex.search(r.text).group(1)
30 return token
31
a993a4b6
MK
32 def login(self, username, password):
33 """This function is used to connect to the pod and log in.
34
35 :param username: The username used to log in.
36 :type username: str
37 :param password: The password used to log in.
38 :type password: str
39
40 """
41 self._username = username
42 self._password = password
43 r = self.session.get(self.pod + "/users/sign_in")
44 token = self._token_regex.search(r.text).group(1)
45
46 data = {'user[username]': self._username,
47 'user[password]': self._password,
48 'authenticity_token': token,
49 'commit': ''}
50
51 r = self.session.post(self.pod + "/users/sign_in", data=data)
52
53 def post(self, text, aspect_id='public'):
54 """This function sends a post to an aspect
55
56 :param text: Text to post.
57 :type text: str
58 :param aspect_id: Aspect id to send post to.
59 :type aspect_id: str
60
61 """
62 data = {'aspect_ids': aspect_id,
63 'status_message[text]': text,
64 'authenticity_token': self.get_token()}
65 r = self.session.post(self.pod + "/status_messages", data=data)
66
67 def get_user_info(self):
68 """This function returns the current user's attributes.
69
70 :returns: dict -- json formatted user info.
71
72 """
73 r = self.session.get(self.pod + "/stream")
74 regex = re.compile(r'window.current_user_attributes = ({.*})')
75 userdata = json.loads(regex.search(r.text).group(1))
76 return userdata