Skip to content

Commit 40b67c3

Browse files
Update directadmin_api.py
1 parent ee9e967 commit 40b67c3

File tree

1 file changed

+62
-27
lines changed

1 file changed

+62
-27
lines changed

app/directadmin_api.py

Lines changed: 62 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def _make_request(self, cmd, method='GET', data=None):
2828
auth=auth,
2929
verify=False,
3030
timeout=10,
31-
allow_redirects=True
31+
allow_redirects=False # Don't follow redirects
3232
)
3333
else:
3434
response = self.session.post(
@@ -38,38 +38,61 @@ def _make_request(self, cmd, method='GET', data=None):
3838
verify=False,
3939
timeout=10,
4040
headers={'Content-Type': 'application/x-www-form-urlencoded'},
41-
allow_redirects=True
41+
allow_redirects=False # Don't follow redirects
4242
)
4343

4444
print(f"Response status: {response.status_code}")
45-
print(f"Response headers: {response.headers}")
4645

4746
if response.status_code == 401:
48-
raise Exception("DirectAdmin authentication failed - check username/password")
47+
raise Exception("Authentication failed - invalid username or password")
48+
elif response.status_code == 302 or response.status_code == 301:
49+
# DirectAdmin might redirect on auth failure
50+
raise Exception("Authentication required - check credentials")
4951

5052
return response
5153
except requests.exceptions.ConnectionError:
52-
raise Exception(f"Cannot connect to DirectAdmin server at {self.server}")
54+
raise Exception(f"Cannot connect to server at {self.server}")
5355
except requests.exceptions.Timeout:
54-
raise Exception("DirectAdmin server timeout")
56+
raise Exception("Connection timeout - server not responding")
57+
except requests.exceptions.SSLError:
58+
raise Exception("SSL error - try using http:// instead of https://")
5559
except requests.exceptions.RequestException as e:
56-
raise Exception(f"DirectAdmin connection error: {str(e)}")
60+
raise Exception(f"Connection error: {str(e)}")
5761

5862
def test_connection(self):
59-
"""Test connection by getting API version or domains"""
63+
"""Test connection with a simple API call"""
6064
try:
61-
# Try multiple endpoints to test connection
62-
# First try SHOW_DOMAINS
63-
response = self._make_request('API_SHOW_DOMAINS')
64-
if response.status_code == 200:
65-
return True, "Connection successful"
66-
67-
# If that fails, try getting user info
68-
response = self._make_request('API_SHOW_USER_CONFIG')
69-
if response.status_code == 200:
70-
return True, "Connection successful"
71-
72-
return False, f"Unexpected response: {response.status_code}"
65+
# Try the simplest API call - show API version
66+
# Some of these endpoints might work depending on DA version
67+
test_endpoints = [
68+
'API_SHOW_DOMAINS', # List domains
69+
'API_SHOW_USER_USAGE', # Show user usage
70+
'API_SHOW_USER_CONFIG', # Show user config
71+
]
72+
73+
last_error = None
74+
for endpoint in test_endpoints:
75+
try:
76+
response = self._make_request(endpoint)
77+
if response.status_code == 200:
78+
# Check if response looks like DirectAdmin
79+
content = response.text.lower()
80+
if 'error=1' in content:
81+
# DirectAdmin error response
82+
continue
83+
elif '=' in response.text or response.text.strip():
84+
# Looks like a valid DirectAdmin response
85+
return True, "Connection successful!"
86+
except Exception as e:
87+
last_error = str(e)
88+
print(f"Test endpoint {endpoint} failed: {e}")
89+
continue
90+
91+
# If we get here, no endpoint worked
92+
if last_error:
93+
return False, last_error
94+
else:
95+
return False, "Could not verify DirectAdmin API access"
7396

7497
except Exception as e:
7598
return False, str(e)
@@ -82,20 +105,32 @@ def get_email_accounts(self, domain):
82105
# Parse the response - DirectAdmin returns URL-encoded list
83106
if response.text.strip():
84107
# Response format: account1=data&account2=data&...
85-
parsed = parse_qs(response.text.strip())
86-
for account_name in parsed.keys():
87-
# Skip the API username and system accounts
88-
if (account_name != self.username and
89-
not account_name.startswith('_') and
90-
'@' not in account_name):
91-
accounts.append(f"{account_name}@{domain}")
108+
# or sometimes: account1&account2&account3
109+
if '=' in response.text:
110+
parsed = parse_qs(response.text.strip())
111+
for account_name in parsed.keys():
112+
if (account_name != self.username and
113+
not account_name.startswith('_') and
114+
'@' not in account_name):
115+
accounts.append(f"{account_name}@{domain}")
116+
else:
117+
# Simple list format
118+
for line in response.text.strip().split('\n'):
119+
account_name = line.split('&')[0].strip()
120+
if (account_name and
121+
account_name != self.username and
122+
not account_name.startswith('_')):
123+
accounts.append(f"{account_name}@{domain}")
92124

93125
return sorted(accounts)
94126
return []
95127
except Exception as e:
96128
print(f"Error in get_email_accounts: {e}")
97129
return []
98130

131+
# ... rest of the methods remain the same ...
132+
133+
99134
def get_forwarders(self, domain):
100135
try:
101136
response = self._make_request(f'API_EMAIL_FORWARDERS?domain={domain}')

0 commit comments

Comments
 (0)