server.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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_response(302)
  39. self.send_header('Location', '/index.html')
  40. self.end_headers()
  41. elif self.path == '/index.html':
  42. self.send_file('index.html')
  43. elif self.path.startswith('/chat'):
  44. query_params = parse_qs(self.path[6:])
  45. nickname = query_params.get('nickname', ['匿名'])[0]
  46. roomid = query_params.get('roomid', ['默认'])[0]
  47. self.send_response(200)
  48. self.send_header('Content-type', 'text/html')
  49. self.end_headers()
  50. self.wfile.write(self.generate_chat_html(nickname, roomid))
  51. elif self.path.startswith('/log'):
  52. query_string = self.path.split('?', 1)[-1]
  53. query_params = parse_qs(query_string)
  54. roomid = query_params.get('id', ['默认'])[0]
  55. self.send_response(200)
  56. self.send_header('Content-type', 'text/html')
  57. self.end_headers()
  58. self.wfile.write(self.generate_chat_log_html(roomid))
  59. elif self.path.endswith('.css'):
  60. self.send_file(self.path.lstrip('/'))
  61. else:
  62. self.send_error(404)
  63. except Exception as e:
  64. logging.error(f"Error processing GET request: {e}")
  65. self.send_error(500)
  66. def do_POST(self):
  67. try:
  68. if self.path == '/send_message':
  69. content_length = int(self.headers['Content-Length'])
  70. post_data = self.rfile.read(content_length).decode('utf-8')
  71. post_data = parse_qs(post_data)
  72. nickname = post_data.get('nickname', ['匿名'])[0]
  73. roomid = post_data.get('roomid', ['默认'])[0]
  74. message = post_data.get('messageInput', [''])[0]
  75. # 检查非法字符
  76. illegal_chars = ['<', '>', '&', '"', "'"]
  77. if any(char in message for char in illegal_chars):
  78. self.send_error(400, "Bad Request: Message contains illegal characters.")
  79. return
  80. # 发送频率上限检查
  81. if self.check_message_rate_limit(roomid):
  82. if message and len(message) <= self.max_message_length:
  83. self.add_message(roomid, nickname, message)
  84. else:
  85. self.send_error(413, "Request Entity Too Large")
  86. return
  87. self.send_response(302)
  88. self.send_header('Location', f'/chat?nickname={quote(nickname)}&roomid={quote(roomid)}')
  89. self.end_headers()
  90. self.save_rooms() # 不执行会导致用户无法第一时间读取最新聊天记录
  91. else:
  92. self.send_error(429, "Too Many Requests")
  93. else:
  94. self.send_error(404)
  95. except Exception as e:
  96. logging.error(f"Error processing POST request: {e}")
  97. self.send_error(500)
  98. def check_message_rate_limit(self, roomid):
  99. current_time = time.time()
  100. if roomid not in self.message_rate_limit:
  101. self.message_rate_limit[roomid] = [current_time]
  102. return True
  103. # Remove old timestamps
  104. self.message_rate_limit[roomid] = [t for t in self.message_rate_limit[roomid] if t > current_time - 60]
  105. # 检查是否达到频率上限
  106. if len(self.message_rate_limit[roomid]) >= self.max_messages_per_minute:
  107. return False
  108. self.message_rate_limit[roomid].append(current_time)
  109. return True
  110. def add_message(self, roomid, nickname, message):
  111. if roomid not in self.rooms:
  112. if len(self.rooms) >= self.max_rooms:
  113. oldest_room = next(iter(self.rooms))
  114. del self.rooms[oldest_room]
  115. self.rooms[roomid] = []
  116. messages = self.rooms[roomid]
  117. timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
  118. messages.append(f'{timestamp} {nickname}: {message}')
  119. if len(messages) > self.max_messages_per_room:
  120. messages.pop(0)
  121. def save_rooms(self):
  122. config = ChatConfig().config
  123. for roomid, messages in self.rooms.items():
  124. config[roomid] = {'messages': '\n'.join(messages)}
  125. with open(ChatConfig().config_file, 'w', encoding='utf-8') as configfile:
  126. config.write(configfile)
  127. def save_rooms_periodically(self):
  128. while True:
  129. self.save_rooms()
  130. time.sleep(120)
  131. def load_rooms(self):
  132. config = ChatConfig().config
  133. for section in config.sections():
  134. self.rooms[section] = config.get(section, 'messages').split('\n')
  135. def generate_chat_html(self, nickname, roomid):
  136. return f'''
  137. <!DOCTYPE html>
  138. <html lang="zh-Hans">
  139. <head>
  140. <meta charset="UTF-8">
  141. <title>聊天室 - {roomid}</title>
  142. <link type="text/css" rel="stylesheet" href="html-chat.css">
  143. <meta name="viewport" content="width=192, initial-scale=1.0">
  144. </head>
  145. <body>
  146. <div class="container">
  147. <form action="./send_message" method="post">
  148. <fieldset>
  149. <legend>聊天室 - {roomid}</legend>
  150. <iframe src="./log?id={roomid}" frameborder="0">加载中……</iframe>
  151. <br>
  152. <label for="messageInput">{nickname}说:</label>
  153. <input type="text" id="messageInput" name="messageInput">
  154. <button type="submit">发送</button>
  155. <a href=".">退出</a>
  156. </fieldset>
  157. <input type="text" id="nickname" name="nickname" value="{nickname}" style="display: none;">
  158. <input type="text" id="roomid" name="roomid" value="{roomid}" style="display: none;">
  159. </form>
  160. </div>
  161. </body>
  162. </html>
  163. '''.encode('utf-8')
  164. def generate_chat_log_html(self, roomid):
  165. messages = self.rooms.get(roomid, [])
  166. chat_log = '<br>'.join(messages) if messages else '<p style="color:#ccc">无聊天记录</p>'
  167. return f'''
  168. <!DOCTYPE html>
  169. <html lang="zh-Hans">
  170. <head>
  171. <meta charset="UTF-8">
  172. <title>聊天记录 - {roomid}</title>
  173. <meta name="viewport" content="width=192, initial-scale=1.0">
  174. <meta http-equiv="refresh" content="60">
  175. </head>
  176. <body style="font-family: Arial, sans-serif;">
  177. <span>
  178. {chat_log}
  179. </span>
  180. </body>
  181. </html>
  182. '''.encode('utf-8')
  183. def send_file(self, filename):
  184. try:
  185. if filename.endswith('.css'):
  186. self.send_response(200)
  187. self.send_header('Content-type', 'text/css; charset=UTF-8')
  188. else:
  189. self.send_response(200)
  190. self.send_header('Content-type', 'text/html; charset=UTF-8')
  191. self.end_headers()
  192. with open(filename, 'rb') as file:
  193. self.wfile.write(file.read())
  194. except FileNotFoundError:
  195. logging.error(f"File not found: {filename}")
  196. self.send_error(404)
  197. def main():
  198. parser = argparse.ArgumentParser(description='聊天室')
  199. parser.add_argument('--port', type=int, default=8000, help='Port to listen on.')
  200. args = parser.parse_args()
  201. server_address = ('0.0.0.0', args.port)
  202. httpd = socketserver.TCPServer(server_address, ChatServer)
  203. httpd.allow_reuse_address = True
  204. print(f'Starting server at http://127.0.0.1:{args.port} ...')
  205. httpd.serve_forever()
  206. if __name__ == '__main__':
  207. main()