Alvin3y1 commited on
Commit
5f7f889
·
verified ·
1 Parent(s): 07129ba

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -0
app.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uvicorn
2
+ from fastapi import FastAPI, WebSocket, WebSocketDisconnect
3
+ from fastapi.responses import HTMLResponse
4
+ from typing import List
5
+
6
+ app = FastAPI()
7
+
8
+ # --- Connection Manager ---
9
+ class ConnectionManager:
10
+ def __init__(self):
11
+ # Store active connections
12
+ self.macos_connections: List[WebSocket] = []
13
+ self.linux_connections: List[WebSocket] = []
14
+
15
+ async def connect_macos(self, websocket: WebSocket):
16
+ await websocket.accept()
17
+ self.macos_connections.append(websocket)
18
+ print(f"Client connected to macOS. Total: {len(self.macos_connections)}")
19
+
20
+ async def connect_linux(self, websocket: WebSocket):
21
+ await websocket.accept()
22
+ self.linux_connections.append(websocket)
23
+ print(f"Client connected to Linux. Total: {len(self.linux_connections)}")
24
+
25
+ def disconnect_macos(self, websocket: WebSocket):
26
+ if websocket in self.macos_connections:
27
+ self.macos_connections.remove(websocket)
28
+ print("Client disconnected from macOS")
29
+
30
+ def disconnect_linux(self, websocket: WebSocket):
31
+ if websocket in self.linux_connections:
32
+ self.linux_connections.remove(websocket)
33
+ print("Client disconnected from Linux")
34
+
35
+ async def forward_to_linux_clients(self, message: str):
36
+ # Forward message to all Linux clients
37
+ # Iterate over a copy of the list to avoid issues if a client disconnects mid-loop
38
+ for connection in self.linux_connections[:]:
39
+ try:
40
+ await connection.send_text(message)
41
+ except Exception as e:
42
+ print(f"Error sending to linux client: {e}")
43
+
44
+ async def forward_to_macos_clients(self, message: str):
45
+ # Forward message to all macOS clients
46
+ for connection in self.macos_connections[:]:
47
+ try:
48
+ await connection.send_text(message)
49
+ except Exception as e:
50
+ print(f"Error sending to macos client: {e}")
51
+
52
+ manager = ConnectionManager()
53
+
54
+ # --- WebSocket Endpoints ---
55
+
56
+ @app.websocket("/macos")
57
+ async def websocket_macos(websocket: WebSocket):
58
+ await manager.connect_macos(websocket)
59
+ try:
60
+ while True:
61
+ # Wait for data from macOS client
62
+ data = await websocket.receive_text()
63
+ print(f"Received from macOS: {data}")
64
+ # Forward exact same thing to Linux clients
65
+ await manager.forward_to_linux_clients(data)
66
+ except WebSocketDisconnect:
67
+ manager.disconnect_macos(websocket)
68
+ except Exception as e:
69
+ print(f"Error in macOS socket: {e}")
70
+ manager.disconnect_macos(websocket)
71
+
72
+ @app.websocket("/linux")
73
+ async def websocket_linux(websocket: WebSocket):
74
+ await manager.connect_linux(websocket)
75
+ try:
76
+ while True:
77
+ # Wait for data from Linux client
78
+ data = await websocket.receive_text()
79
+ print(f"Received from Linux: {data}")
80
+ # Forward exact same thing to macOS clients
81
+ await manager.forward_to_macos_clients(data)
82
+ except WebSocketDisconnect:
83
+ manager.disconnect_linux(websocket)
84
+ except Exception as e:
85
+ print(f"Error in Linux socket: {e}")
86
+ manager.disconnect_linux(websocket)
87
+
88
+ # --- Simple UI for testing (Optional) ---
89
+ @app.get("/")
90
+ async def get():
91
+ return HTMLResponse("""
92
+ <!DOCTYPE html>
93
+ <html>
94
+ <head>
95
+ <title>Bridge Tester</title>
96
+ </head>
97
+ <body>
98
+ <h1>OS Bridge Tester</h1>
99
+ <div style="display:flex; gap: 20px;">
100
+ <div style="border:1px solid #ccc; padding:10px;">
101
+ <h2>Pretend to be macOS</h2>
102
+ <button onclick="connect('macos')">Connect to /macos</button>
103
+ <input type="text" id="msgMac" placeholder="Message to Linux" />
104
+ <button onclick="send('macos')">Send</button>
105
+ <ul id="logMac"></ul>
106
+ </div>
107
+
108
+ <div style="border:1px solid #ccc; padding:10px;">
109
+ <h2>Pretend to be Linux</h2>
110
+ <button onclick="connect('linux')">Connect to /linux</button>
111
+ <input type="text" id="msgLin" placeholder="Message to macOS" />
112
+ <button onclick="send('linux')">Send</button>
113
+ <ul id="logLin"></ul>
114
+ </div>
115
+ </div>
116
+
117
+ <script>
118
+ var wsMac = null;
119
+ var wsLin = null;
120
+
121
+ function connect(os) {
122
+ var ws = new WebSocket(((window.location.protocol === "https:") ? "wss://" : "ws://") + window.location.host + "/" + os);
123
+
124
+ ws.onopen = function() { appendLog(os, "Connected!"); };
125
+ ws.onmessage = function(event) { appendLog(os, "Received: " + event.data); };
126
+
127
+ if(os === 'macos') wsMac = ws;
128
+ else wsLin = ws;
129
+ }
130
+
131
+ function send(os) {
132
+ var input = document.getElementById(os === 'macos' ? 'msgMac' : 'msgLin');
133
+ var ws = os === 'macos' ? wsMac : wsLin;
134
+ if(ws) ws.send(input.value);
135
+ input.value = '';
136
+ }
137
+
138
+ function appendLog(os, msg) {
139
+ var ul = document.getElementById(os === 'macos' ? 'logMac' : 'logLin');
140
+ var li = document.createElement("li");
141
+ li.appendChild(document.createTextNode(msg));
142
+ ul.appendChild(li);
143
+ }
144
+ </script>
145
+ </body>
146
+ </html>
147
+ """)
148
+
149
+ # Entry point for Hugging Face (Starts on port 7860)
150
+ if __name__ == "__main__":
151
+ uvicorn.run(app, host="0.0.0.0", port=7860)