为3.0服务器提供外接API功能

This commit is contained in:
DZY 2025-05-31 19:16:22 +08:00
parent caca23727c
commit 0870a2f923

View File

@ -39,6 +39,7 @@ class ChatServer:
def handle_client(self, client, address): def handle_client(self, client, address):
username = None username = None
try: try:
while True: while True:
message = client.recv(1024).decode('utf-8') message = client.recv(1024).decode('utf-8')
@ -98,6 +99,158 @@ class ChatServer:
if user in self.clients: if user in self.clients:
self.groups[group_name].add(user) self.groups[group_name].add(user)
self.send_group_list_to_all() self.send_group_list_to_all()
# 管理API处理逻辑
elif data['type'] == 'admin_get_users':
cursor = self.db.cursor()
cursor.execute('SELECT id, username FROM users')
users = [{'id': row[0], 'username': row[1]} for row in cursor.fetchall()]
client.send(json.dumps({'type': 'admin_response', 'data': users}).encode('utf-8'))
elif data['type'] == 'admin_create_user':
try:
cursor = self.db.cursor()
cursor.execute('INSERT INTO users (username, password) VALUES (?, ?)',
(data['username'], data['password']))
self.db.commit()
client.send(json.dumps({'type': 'admin_response', 'success': True}).encode('utf-8'))
except sqlite3.IntegrityError:
client.send(json.dumps({'type': 'admin_response', 'success': False, 'error': 'Username exists'}).encode('utf-8'))
elif data['type'] == 'admin_delete_user':
cursor = self.db.cursor()
try:
cursor.execute('DELETE FROM messages WHERE sender=? OR receiver=?',
(data['username'], data['username']))
cursor.execute('DELETE FROM users WHERE username=?', (data['username'],))
self.db.commit()
if data['username'] in self.clients:
self.clients[data['username']].close()
del self.clients[data['username']]
for group in self.groups.values():
if data['username'] in group:
group.remove(data['username'])
self.send_user_list()
self.send_group_list_to_all()
client.send(json.dumps({'type': 'admin_response', 'success': True}).encode('utf-8'))
except Exception as e:
client.send(json.dumps({'type': 'admin_response', 'success': False, 'error': str(e)}).encode('utf-8'))
elif data['type'] == 'admin_get_messages':
cursor = self.db.cursor()
query = 'SELECT id, sender, receiver, message, timestamp, is_group FROM messages WHERE 1=1'
params = []
if 'sender' in data and data['sender']:
query += ' AND sender=?'
params.append(data['sender'])
if 'receiver' in data and data['receiver']:
query += ' AND receiver=?'
params.append(data['receiver'])
if 'is_group' in data and data['is_group'] is not None:
query += ' AND is_group=?'
params.append(1 if data['is_group'] else 0)
if 'start_time' in data and data['start_time']:
query += ' AND timestamp >= ?'
params.append(data['start_time'])
if 'end_time' in data and data['end_time']:
query += ' AND timestamp <= ?'
params.append(data['end_time'])
query += ' ORDER BY timestamp DESC LIMIT 1000'
cursor.execute(query, params)
messages = []
for row in cursor.fetchall():
messages.append({
'id': row[0],
'sender': row[1],
'receiver': row[2],
'message': row[3],
'timestamp': row[4],
'is_group': bool(row[5])
})
client.send(json.dumps({'type': 'admin_response', 'data': messages}).encode('utf-8'))
elif data['type'] == 'admin_delete_message':
cursor = self.db.cursor()
cursor.execute('DELETE FROM messages WHERE id=?', (data['message_id'],))
self.db.commit()
client.send(json.dumps({'type': 'admin_response', 'success': True}).encode('utf-8'))
elif data['type'] == 'admin_get_groups':
groups = []
for name, members in self.groups.items():
groups.append({
'name': name,
'members': list(members)
})
client.send(json.dumps({'type': 'admin_response', 'data': groups}).encode('utf-8'))
elif data['type'] == 'admin_create_group':
group_name = data['group_name']
if group_name not in self.groups:
self.groups[group_name] = set()
for user in data['members']:
if user in self.clients or self.user_exists(user):
self.groups[group_name].add(user)
self.send_group_list_to_all()
client.send(json.dumps({'type': 'admin_response', 'success': True}).encode('utf-8'))
else:
client.send(json.dumps({'type': 'admin_response', 'success': False, 'error': 'Group already exists'}).encode('utf-8'))
elif data['type'] == 'admin_delete_group':
if data['group_name'] in self.groups:
del self.groups[data['group_name']]
cursor = self.db.cursor()
cursor.execute('DELETE FROM messages WHERE receiver=? AND is_group=1', (data['group_name'],))
self.db.commit()
self.send_group_list_to_all()
client.send(json.dumps({'type': 'admin_response', 'success': True}).encode('utf-8'))
else:
client.send(json.dumps({'type': 'admin_response', 'success': False, 'error': 'Group not found'}).encode('utf-8'))
elif data['type'] == 'admin_add_group_member':
if data['group_name'] in self.groups:
if data['username'] in self.clients or self.user_exists(data['username']):
self.groups[data['group_name']].add(data['username'])
if data['username'] in self.clients:
self.send_group_list(data['username'])
client.send(json.dumps({'type': 'admin_response', 'success': True}).encode('utf-8'))
else:
client.send(json.dumps({'type': 'admin_response', 'success': False, 'error': 'User not found'}).encode('utf-8'))
else:
client.send(json.dumps({'type': 'admin_response', 'success': False, 'error': 'Group not found'}).encode('utf-8'))
elif data['type'] == 'admin_remove_group_member':
if data['group_name'] in self.groups and data['username'] in self.groups[data['group_name']]:
self.groups[data['group_name']].remove(data['username'])
if data['username'] in self.clients:
self.send_group_list(data['username'])
client.send(json.dumps({'type': 'admin_response', 'success': True}).encode('utf-8'))
else:
client.send(json.dumps({'type': 'admin_response', 'success': False, 'error': 'Member not in group'}).encode('utf-8'))
elif data['type'] == 'admin_get_server_status':
status = {
'status': 'running',
'users_online': len(self.clients),
'groups': len(self.groups),
'start_time': str(datetime.now())
}
client.send(json.dumps({'type': 'admin_response', 'data': status}).encode('utf-8'))
elif data['type'] == 'admin_restart_server':
client.send(json.dumps({'type': 'admin_response', 'success': True, 'message': 'Restart command received'}).encode('utf-8'))
elif data['type'] == 'admin_shutdown_server':
client.send(json.dumps({'type': 'admin_response', 'success': True, 'message': 'Shutdown command received'}).encode('utf-8'))
threading.Thread(target=self.shutdown).start()
except Exception as e: except Exception as e:
print(f"Error handling client: {e}") print(f"Error handling client: {e}")
finally: finally: