-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
243 lines (215 loc) · 9.47 KB
/
Copy pathserver.py
File metadata and controls
243 lines (215 loc) · 9.47 KB
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
import http.server
import socketserver
import ssl
import os
import json
import socket
import threading
import time
import sys
import argparse
# ─── Shared state ────────────────────────────────────────────────────────────
class Store:
def __init__(self):
self.lock = threading.Lock()
self.events = []
self._reset()
def _reset(self):
self.offer = None
self.answer = None
self.cam_ice = []
self.obs_ice = []
self.add_event("Signaling state initialized.")
def add_event(self, msg):
timestamp = time.strftime("%H:%M:%S")
formatted = f"[{timestamp}] {msg}"
self.events.append(formatted)
if len(self.events) > 30:
self.events.pop(0)
store = Store()
def get_local_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
except Exception:
return "127.0.0.1"
LOCAL_IP = get_local_ip()
# Ports configured dynamically via arguments
HTTPS_PORT = 8000
HTTP_PORT = 8001
# ─── Request handler ─────────────────────────────────────────────────────────
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=os.path.join(os.path.dirname(__file__), "public"), **kwargs)
# Silence request logs
def log_message(self, format, *args):
pass
def _cors(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._cors()
self.end_headers()
def do_GET(self):
routes = {"/": "/index.html", "/camera": "/camera.html", "/obs": "/obs.html"}
self.path = routes.get(self.path, self.path)
if self.path.startswith("/api/"):
self._api_get()
else:
super().do_GET()
def do_POST(self):
if self.path.startswith("/api/"):
length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(length)
try:
data = json.loads(body) if body else {}
except Exception:
self.send_error(400, "Bad JSON")
return
self._api_post(data)
else:
self.send_error(404)
# ── GET endpoints ──────────────────────────────────────────────────────
def _api_get(self):
p = self.path.split("?")[0]
with store.lock:
if p == "/api/offer":
resp = {"offer": store.offer}
elif p == "/api/answer":
resp = {"answer": store.answer}
elif p == "/api/cam-ice":
resp = {"candidates": store.cam_ice}
elif p == "/api/obs-ice":
resp = {"candidates": store.obs_ice}
elif p == "/api/logs":
resp = {"logs": store.events}
elif p == "/api/config":
resp = {
"local_ip": LOCAL_IP,
"https_port": HTTPS_PORT,
"http_port": HTTP_PORT,
}
else:
self.send_error(404)
return
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Cache-Control", "no-store")
self._cors()
self.end_headers()
self.wfile.write(json.dumps(resp).encode())
# ── POST endpoints ─────────────────────────────────────────────────────
def _api_post(self, data):
p = self.path.split("?")[0]
with store.lock:
if p == "/api/offer":
store.offer = data.get("offer")
store.answer = None
store.obs_ice = []
store.add_event("Offer received from phone camera.")
print(f"[signal] offer received from phone")
elif p == "/api/answer":
store.answer = data.get("answer")
store.add_event("Answer received from OBS. Establishing WebRTC channel.")
print(f"[signal] answer received from OBS")
elif p == "/api/cam-ice":
c = data.get("candidate")
if c:
store.cam_ice.append(c)
# Limit logging noise
if len(store.cam_ice) == 1:
store.add_event("Receiving camera connection candidates...")
elif p == "/api/obs-ice":
c = data.get("candidate")
if c:
store.obs_ice.append(c)
if len(store.obs_ice) == 1:
store.add_event("Receiving OBS connection candidates...")
elif p == "/api/reset":
store._reset()
print("[signal] session reset")
else:
self.send_error(404)
return
self.send_response(200)
self.send_header("Content-Type", "application/json")
self._cors()
self.end_headers()
self.wfile.write(b'{"ok":true}')
class ThreadedServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
daemon_threads = True
# ─── Main ─────────────────────────────────────────────────────────────────────
def main():
global HTTPS_PORT, HTTP_PORT
parser = argparse.ArgumentParser(description="Phone to OBS WebRTC Streamer Server")
parser.add_argument("--https-port", type=int, default=8000, help="HTTPS port for phone camera (default: 8000)")
parser.add_argument("--http-port", type=int, default=8001, help="HTTP port for OBS / PC Dashboard (default: 8001)")
args = parser.parse_args()
HTTPS_PORT = args.https_port
HTTP_PORT = args.http_port
# ── HTTPS server (for phone camera) ──────────────────────────────────
https_ok = False
if os.path.exists("cert.pem") and os.path.exists("key.pem"):
try:
https_srv = ThreadedServer(("", HTTPS_PORT), Handler)
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain("cert.pem", "key.pem")
https_srv.socket = ctx.wrap_socket(https_srv.socket, server_side=True)
t1 = threading.Thread(target=https_srv.serve_forever, daemon=True)
t1.start()
https_ok = True
store.add_event(f"HTTPS Server running on port {HTTPS_PORT}.")
except OSError as e:
print(f"[FATAL] Port {HTTPS_PORT} is already in use by another application.")
print("Please close that application or run this server with a different port:")
print(f"python server.py --https-port <other-port>")
sys.exit(1)
except Exception as e:
print(f"[server] HTTPS startup failed: {e}")
else:
print("[server] No cert.pem/key.pem found - HTTPS disabled")
store.add_event("HTTPS disabled (Missing SSL files cert.pem/key.pem).")
# ── HTTP server (for OBS + dashboard) ────────────────────────────────
try:
http_srv = ThreadedServer(("", HTTP_PORT), Handler)
t2 = threading.Thread(target=http_srv.serve_forever, daemon=True)
t2.start()
store.add_event(f"HTTP Server running on port {HTTP_PORT}.")
except OSError as e:
print(f"[FATAL] Port {HTTP_PORT} is already in use by another application.")
print("Please close that application or run this server with a different port:")
print(f"python server.py --http-port <other-port>")
sys.exit(1)
# ── Print links ───────────────────────────────────────────────────────
print()
print("=" * 55)
print(" PHONE -> OBS CAMERA | READY")
print("=" * 55)
print(f" Dashboard (PC browser) : http://localhost:{HTTP_PORT}")
if https_ok:
print(f" Phone camera link : https://{LOCAL_IP}:{HTTPS_PORT}/camera")
print(f" OBS Browser Source : http://localhost:{HTTP_PORT}/obs")
else:
print(f" Phone camera link : http://{LOCAL_IP}:{HTTP_PORT}/camera")
print(f" OBS Browser Source : http://localhost:{HTTP_PORT}/obs")
print()
print(" ⚠ No SSL certificate - phone camera may not work.")
print(" Run generate_cert.py first, then restart.")
print("=" * 55)
print()
# Keep alive
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\n[server] shutting down...")
http_srv.shutdown()
if https_ok:
https_srv.shutdown()
if __name__ == "__main__":
main()