4 """This module abstracts connection to pod.
13 from diaspy
import errors
20 """Object representing connection with the pod.
22 _token_regex
= re
.compile(r
'content="(.*?)"\s+name="csrf-token')
23 _userinfo_regex
= re
.compile(r
'window.current_user_attributes = ({.*})')
24 _userinfo_regex_2
= re
.compile(r
'gon.user=({.*});gon.preloads')
26 def __init__(self
, pod
, username
, password
, schema
='https'):
28 :param pod: The complete url of the diaspora pod to use.
30 :param username: The username used to log in.
32 :param password: The password used to log in.
36 self
._session
= requests
.Session()
37 self
._login
_data
= {'user[remember_me]': 1, 'utf8': '✓'}
40 self
._diaspora
_session
= ''
41 self
._cookies
= self
._fetchcookies
()
43 #self._setlogin(username, password)
44 self
._login
_data
= {'user[username]': username
,
45 'user[password]': password
,
46 'authenticity_token': self
._fetchtoken
()}
48 except requests
.exceptions
.MissingSchema
:
49 self
.pod
= '{0}://{1}'.format(schema
, self
.pod
)
50 warnings
.warn('schema was missing')
56 self
._login
_data
= {'user[username]': username
,
57 'user[password]': password
,
58 'authenticity_token': self
._fetchtoken
()}
59 except Exception as e
:
60 raise errors
.LoginError('cannot create login data (caused by: {0})'.format(e
))
62 def _fetchcookies(self
):
63 request
= self
.get('stream')
64 return request
.cookies
67 """Returns token string.
68 It will be easier to change backend if programs will just use:
70 instead of calling a specified method.
72 return self
._fetchtoken
()
74 def get(self
, string
, headers
={}, params
={}, direct
=False, **kwargs
):
75 """This method gets data from session.
76 Performs additional checks if needed.
79 To obtain 'foo' from pod one should call `get('foo')`.
81 :param string: URL to get without the pod's URL and slash eg. 'stream'.
83 :param direct: if passed as True it will not be expanded
86 if not direct
: url
= '{0}/{1}'.format(self
.pod
, string
)
88 return self
._session
.get(url
, params
=params
, headers
=headers
, **kwargs
)
90 def post(self
, string
, data
, headers
={}, params
={}, **kwargs
):
91 """This method posts data to session.
92 Performs additional checks if needed.
95 To post to 'foo' one should call `post('foo', data={})`.
97 :param string: URL to post without the pod's URL and slash eg. 'status_messages'.
99 :param data: Data to post.
100 :param headers: Headers (optional).
102 :param params: Parameters (optional).
105 string
= '{0}/{1}'.format(self
.pod
, string
)
106 request
= self
._session
.post(string
, data
, headers
=headers
, params
=params
, **kwargs
)
109 def put(self
, string
, data
=None, headers
={}, params
={}, **kwargs
):
110 """This method PUTs to session.
112 string
= '{0}/{1}'.format(self
.pod
, string
)
113 if data
is not None: request
= self
._session
.put(string
, data
, headers
=headers
, params
=params
, **kwargs
)
114 else: request
= self
._session
.put(string
, headers
=headers
, params
=params
, **kwargs
)
117 def delete(self
, string
, data
, headers
={}, **kwargs
):
118 """This method lets you send delete request to session.
119 Performs additional checks if needed.
121 :param string: URL to use.
123 :param data: Data to use.
124 :param headers: Headers to use (optional).
127 string
= '{0}/{1}'.format(self
.pod
, string
)
128 request
= self
._session
.delete(string
, data
=data
, headers
=headers
, **kwargs
)
131 def _setlogin(self
, username
, password
):
132 """This function is used to set data for login.
135 It should be called before _login() function.
137 self
._login
_data
= {'user[username]': username
,
138 'user[password]': password
,
139 'authenticity_token': self
._fetchtoken
()}
142 """Handles actual login request.
143 Raises LoginError if login failed.
145 request
= self
.post('users/sign_in',
146 data
=self
._login
_data
,
147 allow_redirects
=False)
148 if request
.status_code
!= 302:
149 raise errors
.LoginError('{0}: login failed'.format(request
.status_code
))
150 return request
.status_code
152 def login(self
, remember_me
=1):
153 """This function is used to log in to a pod.
154 Will raise LoginError if password or username was not specified.
156 if not self
._login
_data
['user[username]'] or not self
._login
_data
['user[password]']:
157 raise errors
.LoginError('username and/or password is not specified')
158 self
._login
_data
['user[remember_me]'] = remember_me
159 status
= self
._login
()
160 self
._login
_data
= {}
164 """Logs out from a pod.
165 When logged out you can't do anything.
167 self
.get('users/sign_out')
170 def podswitch(self
, pod
, username
, password
):
171 """Switches pod from current to another one.
174 self
._setlogin
(username
, password
)
177 def getUserInfo(self
, fetch
=False):
178 """This function returns the current user's attributes.
180 :returns: dict -- json formatted user info.
182 request
= self
.get('bookmarklet')
183 userdata
= self
._userinfo
_regex
.search(request
.text
)
184 if userdata
is None: userdata
= self
._userinfo
_regex
_2.search(request
.text
)
185 if userdata
is None: raise errors
.DiaspyError('cannot find user data')
186 userdata
= userdata
.group(1)
187 warnings
.warn(userdata
)
188 return json
.loads(userdata
)
190 def _fetchtoken(self
):
191 """This method tries to get token string needed for authentication on D*.
193 :returns: token string
195 request
= self
.get('stream')
196 if DEBUG
: print('_fetchtoken(): status code:', request
.status_code
)
197 token
= self
._token
_regex
.search(request
.text
).group(1)
201 def get_token(self
, fetch
=True):
202 """This function returns a token needed for authentication in most cases.
203 **Notice:** using repr() is recommended method for getting token.
205 Each time it is run a _fetchtoken() is called and refreshed token is stored.
207 It is more safe to use than _fetchtoken().
208 By setting new you can request new token or decide to get stored one.
209 If no token is stored new one will be fetched anyway.
211 :returns: string -- token used to authenticate
214 if fetch
or not self
._token
: self
._fetchtoken
()
215 except requests
.exceptions
.ConnectionError
as e
:
216 warnings
.warn('{0} was cought: reusing old token'.format(e
))
218 if not self
._token
: raise errors
.TokenError('cannot obtain token and no previous token found for reuse')
221 def getSessionToken(self
):
222 """Returns session token string (_diaspora_session).
224 return self
._diaspora
_session