File size: 11,847 Bytes
3c55128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6029109
 
 
3c55128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
886ecb9
3c55128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a7290c
3c55128
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#!/usr/bin/env python3

from http.server import HTTPServer, BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import sys
import os
import random
import threading
import time
from datetime import datetime, timedelta

sessions = {}
clients = {}

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
    def _add_cors_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')

    def do_OPTIONS(self):
        self.send_response(200)
        self._add_cors_headers()
        self.end_headers()

    def do_GET(self):
        if self.path == '/':
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self._add_cors_headers()
            self.end_headers()
            response = {'message': 'API Server is running!', 'status': 'ok'}
            self.wfile.write(json.dumps(response).encode())
        elif self.path == '/health':
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self._add_cors_headers()
            self.end_headers()
            response = {'status': 'healthy', 'active_sessions': len(sessions)}
            self.wfile.write(json.dumps(response).encode())
        elif self.path.startswith('/api/session'):
            self.handle_session_get()
        elif self.path.startswith('/api/events/'):
            self.handle_sse_connection()
        else:
            self.send_response(404)
            self.send_header('Content-type', 'application/json')
            self._add_cors_headers()
            self.end_headers()
            response = {'error': 'Endpoint not found'}
            self.wfile.write(json.dumps(response).encode())

    def do_POST(self):
        if self.path == '/api/session':
            self.handle_session_post()
        elif self.path == '/api/message':
            self.handle_message_post()
        elif self.path.startswith('/api/session/'):
            pass
        else:
            content_length = int(self.headers['Content-Length']) if self.headers.get('Content-Length') else 0
            post_data = self.rfile.read(content_length) if content_length > 0 else b''

            try:
                data = json.loads(post_data.decode()) if post_data else {}
            except json.JSONDecodeError:
                self.send_response(400)
                self.send_header('Content-type', 'application/json')
                self.end_headers()
                response = {'error': 'Invalid JSON'}
                self.wfile.write(json.dumps(response).encode())
                return

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self._add_cors_headers()
            self.end_headers()
            response = {'message': 'Data received', 'data': data}
            self.wfile.write(json.dumps(response).encode())

    def handle_session_get(self):
        path_parts = self.path.split('/')
        if len(path_parts) >= 4 and path_parts[3]:
            session_code = path_parts[3].upper()
            if session_code in sessions:
                self.send_response(200)
                self.send_header('Content-type', 'application/json')
                self._add_cors_headers()
                self.end_headers()
                response = {'exists': True, 'session_code': session_code}
                self.wfile.write(json.dumps(response).encode())
            else:
                self.send_response(404)
                self.send_header('Content-type', 'application/json')
                self._add_cors_headers()
                self.end_headers()
                response = {'exists': False, 'session_code': session_code}
                self.wfile.write(json.dumps(response).encode())
        else:
            self.send_response(400)
            self.send_header('Content-type', 'application/json')
            self._add_cors_headers()
            self.end_headers()
            response = {'error': 'Missing session code'}
            self.wfile.write(json.dumps(response).encode())

    def handle_session_post(self):
        content_length = int(self.headers['Content-Length']) if self.headers.get('Content-Length') else 0
        post_data = self.rfile.read(content_length) if content_length > 0 else b''

        try:
            data = json.loads(post_data.decode()) if post_data else {}
        except json.JSONDecodeError:
            self.send_response(400)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            response = {'error': 'Invalid JSON'}
            self.wfile.write(json.dumps(response).encode())
            return
        session_code = None
        attempts = 0
        while session_code is None and attempts < 100:
            code = ''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=4))
            if code not in sessions:
                session_code = code
            attempts += 1

        if session_code is None:
            self.send_response(500)
            self.send_header('Content-type', 'application/json')
            self._add_cors_headers()
            self.end_headers()
            response = {'error': 'Could not generate unique session code'}
            self.wfile.write(json.dumps(response).encode())
            return
        sessions[session_code] = {
            'clients': [],
            'created_at': datetime.now(),
            'host': data.get('client_id', 'unknown')
        }

        self.send_response(201)
        self.send_header('Content-type', 'application/json')
        self._add_cors_headers()
        self.end_headers()
        response = {'session_code': session_code, 'created': True}
        self.wfile.write(json.dumps(response).encode())

    def handle_sse_connection(self):
        path_parts = self.path.split('/')
        if len(path_parts) >= 5 and path_parts[3] and path_parts[4]:
            session_code = path_parts[3].upper()
            client_id = path_parts[4]

            if session_code in sessions and client_id:
                if client_id not in sessions[session_code]['clients']:
                    sessions[session_code]['clients'].append(client_id)

                clients[client_id] = {
                    'session': session_code,
                    'connection': self
                }

                self.send_response(200)
                self.send_header('Content-Type', 'text/event-stream')
                self.send_header('Cache-Control', 'no-cache')
                self.send_header('Connection', 'keep-alive')
                self._add_cors_headers()
                self.end_headers()

                try:
                    while True:
                        time.sleep(30)
                        self.wfile.write(b': keepalive\n\n')
                        self.wfile.flush()
                except:
                    if client_id in clients:
                        if client_id in sessions[session_code]['clients']:
                            sessions[session_code]['clients'].remove(client_id)
                        del clients[client_id]
            else:
                self.send_response(404)
                self.send_header('Content-type', 'application/json')
                self._add_cors_headers()
                self.end_headers()
                response = {'error': 'Session not found or missing client ID'}
                self.wfile.write(json.dumps(response).encode())
        else:
            self.send_response(400)
            self.send_header('Content-type', 'application/json')
            self._add_cors_headers()
            self.end_headers()
            response = {'error': 'Missing session code or client ID'}
            self.wfile.write(json.dumps(response).encode())

    def handle_message_post(self):
        content_length = int(self.headers['Content-Length']) if self.headers.get('Content-Length') else 0
        post_data = self.rfile.read(content_length) if content_length > 0 else b''

        try:
            data = json.loads(post_data.decode())
        except json.JSONDecodeError:
            self.send_response(400)
            self.send_header('Content-type', 'application/json')
            self._add_cors_headers()
            self.end_headers()
            response = {'error': 'Invalid JSON'}
            self.wfile.write(json.dumps(response).encode())
            return

        client_id = data.get('client_id')
        session_code = data.get('session_code')

        if session_code and session_code in sessions:
            broadcast_message = {
                'type': 'message',
                'client_id': client_id,
                'username': data.get('username', f'User-{client_id[:8]}'),
                'content': data['content'],
                'timestamp': datetime.now().isoformat(),
                'session_code': session_code
            }

            if 'replyTo' in data:
                broadcast_message['replyTo'] = data['replyTo']

            for cid in sessions[session_code]['clients']:
                if cid in clients and cid != client_id:
                    try:
                        conn = clients[cid]['connection']
                        event_data = f"data: {json.dumps(broadcast_message)}\n\n"
                        conn.wfile.write(event_data.encode())
                        conn.wfile.flush()
                    except:
                        pass

            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self._add_cors_headers()
            self.end_headers()
            response = {'sent': True}
            self.wfile.write(json.dumps(response).encode())
        else:
            self.send_response(404)
            self.send_header('Content-type', 'application/json')
            self._add_cors_headers()
            self.end_headers()
            response = {'error': 'Session not found'}
            self.wfile.write(json.dumps(response).encode())

    def log_message(self, format, *args):
        pass


