server.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. #!/usr/bin/env python3
  2. import http.server
  3. import socketserver
  4. import configparser
  5. import os
  6. import time
  7. from urllib.parse import parse_qs
  8. import argparse
  9. import logging
  10. # Configure logging
  11. logging.basicConfig(level=logging.INFO)
  12. class ChatConfig:
  13. def __init__(self):
  14. self.config = configparser.ConfigParser()
  15. self.config_file = 'chat_records.ini'
  16. if not os.path.exists(self.config_file):
  17. open(self.config_file, 'w').close() # Create an empty file if it doesn't exist
  18. self.config.read(self.config_file)
  19. class ChatServer(http.server.BaseHTTPRequestHandler):
  20. rooms = {}
  21. max_rooms = 32
  22. max_messages_per_room = 50
  23. max_message_length = 2048
  24. max_messages_per_minute = 20
  25. message_rate_limit = {} # To track messages per minute
  26. def __init__(self, *args, **kwargs):
  27. super().__init__(*args, **kwargs)
  28. self.load_rooms()
  29. def do_GET(self):
  30. try:
  31. if self.path == '/':
  32. self.send_response(302)
  33. self.send_header('Location', '/index.html')
  34. self.end_headers()
  35. elif self.path == '/index.html':
  36. self.send_file('index.html')
  37. elif self.path == '/send_message':
  38. self.send_response(302)
  39. self.send_header('Location', '/chat')
  40. self.end_headers()
  41. elif self.path.startswith('/chat'):
  42. query_params = parse_qs(self.path[6:])
  43. nickname = query_params.get('nickname', ['匿名'])[0]
  44. roomid = query_params.get('roomid', ['默认'])[0]
  45. self.send_response(200)
  46. self.send_header('Content-type', 'text/html')
  47. self.end_headers()
  48. self.wfile.write(self.generate_chat_html(nickname, roomid).encode('utf-8'))
  49. elif self.path.endswith('.css'):
  50. self.send_file(self.path.lstrip('/'))
  51. else:
  52. self.send_error(404)
  53. except Exception as e:
  54. logging.error(f"Error processing GET request: {e}")
  55. self.send_error(500)
  56. def do_POST(self):
  57. try:
  58. if self.path == '/send_message':
  59. content_length = int(self.headers['Content-Length'])
  60. post_data = self.rfile.read(content_length).decode('utf-8')
  61. post_data = parse_qs(post_data)
  62. nickname = post_data.get('nickname', ['匿名'])[0]
  63. roomid = post_data.get('roomid', ['默认'])[0]
  64. message = post_data.get('messageInput', [''])[0]
  65. # Rate limiting
  66. if self.check_message_rate_limit(roomid):
  67. if message and len(message) <= self.max_message_length:
  68. self.add_message(roomid, nickname, message)
  69. self.send_response(302)
  70. self.send_header('Location', f'/chat?nickname={nickname}&roomid={roomid}')
  71. self.end_headers()
  72. else:
  73. self.send_error(429, "Too Many Requests")
  74. else:
  75. self.send_error(404)
  76. except Exception as e:
  77. logging.error(f"Error processing POST request: {e}")
  78. self.send_error(500)
  79. def check_message_rate_limit(self, roomid):
  80. current_time = time.time()
  81. if roomid not in self.message_rate_limit:
  82. self.message_rate_limit[roomid] = [current_time]
  83. return True
  84. # Remove old timestamps
  85. self.message_rate_limit[roomid] = [t for t in self.message_rate_limit[roomid] if t > current_time - 60]
  86. # Check if we have exceeded the limit
  87. if len(self.message_rate_limit[roomid]) >= self.max_messages_per_minute:
  88. return False
  89. self.message_rate_limit[roomid].append(current_time)
  90. return True
  91. def add_message(self, roomid, nickname, message):
  92. if roomid not in self.rooms:
  93. if len(self.rooms) >= self.max_rooms:
  94. oldest_room = next(iter(self.rooms))
  95. del self.rooms[oldest_room]
  96. self.rooms[roomid] = []
  97. messages = self.rooms[roomid]
  98. timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
  99. messages.append(f'{timestamp} {nickname}: {message}')
  100. if len(messages) > self.max_messages_per_room:
  101. messages.pop(0)
  102. def save_rooms(self):
  103. config = ChatConfig().config
  104. for roomid, messages in self.rooms.items():
  105. config[roomid] = {'messages': '\n'.join(messages)}
  106. with open(ChatConfig().config_file, 'w') as configfile:
  107. config.write(configfile, encoding='utf-8')
  108. def load_rooms(self):
  109. config = ChatConfig().config
  110. for section in config.sections():
  111. self.rooms[section] = config.get(section, 'messages').split('\n')
  112. def generate_chat_html(self, nickname, roomid):
  113. chat_log = '<br>'.join(self.rooms.get(roomid, []))
  114. return f'''
  115. <!DOCTYPE html>
  116. <html lang="zh-Hans">
  117. <head>
  118. <meta charset="UTF-8">
  119. <title>聊天室 - {roomid}</title>
  120. <meta http-equiv="refresh" content="60">
  121. <link type="text/css" rel="stylesheet" href="html-chat.css">
  122. </head>
  123. <body>
  124. <div class="container">
  125. <form action="/send_message" method="post">
  126. <fieldset>
  127. <legend>聊天室 - {roomid}</legend>
  128. <textarea id="chatLog" rows="10" cols="50" readonly>{chat_log}</textarea>
  129. <br>
  130. <label for="messageInput">{nickname}说:</label>
  131. <input type="text" id="messageInput" name="messageInput">
  132. <button type="submit">发送</button>
  133. <a href="."><button type="button">退出</button></a>
  134. </fieldset>
  135. <input type="text" id="nickname" name="nickname" value="{nickname}" style="display: none;">
  136. <input type="text" id="roomid" name="roomid" value="{roomid}" style="display: none;">
  137. </form>
  138. </div>
  139. </body>
  140. </html>
  141. '''
  142. def send_file(self, filename):
  143. try:
  144. if filename.endswith('.css'):
  145. self.send_response(200)
  146. self.send_header('Content-type', 'text/css')
  147. else:
  148. self.send_response(200)
  149. self.send_header('Content-type', 'text/html; charset=UTF-8')
  150. self.end_headers()
  151. with open(filename, 'rb') as file:
  152. self.wfile.write(file.read())
  153. except FileNotFoundError:
  154. logging.error(f"File not found: {filename}")
  155. self.send_error(404)
  156. def main():
  157. parser = argparse.ArgumentParser(description='Simple chat server.')
  158. parser.add_argument('--port', type=int, default=8000, help='Port to listen on.')
  159. args = parser.parse_args()
  160. server_address = ('0.0.0.0', args.port)
  161. httpd = socketserver.TCPServer(server_address, ChatServer)
  162. httpd.allow_reuse_address = True
  163. print(f'Starting server on port {args.port}...')
  164. httpd.serve_forever()
  165. if __name__ == '__main__':
  166. main()