#!/usr/bin/env python3
import http.server
import socketserver
import configparser
import os
import time
from urllib.parse import parse_qs
import argparse
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
class ChatConfig:
def __init__(self):
self.config = configparser.ConfigParser()
self.config_file = 'chat_records.ini'
if not os.path.exists(self.config_file):
open(self.config_file, 'w').close() # Create an empty file if it doesn't exist
self.config.read(self.config_file)
class ChatServer(http.server.BaseHTTPRequestHandler):
rooms = {}
max_rooms = 32
max_messages_per_room = 50
max_message_length = 2048
max_messages_per_minute = 20
message_rate_limit = {} # To track messages per minute
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.load_rooms()
def do_GET(self):
try:
if self.path == '/':
self.send_response(302)
self.send_header('Location', '/index.html')
self.end_headers()
elif self.path == '/index.html':
self.send_file('index.html')
elif self.path == '/send_message':
self.send_response(302)
self.send_header('Location', '/chat')
self.end_headers()
elif self.path.startswith('/chat'):
query_params = parse_qs(self.path[6:])
nickname = query_params.get('nickname', ['匿名'])[0]
roomid = query_params.get('roomid', ['默认'])[0]
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(self.generate_chat_html(nickname, roomid).encode('utf-8'))
elif self.path.endswith('.css'):
self.send_file(self.path.lstrip('/'))
else:
self.send_error(404)
except Exception as e:
logging.error(f"Error processing GET request: {e}")
self.send_error(500)
def do_POST(self):
try:
if self.path == '/send_message':
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf-8')
post_data = parse_qs(post_data)
nickname = post_data.get('nickname', ['匿名'])[0]
roomid = post_data.get('roomid', ['默认'])[0]
message = post_data.get('messageInput', [''])[0]
# Rate limiting
if self.check_message_rate_limit(roomid):
if message and len(message) <= self.max_message_length:
self.add_message(roomid, nickname, message)
self.send_response(302)
self.send_header('Location', f'/chat?nickname={nickname}&roomid={roomid}')
self.end_headers()
else:
self.send_error(429, "Too Many Requests")
else:
self.send_error(404)
except Exception as e:
logging.error(f"Error processing POST request: {e}")
self.send_error(500)
def check_message_rate_limit(self, roomid):
current_time = time.time()
if roomid not in self.message_rate_limit:
self.message_rate_limit[roomid] = [current_time]
return True
# Remove old timestamps
self.message_rate_limit[roomid] = [t for t in self.message_rate_limit[roomid] if t > current_time - 60]
# Check if we have exceeded the limit
if len(self.message_rate_limit[roomid]) >= self.max_messages_per_minute:
return False
self.message_rate_limit[roomid].append(current_time)
return True
def add_message(self, roomid, nickname, message):
if roomid not in self.rooms:
if len(self.rooms) >= self.max_rooms:
oldest_room = next(iter(self.rooms))
del self.rooms[oldest_room]
self.rooms[roomid] = []
messages = self.rooms[roomid]
timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
messages.append(f'{timestamp} {nickname}: {message}')
if len(messages) > self.max_messages_per_room:
messages.pop(0)
def save_rooms(self):
config = ChatConfig().config
for roomid, messages in self.rooms.items():
config[roomid] = {'messages': '\n'.join(messages)}
with open(ChatConfig().config_file, 'w') as configfile:
config.write(configfile, encoding='utf-8')
def load_rooms(self):
config = ChatConfig().config
for section in config.sections():
self.rooms[section] = config.get(section, 'messages').split('\n')
def generate_chat_html(self, nickname, roomid):
chat_log = '
'.join(self.rooms.get(roomid, []))
return f'''