server.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. #!/usr/bin/env python3
  2. import threading
  3. import http.server
  4. import socketserver
  5. import configparser
  6. import os
  7. import time
  8. from urllib.parse import parse_qs, quote
  9. import argparse
  10. import logging
  11. # Configure logging
  12. logging.basicConfig(level=logging.INFO)
  13. class ChatConfig:
  14. def __init__(self):
  15. self.config = configparser.ConfigParser()
  16. self.config_file = 'chat_records.ini'
  17. if not os.path.exists(self.config_file):
  18. open(self.config_file, 'w', encoding='utf-8').close()
  19. with open(self.config_file, 'r', encoding='utf-8') as config_file:
  20. self.config.read_file(config_file)
  21. class ChatServer(http.server.BaseHTTPRequestHandler):
  22. rooms = {}
  23. max_rooms = 32
  24. max_messages_per_room = 50
  25. max_message_length = 2048
  26. max_messages_per_minute = 20
  27. message_rate_limit = {} # To track messages per minute
  28. def __init__(self, *args, **kwargs):
  29. super().__init__(*args, **kwargs)
  30. self.load_rooms()
  31. # 创建一个线程,每 120 秒保存一次聊天数据
  32. self.save_thread = threading.Thread(target=self.save_rooms_periodically)
  33. self.save_thread.daemon = True
  34. self.save_thread.start()
  35. def do_GET(self):
  36. try:
  37. if self.path == '/':
  38. self.send_file('index.html')
  39. elif self.path == '/index.html':
  40. self.send_file('index.html')
  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))
  49. elif self.path.startswith('/log'):
  50. query_string = self.path.split('?', 1)[-1]
  51. query_params = parse_qs(query_string)
  52. roomid = query_params.get('id', ['默认'])[0]
  53. self.send_response(200)
  54. self.send_header('Content-type', 'text/html')
  55. self.end_headers()
  56. self.wfile.write(self.generate_chat_log_html(roomid))
  57. elif self.path.endswith('.css'):
  58. self.send_file(self.path.lstrip('/'))
  59. else:
  60. self.send_error(404)
  61. except Exception as e:
  62. logging.error(f"Error processing GET request: {e}")
  63. self.send_error(500)
  64. def do_POST(self):
  65. try:
  66. if self.path == '/send_message':
  67. content_length = int(self.headers['Content-Length'])
  68. post_data = self.rfile.read(content_length).decode('utf-8')
  69. post_data = parse_qs(post_data)
  70. nickname = post_data.get('nickname', ['匿名'])[0]
  71. roomid = post_data.get('roomid', ['默认'])[0]
  72. message = post_data.get('messageInput', [''])[0]
  73. # 检查非法字符
  74. illegal_chars = ['<', '>', '&', '"', "'"]
  75. if any(char in message for char in illegal_chars):
  76. self.send_error(400, "Bad Request: Message contains illegal characters.")
  77. return
  78. # 发送频率上限检查
  79. if self.check_message_rate_limit(roomid):
  80. if message and len(message) <= self.max_message_length:
  81. self.add_message(roomid, nickname, message)
  82. else:
  83. self.send_error(413, "Request Entity Too Large")
  84. return
  85. self.send_response(302)
  86. self.send_header('Location', f'/chat?nickname={quote(nickname)}&roomid={quote(roomid)}')
  87. self.end_headers()
  88. self.save_rooms() # 不执行会导致用户无法第一时间读取最新聊天记录
  89. else:
  90. self.send_error(429, "Too Many Requests")
  91. else:
  92. self.send_error(404)
  93. except Exception as e:
  94. logging.error(f"Error processing POST request: {e}")
  95. self.send_error(500)
  96. def check_message_rate_limit(self, roomid):
  97. current_time = time.time()
  98. if roomid not in self.message_rate_limit:
  99. self.message_rate_limit[roomid] = [current_time]
  100. return True
  101. # Remove old timestamps
  102. self.message_rate_limit[roomid] = [t for t in self.message_rate_limit[roomid] if t > current_time - 60]
  103. # 检查是否达到频率上限
  104. if len(self.message_rate_limit[roomid]) >= self.max_messages_per_minute:
  105. return False
  106. self.message_rate_limit[roomid].append(current_time)
  107. return True
  108. def add_message(self, roomid, nickname, message):
  109. if roomid not in self.rooms:
  110. if len(self.rooms) >= self.max_rooms:
  111. oldest_room = next(iter(self.rooms))
  112. del self.rooms[oldest_room]
  113. self.rooms[roomid] = []
  114. messages = self.rooms[roomid]
  115. timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
  116. messages.append(f'{timestamp} {nickname}: {message}')
  117. if len(messages) > self.max_messages_per_room:
  118. messages.pop(0)
  119. def save_rooms(self):
  120. config = ChatConfig().config
  121. for roomid, messages in self.rooms.items():
  122. config[roomid] = {'messages': '\n'.join(messages)}
  123. with open(ChatConfig().config_file, 'w', encoding='utf-8') as configfile:
  124. config.write(configfile)
  125. def save_rooms_periodically(self):
  126. while True:
  127. self.save_rooms()
  128. time.sleep(120)
  129. def load_rooms(self):
  130. config = ChatConfig().config
  131. for section in config.sections():
  132. self.rooms[section] = config.get(section, 'messages').split('\n')
  133. def generate_chat_html(self, nickname, roomid):
  134. return f'''<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><title>聊天室 - {roomid}</title><link type="text/css" rel="stylesheet" href="html-chat.css"><meta name="viewport" content="width=192, initial-scale=1.0"></head><body><div class="container"><form action="./send_message" method="post"><fieldset><legend>聊天室 - {roomid}</legend><iframe src="./log?id={roomid}" frameborder="0">加载中……</iframe><br><label for="messageInput">{nickname}说:</label><input type="text" id="messageInput" name="messageInput"><button type="submit">发送</button><a href=".">退出</a></fieldset><input type="text" id="nickname" name="nickname" value="{nickname}" style="display: none;"><input type="text" id="roomid" name="roomid" value="{roomid}" style="display: none;"></form></div></body></html>'''.encode('utf-8')
  135. def generate_chat_log_html(self, roomid):
  136. messages = self.rooms.get(roomid, [])
  137. chat_log = '<br>'.join(messages) if messages else '<p style="color:#ccc">无聊天记录</p>'
  138. return f'''<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><title>聊天记录 - {roomid}</title><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="refresh" content="60"></head><body style="font-family: Arial, sans-serif;"><span>{chat_log}</span></body></html>'''.encode('utf-8')
  139. def send_file(self, filename):
  140. try:
  141. if filename.endswith('.css'):
  142. self.send_response(200)
  143. self.send_header('Content-type', 'text/css; charset=UTF-8')
  144. else:
  145. self.send_response(200)
  146. self.send_header('Content-type', 'text/html; charset=UTF-8')
  147. self.end_headers()
  148. with open(filename, 'rb') as file:
  149. self.wfile.write(file.read())
  150. except FileNotFoundError:
  151. logging.error(f"File not found: {filename}")
  152. self.send_error(404)
  153. def main():
  154. parser = argparse.ArgumentParser(description='聊天室')
  155. parser.add_argument('--port', type=int, default=2666, help='Port to listen on.')
  156. args = parser.parse_args()
  157. server_address = ('0.0.0.0', args.port)
  158. httpd = socketserver.TCPServer(server_address, ChatServer)
  159. httpd.allow_reuse_address = True
  160. print(f'Starting server at http://127.0.0.1:{args.port} ...')
  161. httpd.serve_forever()
  162. if __name__ == '__main__':
  163. main()