def cleanup_sessions():
    current_time = datetime.now()
    expired_sessions = []

    for session_code, session_data in sessions.items():
        if current_time - session_data['created_at'] > timedelta(minutes=15):
            expired_sessions.append(session_code)

    for session_code in expired_sessions:
        if session_code in sessions:
            for client_id in sessions[session_code]['clients']:
                if client_id in clients:
                    try:
                        conn = clients[client_id]['connection']
                        event_data = f"data: {json.dumps({'type': 'session_expired', 'session_code': session_code})}\n\n"
                        conn.wfile.write(event_data.encode())
                        conn.wfile.flush()
                    except:
                        pass
        del sessions[session_code]

    if expired_sessions:
        print(f"Cleaned up {len(expired_sessions)} expired sessions")

def run_server(port=8000, host='0.0.0.0'):
    server_address = (host, port)
    httpd = ThreadingHTTPServer(server_address, SimpleHTTPRequestHandler)
    print(f"Server running on http://{host}:{port}")
    print("Press Ctrl+C to stop")

    def cleanup_timer():
        while True:
            time.sleep(300)
            cleanup_sessions()

    cleanup_thread = threading.Thread(target=cleanup_timer, daemon=True)
    cleanup_thread.start()

    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\nServer stopped")
        httpd.server_close()

if __name__ == '__main__':
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 7860
    run_server(port)