Stream() object with some basic functionality implemented (plus manual
[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._setlogin(username, password)
30
31 def get(self, string):
32 """This method gets data from session.
33 Performs additional checks if needed.
34
35 Example:
36 To obtain 'foo' from pod one should call `get('foo')`.
37
38 :param string: URL to get without the pod's URL and slash eg. 'stream'.
39 :type string: str
40 """
41 return self.session.get('{0}/{1}'.format(self.pod, string))
42
43 def post(self, string, data, headers={}, params={}):
44 """This method posts data to session.
45 Performs additional checks if needed.
46
47 Example:
48 To post to 'foo' one should call `post('foo', data={})`.
49
50 :param string: URL to post without the pod's URL and slash eg. 'status_messages'.
51 :type string: str
52 :param data: Data to post.
53 :param headers: Headers (optional).
54 :type headers: dict
55 :param params: Parameters (optional).
56 :type params: dict
57 """
58 string = '{0}/{1}'.format(self.pod, string)
59 if headers and params:
60 request = self.session.post(string, data=data, headers=headers, params=params)
61 elif headers and not params:
62 request = self.session.post(string, data=data, headers=headers)
63 elif not headers and params:
64 request = self.session.post(string, data=data, params=params)
65 else:
66 request = self.session.post(string, data=data)
67 return request
68
69 def delete(self, string, data, headers={}):
70 """This method lets you send delete request to session.
71 Performs additional checks if needed.
72
73 :param string: URL to use.
74 :type string: str
75 :param data: Data to use.
76 :param headers: Headers to use (optional).
77 :type headers: dict
78 """
79 string = '{0}/{1}'.format(self.pod, string)
80 if headers:
81 request = self.session.delete(string, data=data, headers=headers)
82 else:
83 request = self.session.delete(string, data=data)
84 return request
85
86 def _setlogin(self, username, password):
87 """This function is used to set data for login.
88 .. note::
89 It should be called before _login() function.
90 """
91 self.username, self.password = username, password
92 self.login_data = {'user[username]': self.username,
93 'user[password]': self.password,
94 'authenticity_token': self.getToken()}
95
96 def _login(self):
97 """Handles actual login request.
98 Raises LoginError if login failed.
99 """
100 request = self.post('users/sign_in',
101 data=self.login_data,
102 headers={'accept': 'application/json'})
103 if request.status_code != 201:
104 raise LoginError('{0}: Login failed.'.format(request.status_code))
105
106 def login(self, username='', password=''):
107 """This function is used to log in to a pod.
108 Will raise LoginError if password or username was not specified.
109 """
110 if username and password: self._setlogin(username, password)
111 if not self.username or not self.password: raise LoginError('password or username not specified')
112 self._login()
113
114 def podswitch(self, pod):
115 """Switches pod from current to another one.
116 """
117 self.pod = pod
118 self._login()
119
120 def getUserInfo(self):
121 """This function returns the current user's attributes.
122
123 :returns: dict -- json formatted user info.
124 """
125 request = self.get('bookmarklet')
126 userdata = json.loads(self._userinfo_regex.search(request.text).group(1))
127 return userdata
128
129 def getToken(self):
130 """This function returns a token needed for authentication in most cases.
131
132 :returns: string -- token used to authenticate
133 """
134 r = self.get('stream')
135 token = self._token_regex.search(r.text).group(1)
136 return token