-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver-cli.py
More file actions
300 lines (265 loc) · 9.18 KB
/
server-cli.py
File metadata and controls
300 lines (265 loc) · 9.18 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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Command-line server launcher for Shift Handover Log
Simple terminal-only version without GUI
"""
import os
import sys
import json
import secrets
import subprocess
import signal
import socket
import time
from pathlib import Path
# Configuration
CONFIG_FILE = "server_config.json"
DEFAULT_CONFIG_FILE = "server_default_config.json"
DEFAULT_PORT = 8500
# Detect if running from dist folder (executable)
# When running as PyInstaller exe: use executable's directory (cwd can be wrong)
if getattr(sys, 'frozen', False):
BASE_DIR = Path(sys.executable).parent
else:
BASE_DIR = Path.cwd()
current_path = BASE_DIR
# Check if we're running from inside dist folder (executable scenario)
if (current_path / "server" / "index.js").exists():
if (current_path / "HandoverServer.exe").exists() or current_path.name == "dist":
BASE_DIR = current_path
NODEJS_DIR = BASE_DIR / "nodejs"
SERVER_DIR = BASE_DIR / "server"
CLIENT_BUILD_DIR = BASE_DIR / "client" / "build"
DATA_DIR = BASE_DIR / "data"
else:
BASE_DIR = current_path
NODEJS_DIR = BASE_DIR / "nodejs"
SERVER_DIR = BASE_DIR / "server"
CLIENT_BUILD_DIR = BASE_DIR / "client" / "build"
DATA_DIR = BASE_DIR / "data"
elif (current_path / "dist" / "server" / "index.js").exists():
BASE_DIR = current_path / "dist"
NODEJS_DIR = BASE_DIR / "nodejs"
SERVER_DIR = BASE_DIR / "server"
CLIENT_BUILD_DIR = BASE_DIR / "client" / "build"
DATA_DIR = BASE_DIR / "data"
else:
BASE_DIR = current_path
NODEJS_DIR = BASE_DIR / "nodejs"
SERVER_DIR = BASE_DIR / "server"
CLIENT_BUILD_DIR = BASE_DIR / "client" / "build"
DATA_DIR = BASE_DIR / "data"
NODEJS_EXE = NODEJS_DIR / "node.exe"
def check_port_available(port):
"""Check if port is available"""
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('localhost', port))
return True
except OSError:
return False
def load_default_port():
"""Load default port from default config file"""
port = DEFAULT_PORT
if os.path.exists(DEFAULT_CONFIG_FILE):
try:
with open(DEFAULT_CONFIG_FILE, 'r', encoding='utf-8') as f:
config = json.load(f)
port = config.get('default_port', DEFAULT_PORT)
except Exception:
pass
return port
def load_config():
"""Load saved configuration, returns (port, jwt_secret)"""
port = load_default_port()
jwt_secret = None
config_path = BASE_DIR / CONFIG_FILE
if config_path.exists():
try:
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
port = config.get('port', port)
jwt_secret = config.get('jwt_secret')
except Exception:
pass
if not jwt_secret:
jwt_secret = secrets.token_hex(32)
return port, jwt_secret
def save_config(port, jwt_secret=None):
"""Save configuration"""
try:
config_path = BASE_DIR / CONFIG_FILE
config = {'port': port}
if config_path.exists():
try:
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
config['port'] = port
if jwt_secret:
config['jwt_secret'] = jwt_secret
except Exception:
config['jwt_secret'] = jwt_secret or secrets.token_hex(32)
else:
config['jwt_secret'] = jwt_secret or secrets.token_hex(32)
with open(config_path, 'w', encoding='utf-8') as f:
json.dump(config, f, indent=2)
except Exception:
pass
def check_nodejs():
"""Check if Node.js is available"""
if not NODEJS_EXE.exists():
print(f"ERROR: Node.js not found at {NODEJS_EXE}")
print("\nPlease extract portable Node.js to the 'nodejs/' folder")
print("See README_SERVER.md for instructions.")
return False
return True
def check_directories():
"""Check if necessary directories exist"""
errors = []
if not SERVER_DIR.exists():
errors.append(f"Folder 'server' not found")
if not CLIENT_BUILD_DIR.exists():
errors.append(f"Folder 'client/build' not found (frontend not compiled)")
if not DATA_DIR.exists():
DATA_DIR.mkdir(parents=True, exist_ok=True)
print(f"Created folder 'data'")
return errors
def main():
"""Main function"""
print("=" * 50)
print("Shift Handover Log - Command Line Server")
print("=" * 50)
print()
# Check Node.js
if not check_nodejs():
sys.exit(1)
print(f"✓ Node.js found: {NODEJS_EXE}")
# Check directories
errors = check_directories()
if errors:
print("\nERROR: Problems found:")
for error in errors:
print(f" - {error}")
sys.exit(1)
print("✓ All necessary folders found")
print()
# Get port
default_port = load_config()
port = default_port
if len(sys.argv) > 1:
# Port provided as command-line argument
try:
port = int(sys.argv[1])
if port < 1 or port > 65535:
raise ValueError("Invalid port")
except ValueError:
print(f"ERROR: Invalid port '{sys.argv[1]}'. Must be between 1 and 65535.")
sys.exit(1)
else:
# Prompt user with 10-second timeout
print(f"Enter port number [{default_port}] (10 seconds timeout): ", end='', flush=True)
# Use threading for timeout (cross-platform)
import threading
user_input = ''
input_complete = threading.Event()
input_received = False
def get_input():
nonlocal user_input, input_received
try:
result = sys.stdin.readline()
if result:
user_input = result.strip()
input_received = True
except:
pass
finally:
input_complete.set()
# Start input thread
input_thread = threading.Thread(target=get_input, daemon=True)
input_thread.start()
# Wait for input or timeout (10 seconds)
input_complete.wait(timeout=10.0)
if not input_received or not user_input:
# Timeout reached or empty input
print(f"\nTimeout reached. Using default port {default_port}.")
port = default_port
else:
# User provided input
try:
port = int(user_input)
if port < 1 or port > 65535:
raise ValueError("Invalid port")
except ValueError:
print(f"ERROR: Invalid port. Using default {default_port}.")
port = default_port
# Check if port is available
if not check_port_available(port):
print(f"ERROR: Port {port} is already in use.")
print("Please choose another port or stop the application using it.")
sys.exit(1)
save_config(port, jwt_secret)
# Configure environment
env = os.environ.copy()
env['NODE_ENV'] = 'production'
env['PORT'] = str(port)
env['FRONTEND_URL'] = f'http://localhost:{port}'
env['JWT_SECRET'] = jwt_secret
# Server path
server_path = SERVER_DIR / "index.js"
if not server_path.exists():
print(f"ERROR: Server file not found: {server_path}")
sys.exit(1)
print()
print("=" * 50)
print(f"Starting server on port {port}...")
print("=" * 50)
print()
print(f"Server will be available at: http://localhost:{port}")
print(f"API endpoint: http://localhost:{port}/api")
print()
print("Press Ctrl+C to stop the server")
print("=" * 50)
print()
# Start Node.js process
try:
node_path = str(NODEJS_EXE)
server_script = str(server_path)
working_dir = str(BASE_DIR)
process = subprocess.Popen(
[node_path, server_script],
cwd=working_dir,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
universal_newlines=True
)
# Handle Ctrl+C
def signal_handler(sig, frame):
print("\n\nStopping server...")
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
print("Server stopped.")
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# Read and print output
try:
for line in iter(process.stdout.readline, ''):
if line:
print(f"[Server] {line.rstrip()}")
process.stdout.close()
process.wait()
except KeyboardInterrupt:
signal_handler(None, None)
except Exception as e:
print(f"ERROR: Failed to start server: {e}")
sys.exit(1)
if __name__ == "__main__":
main()