Refactor: Implement user information retrieval in Python

This commit is contained in:
Whispering Wind
2025-05-02 12:29:37 +03:30
committed by GitHub
parent 19192bd02d
commit cf4726e5d9
4 changed files with 68 additions and 44 deletions

View File

@ -22,7 +22,7 @@ class Command(Enum):
RESTART_HYSTERIA2 = os.path.join(SCRIPT_DIR, 'hysteria2', 'restart.sh')
CHANGE_PORT_HYSTERIA2 = os.path.join(SCRIPT_DIR, 'hysteria2', 'change_port.py')
CHANGE_SNI_HYSTERIA2 = os.path.join(SCRIPT_DIR, 'hysteria2', 'change_sni.sh')
GET_USER = os.path.join(SCRIPT_DIR, 'hysteria2', 'get_user.sh')
GET_USER = os.path.join(SCRIPT_DIR, 'hysteria2', 'get_user.py')
ADD_USER = os.path.join(SCRIPT_DIR, 'hysteria2', 'add_user.sh')
EDIT_USER = os.path.join(SCRIPT_DIR, 'hysteria2', 'edit_user.sh')
RESET_USER = os.path.join(SCRIPT_DIR, 'hysteria2', 'reset_user.py')
@ -243,7 +243,7 @@ def get_user(username: str) -> dict[str, Any] | None:
'''
Retrieves information about a specific user.
'''
if res := run_cmd(['bash', Command.GET_USER.value, '-u', str(username)]):
if res := run_cmd(['python3', Command.GET_USER.value, '-u', str(username)]):
return json.loads(res)

View File

@ -0,0 +1,64 @@
#!/usr/bin/env python3
import json
import sys
import os
import getopt
from init_paths import *
from paths import *
def get_user_info(username):
"""
Retrieves and prints information for a specific user from the USERS_FILE.
Args:
username (str): The username to look up.
Returns:
int: 0 on success, 1 on failure.
"""
if not os.path.isfile(USERS_FILE):
print(f"users.json file not found at {USERS_FILE}!")
return 1
try:
with open(USERS_FILE, 'r') as f:
users_data = json.load(f)
except json.JSONDecodeError:
print(f"Error: {USERS_FILE} contains invalid JSON.")
return 1
if username in users_data:
user_info = users_data[username]
print(json.dumps(user_info, indent=4)) # Print with indentation for readability
# upload_bytes = user_info.get('upload_bytes', "No upload data available")
# download_bytes = user_info.get('download_bytes', "No download data available")
# status = user_info.get('status', "Status unavailable")
# You can choose to print these individually as well, if needed
# print(f"Upload Bytes: {upload_bytes}")
# print(f"Download Bytes: {download_bytes}")
# print(f"Status: {status}")
return 0
else:
print(f"User '{username}' not found in {USERS_FILE}.")
return 1
if __name__ == "__main__":
username = None
try:
opts, args = getopt.getopt(sys.argv[1:], "u:", ["username="])
except getopt.GetoptError as err:
print(str(err))
print(f"Usage: {sys.argv[0]} -u <username>")
sys.exit(1)
for opt, arg in opts:
if opt in ("-u", "--username"):
username = arg
if not username:
print(f"Usage: {sys.argv[0]} -u <username>")
sys.exit(1)
exit_code = get_user_info(username)
sys.exit(exit_code)

View File

@ -1,40 +0,0 @@
#!/bin/bash
source /etc/hysteria/core/scripts/path.sh
while getopts ":u:" opt; do
case ${opt} in
u )
USERNAME=$OPTARG
;;
\? )
echo "Usage: $0 -u <username>"
exit 1
;;
esac
done
if [ -z "$USERNAME" ]; then
echo "Usage: $0 -u <username>"
exit 1
fi
if [ ! -f "$USERS_FILE" ]; then
echo "users.json file not found at $USERS_FILE!"
exit 1
fi
USER_INFO=$(jq -r --arg username "$USERNAME" '.[$username] // empty' "$USERS_FILE")
if [ -z "$USER_INFO" ]; then
echo "User '$USERNAME' not found in $USERS_FILE."
exit 1
fi
echo "$USER_INFO" | jq .
UPLOAD_BYTES=$(echo "$USER_INFO" | jq -r '.upload_bytes // "No upload data available"')
DOWNLOAD_BYTES=$(echo "$USER_INFO" | jq -r '.download_bytes // "No download data available"')
STATUS=$(echo "$USER_INFO" | jq -r '.status // "Status unavailable"')
exit 0

View File

@ -180,8 +180,8 @@ hysteria2_get_user_handler() {
user_data=$(python3 "$CLI_PATH" get-user --username "$username" 2>/dev/null)
if [[ $? -ne 0 ]]; then
echo -e "${red}Error:${NC} User '$username' not found."
if [[ $exit_code -ne 0 || -z "$user_data" ]]; then
echo -e "${red}Error:${NC} User '$username' not found or invalid response."
return 1
fi