9 """This module abstracts connection to pod.
13 class LoginError(Exception):
17 class TokenError(Exception):
22 """Object representing connection with the server.
23 It is pushed around internally and is considered private.
25 _token_regex
= re
.compile(r
'content="(.*?)"\s+name="csrf-token')
26 _userinfo_regex
= re
.compile(r
'window.current_user_attributes = ({.*})')
30 def __init__(self
, pod
, username
='', password
=''):
32 :param pod: The complete url of the diaspora pod to use.
34 :param username: The username used to log in.
36 :param password: The password used to log in.
40 self
.session
= requests
.Session()
42 self
._setlogin
(username
, password
)
43 except Exception as e
:
44 raise LoginError('cannot create login data (caused by: {0}'.format(e
))
46 def get(self
, string
, headers
={}, params
={}):
47 """This method gets data from session.
48 Performs additional checks if needed.
51 To obtain 'foo' from pod one should call `get('foo')`.
53 :param string: URL to get without the pod's URL and slash eg. 'stream'.
56 return self
.session
.get('{0}/{1}'.format(self
.pod
, string
), params
=params
, headers
=headers
)
58 def post(self
, string
, data
, headers
={}, params
={}):
59 """This method posts data to session.
60 Performs additional checks if needed.
63 To post to 'foo' one should call `post('foo', data={})`.
65 :param string: URL to post without the pod's URL and slash eg. 'status_messages'.
67 :param data: Data to post.
68 :param headers: Headers (optional).
70 :param params: Parameters (optional).
73 string
= '{0}/{1}'.format(self
.pod
, string
)
74 request
= self
.session
.post(string
, data
, headers
=headers
, params
=params
)
77 def put(self
, string
, data
=None, headers
={}, params
={}):
78 """This method PUTs to session.
80 string
= '{0}/{1}'.format(self
.pod
, string
)
81 if data
is not None: request
= self
.session
.put(string
, data
, headers
=headers
, params
=params
)
82 else: request
= self
.session
.put(string
, headers
=headers
, params
=params
)
85 def delete(self
, string
, data
, headers
={}):
86 """This method lets you send delete request to session.
87 Performs additional checks if needed.
89 :param string: URL to use.
91 :param data: Data to use.
92 :param headers: Headers to use (optional).
95 string
= '{0}/{1}'.format(self
.pod
, string
)
96 request
= self
.session
.delete(string
, data
=data
, headers
=headers
)
99 def _setlogin(self
, username
, password
):
100 """This function is used to set data for login.
103 It should be called before _login() function.
105 self
.username
, self
.password
= username
, password
106 self
.login_data
= {'user[username]': self
.username
,
107 'user[password]': self
.password
,
108 'authenticity_token': self
._fetchtoken
()}
111 """Handles actual login request.
112 Raises LoginError if login failed.
114 request
= self
.post('users/sign_in',
115 data
=self
.login_data
,
116 headers
={'accept': 'application/json'})
117 if request
.status_code
!= 201:
118 raise LoginError('{0}: login failed'.format(request
.status_code
))
120 def login(self
, username
='', password
=''):
121 """This function is used to log in to a pod.
122 Will raise LoginError if password or username was not specified.
124 if username
and password
: self
._setlogin
(username
, password
)
125 if not self
.username
or not self
.password
: raise LoginError('password or username not specified')
129 """Logs out from a pod.
130 When logged out you can't do anything.
132 self
.get('users/sign_out')
137 def podswitch(self
, pod
):
138 """Switches pod from current to another one.
143 def getUserInfo(self
):
144 """This function returns the current user's attributes.
146 :returns: dict -- json formatted user info.
148 request
= self
.get('bookmarklet')
149 userdata
= json
.loads(self
._userinfo
_regex
.search(request
.text
).group(1))
152 def _fetchtoken(self
):
153 """This method tries to get token string needed for authentication on D*.
155 :returns: token string
157 request
= self
.get('stream')
158 token
= self
._token
_regex
.search(request
.text
).group(1)
161 def get_token(self
, new
=False):
162 """This function returns a token needed for authentication in most cases.
163 Each time it is run a _fetchtoken() is called and refreshed token is stored.
165 It is more safe to use than _fetchtoken().
166 By setting new you can request new token or decide to get stored one.
167 If no token is stored new one will be fatched anyway.
169 :returns: string -- token used to authenticate
172 if new
: self
.token
= self
._fetchtoken
()
173 if not self
.token
: self
.token
= self
._fetchtoken
()
174 except requests
.exceptions
.ConnectionError
as e
:
175 warnings
.warn('{0} was cought: reusing old token'.format(e
))
177 if not self
.token
: raise TokenError('cannot obtain token and no previous token found for reuse')