CHanges in `Connection()` (medium-sized) and `Stream()` (extra small)
[diaspy.git] / diaspy / connection.py
1 #!/usr/bin/env python
2
3 import re
4 import requests
5 import json
6
7
8 class LoginError(Exception):
9 pass
10
11
12 class Connection():
13 """Object representing connection with the server.
14 It is pushed around internally and is considered private.
15 """
16 def __init__(self, pod, username='', password=''):
17 """
18 :param pod: The complete url of the diaspora pod to use.
19 :type pod: str
20 :param username: The username used to log in.
21 :type username: str
22 :param password: The password used to log in.
23 :type password: str
24 """
25 self.pod = pod
26 self.session = requests.Session()
27 self._token_regex = re.compile(r'content="(.*?)"\s+name="csrf-token')
28 self._userinfo_regex = re.compile(r'window.current_user_attributes = ({.*})')
29 self.login_data = {}
30 self._setlogin(username, password)
31
32 def get(self, string):
33 """This method gets data from session.
34 Performs additional checks if needed.
35
36 Example:
37 To obtain 'foo' from pod one should call `get('foo')`.
38
39 :param string: URL to get without the pod's URL and slash eg. 'stream'.
40 :type string: str
41 """
42 return self.session.get('{0}/{1}'.format(self.pod, string))
43
44 def post(self, string, data, headers={}, params={}):
45 """This method posts data to session.
46 Performs additional checks if needed.
47
48 Example:
49 To post to 'foo' one should call `post('foo', data={})`.
50
51 :param string: URL to post without the pod's URL and slash eg. 'status_messages'.
52 :type string: str
53 :param data: Data to post.
54 :param headers: Headers (optional).
55 :type headers: dict
56 :param params: Parameters (optional).
57 :type params: dict
58 """
59 string = '{0}/{1}'.format(self.pod, string)
60 request = self.session.post(string, data, headers=headers, params=params)
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 request = self.session.delete(string, data=data, headers=headers)
75 return request
76
77 def _setlogin(self, username, password):
78 """This function is used to set data for login.
79 .. note::
80 It should be called before _login() function.
81 """
82 self.username, self.password = username, password
83 self.login_data = {'user[username]': self.username,
84 'user[password]': self.password,
85 'authenticity_token': self.get_token()}
86
87 def _login(self):
88 """Handles actual login request.
89 Raises LoginError if login failed.
90 """
91 request = self.post('users/sign_in',
92 data=self.login_data,
93 headers={'accept': 'application/json'})
94 if request.status_code != 201:
95 raise LoginError('{0}: Login failed.'.format(request.status_code))
96
97 def login(self, username='', password=''):
98 """This function is used to log in to a pod.
99 Will raise LoginError if password or username was not specified.
100 """
101 if username and password: self._setlogin(username, password)
102 if not self.username or not self.password: raise LoginError('password or username not specified')
103 self._login()
104
105 def podswitch(self, pod):
106 """Switches pod from current to another one.
107 """
108 self.pod = pod
109 self._login()
110
111 def getUserInfo(self):
112 """This function returns the current user's attributes.
113
114 :returns: dict -- json formatted user info.
115 """
116 request = self.get('bookmarklet')
117 userdata = json.loads(self._userinfo_regex.search(request.text).group(1))
118 return userdata
119
120 def get_token(self):
121 """This function returns a token needed for authentication in most cases.
122
123 :returns: string -- token used to authenticate
124 """
125 r = self.get('stream')
126 token = self._token_regex.search(r.text).group(1)
127 return token