3
3
import requests
4
4
from .compat import encode_requests_password
5
5
6
+ import logging
7
+ _logger = logging .getLogger (__name__ )
8
+
6
9
7
10
class NextCloudConnectionError (Exception ):
8
11
""" A connection error occurred """
@@ -31,7 +34,7 @@ def __init__(self, url=None, user=None, password=None, auth=None, session_kwargs
31
34
self .auth = None
32
35
self .user = None
33
36
self ._set_credentials (user , password , auth )
34
- self .url = url
37
+ self .url = url . rstrip ( '/' )
35
38
self ._session_kwargs = session_kwargs or {}
36
39
37
40
def _set_credentials (self , user , password , auth ):
@@ -41,12 +44,11 @@ def _set_credentials(self, user, password, auth):
41
44
self .user = user
42
45
else :
43
46
if isinstance (self .auth , tuple ):
44
- (self .user , password ) = self .auth
45
- self .auth = None
47
+ self .user = self .auth [0 ]
46
48
else :
47
49
if isinstance (self .auth , requests .auth .AuthBase ):
48
50
self .user = self .auth .username
49
- if not self .auth :
51
+ if not self .auth and ( self . user and password ) :
50
52
self .auth = (self .user , encode_requests_password (password ))
51
53
52
54
def request (self , method , url , ** kwargs ):
@@ -75,18 +77,35 @@ def login(self, user=None, password=None, auth=None, client=None):
75
77
self ._set_credentials (user , password , auth )
76
78
self .session .auth = self .auth
77
79
if client :
78
- try :
79
- resp = client .with_attr (json_output = True ).get_user ()
80
- if not resp .is_ok :
81
- raise NextCloudLoginError (
82
- 'Failed to login to NextCloud' , self .url , resp )
83
- except requests .exceptions .SSLError as e :
84
- self .logout ()
85
- raise e
86
- except Exception as e :
80
+ self ._check_session (client .with_attr (json_output = True ), retry = 3 )
81
+
82
+
83
+ def _check_session (self , client = None , retry = None ):
84
+ def _clear ():
85
+ if self .session :
87
86
self .logout ()
87
+
88
+ def _raise (e ):
89
+ if retry :
90
+ _logger .warning ('Retry session check (%s)' , self .url )
91
+ return self ._check_session (client , retry = retry - 1 )
92
+ else :
93
+ _clear ()
88
94
raise e
89
95
96
+ try :
97
+ resp = client .get_user ()
98
+ if not resp .is_ok :
99
+ _raise (NextCloudLoginError (
100
+ 'Failed to login to NextCloud' , self .url , resp ))
101
+ except requests .exceptions .SSLError as e :
102
+ _raise (e )
103
+ except NextCloudConnectionError as e :
104
+ _raise (e )
105
+ except Exception as e :
106
+ _clear ()
107
+ raise e
108
+
90
109
def logout (self ):
91
110
"""Log out the authenticated user and close the session.
92
111
0 commit comments