-
Notifications
You must be signed in to change notification settings - Fork 1
/
connection.py
201 lines (169 loc) · 6.26 KB
/
connection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# coding: utf-8
# This file is part of Cae Mobile.
#
# Cae Mobile is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Cae Mobile is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Cae Mobile. If not, see <http://www.gnu.org/licenses/>.
''' Connection object to manage the communication with autonomie server
'''
import urlparse
from kivy.network.urlrequest import UrlRequest
from kivy.event import EventDispatcher
from kivy.properties import (
ObjectProperty, StringProperty, DictProperty, ListProperty)
from kivy.logger import Logger
from functools import partial
from json import JSONDecoder, JSONEncoder
import mock
JSON_ENCODE = JSONEncoder().encode
JSON_DECODE = JSONDecoder().raw_decode
API_PATH = '/api/v1/'
class Connection(EventDispatcher):
''' see module config
'''
cookie = ObjectProperty(None)
server = StringProperty('')
login = StringProperty('')
password = StringProperty('')
requests = ListProperty([])
to_sync = DictProperty({})
errors = ListProperty([])
def auth_redirect(self, path, request, result, **kwargs):
''' This should be called when a connection request succeed
'''
self.cookie = request.resp_headers.get('set-cookie')
if result['status'] == 'success':
self.request(path, **kwargs)
else:
self.connection_error(
request,
error='Erreur de connection, merci de vérifier vos'
'identifiants\n')
def base_url(self):
"""
returns the url for the application. Value is cached.
"""
if hasattr(self, '_base_url'):
return self._base_url
if not self.server.endswith('/'):
self.server += '/'
base_url = urlparse.urljoin(self.server, API_PATH)
if any(base_url.startswith(scheme)
for scheme in ('http://', 'https://')
):
self._base_url = base_url
else:
self._base_url = 'http://%s' % base_url
Logger.info('computed base_url: %s' % self._base_url)
return self._base_url
def _get_headers(self):
"""
Return the headers used to request the remote rest api
"""
headers = {'Content-type': 'text/json',
'Accept': 'text/json',
'X-Requested-With': 'XMLHttpRequest'}
if self.cookie is not None:
headers["Cookie"] = self.cookie
return headers
def _get_request(self, url, body, on_success, on_error, on_progress=None,
**kwargs):
"""
Return a request object based on the passed datas
"""
headers = self._get_headers()
return UrlRequest(
url,
req_body=body,
req_headers=headers,
on_success=on_success,
on_error=on_error,
on_failure=on_error,
on_progress=on_progress,
**kwargs)
def _get_credentials(self):
"""
Return the credentials used for the auth request
"""
Logger.debug("Credentials : {0} {1}".format(self.login, self.password))
return JSON_ENCODE({
'login': self.login,
'password': self.password,
'submit': 'submit', # reserved for future use
})
def request(self, path, req_body, **kwargs):
"""
Base method to send requests to server, autoconnect if needed
"""
if self.server.startswith('mock'):
success = kwargs.pop('on_success', None)
error = kwargs.pop('on_error', None)
answer, req, resp = mock.get_answer(path, req_body, **kwargs)
print success
if answer and success:
print "success"
success(req, resp)
elif not answer and error:
error(req, resp)
return
base_url = self.base_url()
if not self.cookie:
Logger.info("Ndf: not logged in, authenticating")
# get a cookie then call again
body = self._get_credentials()
Logger.info(body)
accept_login = partial(
self.auth_redirect,
path,
req_body=req_body,
#on_progress=Logger.info,
**kwargs
)
on_error = partial(
self.connection_error,
error=r"Impossible de contacter le serveur renseigné "
r"dans la configuration, veuillez vérifier "
r"que l'adresse est correcte.")
self._get_request(
base_url + 'login',
body,
accept_login,
on_error)
else:
on_success = kwargs.pop('on_success', None)
on_error = kwargs.pop('on_error', None)
on_progress = kwargs.pop('on_progress', None)
body = JSON_ENCODE(req_body)
url = urlparse.urljoin(base_url, path)
Logger.info(" + Calling the following url : %s" % url)
self._get_request(
url,
body,
on_success,
on_error,
on_progress,
**kwargs
)
def check_auth(self, success, error):
"""
Check authentification and launch the callback
"""
url = self.base_url() + 'login'
body = self._get_credentials()
print self.server, success, error
if self.server.startswith('mock'):
return self.request(url, body, on_success=success, on_error=error)
self._get_request(url, body, success, error)
def connection_error(self, request, error='Undefined error', *args):
Logger.info(error)
self.errors.append(error)
Logger.debug('%s' % request)