`Connection()` object works, `diaply/client.py` partialy ported
[diaspy.git] / diaspy / connection.py
1 #!/usr/bin/env python
2
3 import re
4 import requests
5
6
7 class Connection():
8 """Object representing connection with the server.
9 It is pushed around internally and is considered private.
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 self.pod = pod
21 self.session = requests.Session()
22 self._token_regex = re.compile(r'content="(.*?)"\s+name="csrf-token')
23 self._setlogin(username, password)
24
25 def get(self, string):
26 """This method gets data from session.
27 Performs additional checks if needed.
28
29 Example:
30 To obtain 'foo' from pod one should call `_sessionget('foo')`.
31
32 :param string: URL to get without the pod's URL and slash eg. 'stream'.
33 :type string: str
34 """
35 return self.session.get('{0}/{1}'.format(self.pod, string))
36
37 def post(self, string, data, headers={}, params={}):
38 """This method posts data to session.
39 Performs additional checks if needed.
40
41 Example:
42 To post to 'foo' one should call `_sessionpost('foo', data={})`.
43
44 :param string: URL to post without the pod's URL and slash eg. 'status_messages'.
45 :type string: str
46 :param data: Data to post.
47 :param headers: Headers (optional).
48 :type headers: dict
49 :param params: Parameters (optional).
50 :type params: dict
51 """
52 string = '{0}/{1}'.format(self.pod, string)
53 if headers and params:
54 request = self.session.post(string, data=data, headers=headers, params=params)
55 elif headers and not params:
56 request = self.session.post(string, data=data, headers=headers)
57 elif not headers and params:
58 request = self.session.post(string, data=data, params=params)
59 else:
60 request = self.session.post(string, data=data)
61 return request
62
63 def delete(self, string, data, headers={}):
64 """This method lets you send delete request to session.
65 Performs additional checks if needed.
66
67 :param string: URL to use.
68 :type string: str
69 :param data: Data to use.
70 :param headers: Headers to use (optional).
71 :type headers: dict
72 """
73 string = '{0}/{1}'.format(self.pod, string)
74 if headers:
75 request = self.session.delete(string, data=data, headers=headers)
76 else:
77 request = self.session.delete(string, data=data)
78 return request
79
80 def _setlogin(self, username, password):
81 """This function is used to set data for login.
82 .. note::
83 It should be called before _login() function.
84 """
85 self.username, self.password = username, password
86 self.login_data = {'user[username]': self.username,
87 'user[password]': self.password,
88 'authenticity_token': self.getToken()}
89
90 def login(self):
91 """This function is used to connect to the pod and log in.
92 """
93 r = self.post('users/sign_in',
94 data=self.login_data,
95 headers={'accept': 'application/json'})
96 if r.status_code != 201:
97 raise Exception('{0}: Login failed.'.format(r.status_code))
98
99 def getToken(self):
100 """This function gets a token needed for authentication in most cases
101
102 :returns: string -- token used to authenticate
103 """
104 r = self.get('stream')
105 token = self._token_regex.search(r.text).group(1)
106 return token