Commit | Line | Data |
---|---|---|
a993a4b6 MK |
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 | .. 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): | |
22 | r = self.session.get(self.pod + "/stream") | |
23 | token = self._token_regex.search(r.text).group(1) | |
24 | return token | |
25 | ||
26 | ||
27 | def login(self, username, password): | |
28 | """This function is used to connect to the pod and log in. | |
29 | ||
30 | :param username: The username used to log in. | |
31 | :type username: str | |
32 | :param password: The password used to log in. | |
33 | :type password: str | |
34 | ||
35 | """ | |
36 | self._username = username | |
37 | self._password = password | |
38 | r = self.session.get(self.pod + "/users/sign_in") | |
39 | token = self._token_regex.search(r.text).group(1) | |
40 | ||
41 | data = {'user[username]': self._username, | |
42 | 'user[password]': self._password, | |
43 | 'authenticity_token': token, | |
44 | 'commit': ''} | |
45 | ||
46 | r = self.session.post(self.pod + "/users/sign_in", data=data) | |
47 | ||
48 | def post(self, text, aspect_id='public'): | |
49 | """This function sends a post to an aspect | |
50 | ||
51 | :param text: Text to post. | |
52 | :type text: str | |
53 | :param aspect_id: Aspect id to send post to. | |
54 | :type aspect_id: str | |
55 | ||
56 | """ | |
57 | data = {'aspect_ids': aspect_id, | |
58 | 'status_message[text]': text, | |
59 | 'authenticity_token': self.get_token()} | |
60 | r = self.session.post(self.pod + "/status_messages", data=data) | |
61 | ||
62 | def get_user_info(self): | |
63 | """This function returns the current user's attributes. | |
64 | ||
65 | :returns: dict -- json formatted user info. | |
66 | ||
67 | """ | |
68 | r = self.session.get(self.pod + "/stream") | |
69 | regex = re.compile(r'window.current_user_attributes = ({.*})') | |
70 | userdata = json.loads(regex.search(r.text).group(1)) | |
71 | return userdata |