-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathserver.py
More file actions
2098 lines (1728 loc) · 82.6 KB
/
server.py
File metadata and controls
2098 lines (1728 loc) · 82.6 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
PrinterOne - Unified Server and GUI Application
A comprehensive TCP print server with integrated GUI management and test client functionality
"""
# Critical startup logging - Log everything from the very beginning
import os
import sys
import time
import json
import socket
import threading
import subprocess
import signal
import tempfile
import logging
import glob
import psutil
import winreg
import traceback
from datetime import datetime, timedelta
# Setup early logging to capture startup issues
def setup_early_logging():
"""Setup logging as early as possible to capture startup issues"""
try:
# Create logs directory if it doesn't exist - use user temp if permission denied
logs_dir = "logs"
try:
if not os.path.exists(logs_dir):
os.makedirs(logs_dir)
except PermissionError:
# Fallback to user temp directory if permission denied
import tempfile
logs_dir = os.path.join(tempfile.gettempdir(), "PrinterOne", "logs")
if not os.path.exists(logs_dir):
os.makedirs(logs_dir, exist_ok=True)
# Generate startup log filename
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
startup_log_filename = f"{timestamp}_startup.log"
startup_log_path = os.path.join(logs_dir, startup_log_filename)
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(startup_log_path, encoding='utf-8'),
logging.StreamHandler()
]
)
logger = logging.getLogger('startup')
logger.info("=== PrinterOne Startup Log ===")
logger.info(f"Python version: {sys.version}")
logger.info(f"Platform: {sys.platform}")
logger.info(f"Current working directory: {os.getcwd()}")
logger.info(f"Script path: {os.path.abspath(__file__)}")
logger.info(f"Command line arguments: {sys.argv}")
logger.info(f"Environment variables: USERPROFILE={os.environ.get('USERPROFILE', 'NOT_SET')}")
return logger
except Exception as e:
print(f"CRITICAL: Failed to setup early logging: {e}")
print(f"Exception type: {type(e).__name__}")
print(f"Traceback: {traceback.format_exc()}")
return None
# Initialize early logging
startup_logger = setup_early_logging()
try:
if startup_logger:
startup_logger.info("Starting import phase...")
# Import GUI modules
try:
if startup_logger:
startup_logger.info("Importing GUI modules...")
import tkinter as tk
from tkinter import ttk
if startup_logger:
startup_logger.info("GUI modules imported successfully")
except ImportError as e:
if startup_logger:
startup_logger.error(f"Failed to import GUI modules: {e}")
raise
# Import Windows-specific modules
try:
if startup_logger:
startup_logger.info("Importing Windows print modules...")
import win32print
if startup_logger:
startup_logger.info("Windows print modules imported successfully")
except ImportError as e:
if startup_logger:
startup_logger.error(f"Failed to import Windows modules: {e}")
raise
# Import PDF generation
try:
if startup_logger:
startup_logger.info("Importing PDF modules...")
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
if startup_logger:
startup_logger.info("PDF modules imported successfully")
except ImportError as e:
if startup_logger:
startup_logger.error(f"Failed to import PDF modules: {e}")
raise
except Exception as e:
error_msg = f"CRITICAL: Import phase failed: {e}"
if startup_logger:
startup_logger.critical(error_msg)
startup_logger.critical(f"Exception type: {type(e).__name__}")
startup_logger.critical(f"Traceback: {traceback.format_exc()}")
else:
print(error_msg)
print(f"Exception type: {type(e).__name__}")
print(f"Traceback: {traceback.format_exc()}")
sys.exit(1)
# System tray imports (optional)
try:
import pystray
from PIL import Image, ImageTk
TRAY_AVAILABLE = True
except ImportError:
TRAY_AVAILABLE = False
print("pystray not available, system tray disabled")
# Global variables
SERVER_RUNNING = True
AUTO_START_MODE = False
class PrinterOneServer:
"""PrinterOne TCP Server"""
def __init__(self, log_callback=None):
try:
if startup_logger:
startup_logger.info("Initializing PrinterOneServer...")
self.config = self.load_config()
if startup_logger:
startup_logger.info(f"Configuration loaded: {self.config}")
self.server_socket = None
self.server_thread = None
self.running = False
self.log_callback = log_callback # Callback function for logging to GUI
if startup_logger:
startup_logger.info("PrinterOneServer initialized successfully")
except Exception as e:
error_msg = f"Failed to initialize PrinterOneServer: {e}"
if startup_logger:
startup_logger.critical(error_msg)
startup_logger.critical(f"Traceback: {traceback.format_exc()}")
raise
def log(self, message):
"""Log message to console and GUI if callback is set"""
print(message) # Always print to console
if self.log_callback:
# Remove the timestamp and brackets from message for GUI (GUI adds its own)
clean_message = message
if message.startswith("[") and "]" in message:
# Extract message after first "]"
bracket_end = message.find("]")
if bracket_end != -1:
clean_message = message[bracket_end + 1:].strip()
self.log_callback(clean_message)
def load_config(self):
"""Load configuration from config.json"""
default_config = {
"printer_name": "",
"port": 9100,
"use_pdf_conversion": True,
"save_pdf_file": False,
"auto_start": False,
"service_name": "PrinterOne",
"service_description": "PrinterOne - Network print server for raw print data",
"manual": False,
"minimize_to_tray": True
}
# Try multiple config file locations
config_paths = [
'config.json', # Current directory first
os.path.join(os.path.expanduser('~'), 'PrinterOne', 'config.json'), # User home
os.path.join(os.environ.get('APPDATA', ''), 'PrinterOne', 'config.json'), # AppData
os.path.join(tempfile.gettempdir(), 'PrinterOne', 'config.json') # Temp directory
]
# Store the successful config path for saving
self.config_path = None
try:
for config_path in config_paths:
try:
config_path = os.path.abspath(config_path)
if startup_logger:
startup_logger.info(f"Trying to load configuration from: {config_path}")
if os.path.exists(config_path):
if startup_logger:
startup_logger.info(f"Config file exists at: {config_path}")
with open(config_path, 'r') as f:
config = json.load(f)
if startup_logger:
startup_logger.info(f"Config loaded from file: {config}")
# Merge with defaults
for key, value in default_config.items():
if key not in config:
config[key] = value
if startup_logger:
startup_logger.info(f"Final merged config: {config}")
self.config_path = config_path # Remember successful path
return config
except PermissionError:
if startup_logger:
startup_logger.warning(f"Permission denied accessing: {config_path}")
continue
except Exception as e:
if startup_logger:
startup_logger.warning(f"Error loading from {config_path}: {e}")
continue
# No config file found or accessible
if startup_logger:
startup_logger.info("No config.json found or accessible, using defaults")
except Exception as e:
error_msg = f"Error in config loading process: {e}"
if startup_logger:
startup_logger.error(error_msg)
startup_logger.error(f"Traceback: {traceback.format_exc()}")
self.log(f"[!] {error_msg}")
if startup_logger:
startup_logger.info(f"Using default config: {default_config}")
# Set a fallback config path for saving
if not self.config_path:
# Try to create a writable config directory
for base_path in [os.path.expanduser('~'), os.environ.get('APPDATA', ''), tempfile.gettempdir()]:
try:
config_dir = os.path.join(base_path, 'PrinterOne')
if not os.path.exists(config_dir):
os.makedirs(config_dir, exist_ok=True)
self.config_path = os.path.join(config_dir, 'config.json')
break
except:
continue
if not self.config_path:
self.config_path = os.path.join(tempfile.gettempdir(), 'PrinterOne_config.json')
return default_config
def save_config(self, printer_name=None, port=None, use_pdf_conversion=None, save_pdf_file=None):
"""Save configuration to config.json"""
try:
if printer_name is not None:
self.config["printer_name"] = printer_name
if port is not None:
self.config["port"] = port
if use_pdf_conversion is not None:
self.config["use_pdf_conversion"] = use_pdf_conversion
if save_pdf_file is not None:
self.config["save_pdf_file"] = save_pdf_file
self.config["manual"] = True
# Use the config path determined during load, or try fallback locations
config_paths_to_try = []
if hasattr(self, 'config_path') and self.config_path:
config_paths_to_try.append(self.config_path)
# Fallback locations in order of preference
config_paths_to_try.extend([
'config.json', # Current directory
os.path.join(os.path.expanduser('~'), 'PrinterOne', 'config.json'), # User home
os.path.join(os.environ.get('APPDATA', ''), 'PrinterOne', 'config.json'), # AppData
os.path.join(tempfile.gettempdir(), 'PrinterOne', 'config.json') # Temp directory
])
# Try to save to each location until one succeeds
for config_path in config_paths_to_try:
try:
# Ensure directory exists
config_dir = os.path.dirname(config_path)
if config_dir and not os.path.exists(config_dir):
os.makedirs(config_dir, exist_ok=True)
# Try to save
with open(config_path, 'w') as f:
json.dump(self.config, f, indent=4)
self.log(f"[SAVE] Configuration saved to {config_path}")
self.config_path = config_path # Remember successful path
return True
except PermissionError:
self.log(f"[WARN] Permission denied saving to {config_path}, trying next location...")
continue
except Exception as e:
self.log(f"[WARN] Error saving to {config_path}: {e}, trying next location...")
continue
# If all locations failed
self.log(f"[!] Failed to save configuration to any location")
return False
except Exception as e:
self.log(f"[!] Error in save_config: {e}")
return False
def list_printers(self):
"""List all available printers"""
try:
printers = []
for printer in win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL, None, 1):
printers.append(printer[2])
return printers
except Exception as e:
self.log(f"[!] Error listing printers: {e}")
return []
def convert_raw_to_pdf(self, raw_data, save_file=False):
"""Convert raw data to PDF for testing with PDF printers (test client only)"""
try:
temp_pdf = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf')
temp_pdf_path = temp_pdf.name
temp_pdf.close()
self.log(f"[INFO] Creating PDF at: {temp_pdf_path}")
c = canvas.Canvas(temp_pdf_path, pagesize=letter)
data_format = self.analyze_raw_data(raw_data)
# Add title
c.setFont("Helvetica-Bold", 16)
c.drawString(100, 750, "PrinterOne - Test Print Job")
# Add info
c.setFont("Helvetica", 12)
c.drawString(100, 720, f"Data length: {len(raw_data)} bytes")
c.drawString(100, 700, f"Data format: {data_format}")
c.drawString(100, 680, f"Received at: {time.strftime('%Y-%m-%d %H:%M:%S')}")
y_position = 640
# Try to extract and display readable text first
try:
text_content = self.extract_readable_text(raw_data)
if text_content and len(text_content.strip()) > 0:
c.setFont("Helvetica-Bold", 14)
c.drawString(100, y_position, "Content:")
y_position -= 30
# Display text content
c.setFont("Helvetica", 11)
lines = text_content.split('\n')
for line in lines:
if y_position < 80:
c.showPage() # New page
y_position = 750
# Wrap long lines
if len(line) > 80:
for i in range(0, len(line), 80):
chunk = line[i:i+80]
c.drawString(100, y_position, chunk)
y_position -= 15
if y_position < 80:
c.showPage()
y_position = 750
else:
c.drawString(100, y_position, line)
y_position -= 15
y_position -= 20
else:
# If no readable text, show hex and ASCII as before
self.add_hex_dump_to_pdf(c, raw_data, y_position)
except Exception as e:
self.log(f"[WARN] Error extracting text, using hex dump: {e}")
self.add_hex_dump_to_pdf(c, raw_data, y_position)
c.save()
# Read the PDF file
with open(temp_pdf_path, 'rb') as f:
pdf_data = f.read()
# Clean up or save file
if save_file:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
saved_path = f"raw_data_{timestamp}.pdf"
os.rename(temp_pdf_path, saved_path)
self.log(f"[SAVE] PDF saved as: {saved_path}")
else:
try:
os.unlink(temp_pdf_path)
except:
pass
return pdf_data
except Exception as e:
self.log(f"[!] PDF conversion error: {e}")
return None
def extract_readable_text(self, raw_data):
"""Extract readable text from raw data"""
try:
# Try UTF-8 first
try:
text = raw_data.decode('utf-8')
# Clean up control characters but keep printable ones
cleaned = ''.join(char if char.isprintable() or char in '\n\r\t' else ' ' for char in text)
return cleaned.strip()
except UnicodeDecodeError:
pass
# Try Windows-1252 (common in Windows printing)
try:
text = raw_data.decode('windows-1252', errors='ignore')
cleaned = ''.join(char if char.isprintable() or char in '\n\r\t' else ' ' for char in text)
return cleaned.strip()
except:
pass
# Try ASCII with error handling
try:
text = raw_data.decode('ascii', errors='ignore')
cleaned = ''.join(char if char.isprintable() or char in '\n\r\t' else ' ' for char in text)
return cleaned.strip()
except:
pass
return None
except Exception as e:
self.log(f"[WARN] Text extraction error: {e}")
return None
def add_hex_dump_to_pdf(self, canvas_obj, raw_data, start_y):
"""Add hex dump to PDF (fallback method)"""
try:
y_position = start_y
# Add hex dump section
canvas_obj.setFont("Helvetica-Bold", 12)
canvas_obj.drawString(100, y_position, "Raw Data (Hex):")
y_position -= 30
# Add raw data as hex (first 2000 bytes)
canvas_obj.setFont("Courier", 8)
hex_data = raw_data[:2000].hex()
# Split hex data into lines
for i in range(0, len(hex_data), 80):
if y_position < 50:
canvas_obj.showPage()
y_position = 750
line = hex_data[i:i+80]
formatted_line = ' '.join([line[j:j+2] for j in range(0, len(line), 2)])
canvas_obj.drawString(100, y_position, formatted_line)
y_position -= 12
# Add ASCII representation
y_position -= 20
if y_position < 100:
canvas_obj.showPage()
y_position = 750
canvas_obj.setFont("Helvetica-Bold", 12)
canvas_obj.drawString(100, y_position, "ASCII representation:")
y_position -= 20
canvas_obj.setFont("Courier", 8)
ascii_data = raw_data[:1000]
ascii_line = ''
for i, byte in enumerate(ascii_data):
if 32 <= byte <= 126:
ascii_line += chr(byte)
else:
ascii_line += '.'
if (i + 1) % 80 == 0:
if y_position < 50:
canvas_obj.showPage()
y_position = 750
canvas_obj.drawString(100, y_position, ascii_line)
y_position -= 12
ascii_line = ''
if ascii_line:
canvas_obj.drawString(100, y_position, ascii_line)
except Exception as e:
self.log(f"[WARN] Hex dump error: {e}")
def analyze_raw_data(self, data):
"""Analyze raw data to determine format"""
if len(data) == 0:
return "Empty data"
# Check for common printer command formats
if data.startswith(b'\x1b'):
return "ESC/P (Epson)"
elif data.startswith(b'\x1b%-12345X'):
return "PCL (HP)"
elif data.startswith(b'%!PS'):
return "PostScript"
elif data.startswith(b'\x02'):
return "ZPL (Zebra)"
elif b'PDF' in data[:100]:
return "PDF document"
elif b'Microsoft Office' in data or b'Word' in data or b'.docx' in data or b'.doc' in data:
return "Microsoft Office document"
elif b'%PDF' in data[:100]:
return "PDF format"
else:
# Try to detect if it contains printable text
try:
decoded = data.decode('utf-8', errors='ignore')
if len(decoded.strip()) > 0 and any(c.isprintable() and c not in '\r\n\t' for c in decoded[:200]):
return f"Text document ({len(data)} bytes)"
except:
pass
return f"Binary/Unknown format ({len(data)} bytes)"
def print_raw(self, data, printer_name):
"""Send raw data to printer"""
try:
self.log(f"[INFO] Opening printer: {printer_name}")
hPrinter = win32print.OpenPrinter(printer_name)
job_info = ("RAW Print Job", None, "RAW")
hJob = win32print.StartDocPrinter(hPrinter, 1, job_info)
win32print.StartPagePrinter(hPrinter)
win32print.WritePrinter(hPrinter, data)
win32print.EndPagePrinter(hPrinter)
win32print.EndDocPrinter(hPrinter)
win32print.ClosePrinter(hPrinter)
self.log(f"[OK] Successfully printed {len(data)} bytes.")
return True
except Exception as e:
self.log(f"[!] Print error: {e}")
return False
def handle_client(self, client_socket, address):
"""Handle a client connection"""
self.log(f"[CONN] Client connected: {address}")
try:
data = b""
while True:
chunk = client_socket.recv(4096)
if not chunk:
break
data += chunk
if data:
self.log(f"[DATA] Received {len(data)} bytes from {address}")
self.log(f"[INFO] Data format: {self.analyze_raw_data(data)}")
printer_name = self.config.get("printer_name", "")
if printer_name:
self.print_raw(data, printer_name)
else:
self.log(f"[!] No printer configured")
else:
self.log(f"[!] No data received from {address}")
except Exception as e:
self.log(f"[!] Error handling client {address}: {e}")
finally:
client_socket.close()
self.log(f"[CONN] Client disconnected: {address}")
def kill_process_on_port(self, port):
"""Kill any process using the specified port"""
try:
# Use psutil instead of netstat to avoid snmpapi.dll dependency
for conn in psutil.net_connections():
if conn.laddr.port == port and conn.status == psutil.CONN_LISTEN:
try:
process = psutil.Process(conn.pid)
process.terminate()
self.log(f"[KILL] Terminated process {conn.pid} ({process.name()}) using port {port}")
time.sleep(1)
# Force kill if still running
if process.is_running():
process.kill()
self.log(f"[KILL] Force killed process {conn.pid}")
except (psutil.NoSuchProcess, psutil.AccessDenied) as e:
self.log(f"[!] Failed to kill process {conn.pid}: {e}")
except Exception as e:
self.log(f"[!] Error killing process on port {port}: {e}")
def get_local_ip(self):
"""Get the actual local IP address of the machine"""
try:
# Method 1: Try to connect to a remote server to determine local IP
test_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# Connect to Google DNS (doesn't actually send data)
test_socket.connect(("8.8.8.8", 80))
local_ip = test_socket.getsockname()[0]
test_socket.close()
# Validate that it's not a loopback address or VirtualBox
if (not local_ip.startswith('127.') and
not local_ip.startswith('192.168.56.') and # VirtualBox Host-Only
not local_ip.startswith('169.254.')): # APIPA
return local_ip
except:
test_socket.close()
# Method 2: Use psutil to get network interfaces with better filtering
try:
import psutil
interfaces_with_gw = []
interfaces_without_gw = []
# Get default gateways to identify primary interfaces
gateways = psutil.net_if_stats()
for interface_name, interface_addresses in psutil.net_if_addrs().items():
# Skip known virtual interfaces
if any(skip in interface_name.lower() for skip in [
'virtualbox', 'vmware', 'vbox', 'hyper-v', 'loopback',
'bluetooth', 'isatap', 'teredo', 'tunnel'
]):
continue
for address in interface_addresses:
if address.family == socket.AF_INET:
ip = address.address
# Skip loopback, APIPA, and VirtualBox IPs
if (ip.startswith('127.') or
ip.startswith('169.254.') or
ip.startswith('192.168.56.')): # VirtualBox Host-Only
continue
# Check if this interface is up and running
try:
interface_stats = psutil.net_if_stats().get(interface_name)
if interface_stats and interface_stats.isup:
# Prefer Wi-Fi and Ethernet over other interfaces
if any(pref in interface_name.lower() for pref in ['wi-fi', 'wifi', 'ethernet', 'local area']):
interfaces_with_gw.append((ip, interface_name))
else:
interfaces_without_gw.append((ip, interface_name))
except:
pass
# Return the best interface
if interfaces_with_gw:
# Prefer Wi-Fi over Ethernet if both available
for ip, name in interfaces_with_gw:
if 'wi-fi' in name.lower() or 'wifi' in name.lower():
return ip
# Otherwise return first good interface
return interfaces_with_gw[0][0]
if interfaces_without_gw:
return interfaces_without_gw[0][0]
except Exception as e:
if startup_logger:
startup_logger.warning(f"Method 2 failed: {e}")
# Method 3: Fallback to hostname resolution
try:
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
if (not local_ip.startswith('127.') and
not local_ip.startswith('192.168.56.')):
return local_ip
except:
pass
# Method 4: Last resort - return localhost
return '127.0.0.1'
except Exception as e:
if startup_logger:
startup_logger.error(f"Error getting local IP: {e}")
return '127.0.0.1'
def start_server(self):
"""Start the TCP print server"""
global SERVER_RUNNING
SERVER_RUNNING = True
printer_name = self.config.get("printer_name", "")
port = self.config.get("port", 9100)
if not printer_name:
self.log("[!] No printer configured!")
return False
# Kill any process using the port first
self.log(f"[KILL] Checking for processes using port {port}...")
self.kill_process_on_port(port)
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.settimeout(1.0)
try:
self.server_socket.bind(('0.0.0.0', port))
self.server_socket.listen(5)
self.running = True
self.log(f"[OK] Server started on port {port}")
self.log(f"[PRINTER] Using printer: {printer_name}")
# Get local IP addresses using improved method
local_ip = self.get_local_ip()
self.log(f"[IP] Local IP: {local_ip}")
self.log(f"[CONNECT] Other machines can connect to: {local_ip}:{port}")
while SERVER_RUNNING and self.running:
try:
client_socket, address = self.server_socket.accept()
client_thread = threading.Thread(
target=self.handle_client,
args=(client_socket, address)
)
client_thread.daemon = True
client_thread.start()
except socket.timeout:
continue
except Exception as e:
if self.running:
self.log(f"[!] Error accepting client: {e}")
break
except Exception as e:
self.log(f"[!] Server error: {e}")
return False
finally:
self.stop_server()
return True
def stop_server(self):
"""Stop the TCP print server"""
global SERVER_RUNNING
SERVER_RUNNING = False
self.running = False
if self.server_socket:
try:
self.server_socket.close()
except:
pass
self.server_socket = None
self.log("[DONE] Server stopped")
class TestClient:
"""Test client for the print server"""
@staticmethod
def test_connection(host='localhost', port=9100, test_data=None, log_callback=None):
"""Test connection to print server"""
def log(message):
print(message) # Always print to console
if log_callback:
log_callback(message)
try:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.settimeout(5)
log(f"[CONNECT] Connecting to {host}:{port}...")
client_socket.connect((host, port))
log(f"[OK] Connected successfully!")
# Send test data if provided
if test_data is not None:
log(f"[SEND] Sending {len(test_data)} bytes...")
client_socket.send(test_data)
log(f"[OK] Data sent successfully!")
else:
log(f"[OK] Connection test only - no data sent")
client_socket.close()
return True
except ConnectionRefusedError:
log(f"[ERROR] Connection refused. Is the server running on {host}:{port}?")
return False
except socket.timeout:
log(f"[ERROR] Connection timeout.")
return False
except Exception as e:
log(f"[ERROR] Error: {e}")
return False
class AutoStartManager:
"""Windows auto-start management"""
@staticmethod
def find_manager_exe():
"""Find PrinterOne Manager GUI executable"""
# Check if running from exe (PyInstaller)
if hasattr(sys, '_MEIPASS'):
# Running from exe - use sys.executable which points to exe
exe_path = os.path.abspath(sys.executable)
# For exe files, we need to include parameters as part of the command
return f'"{exe_path}" gui auto_start'
else:
# Running from Python script
current_script = os.path.abspath(__file__)
python_exe = os.path.abspath(sys.executable)
return f'"{python_exe}" "{current_script}" gui auto_start'
@staticmethod
def add_to_startup():
"""Add PrinterOne Manager to Windows startup"""
try:
registry_path = AutoStartManager.find_manager_exe()
# Add to Windows startup registry
key = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Run",
0,
winreg.KEY_SET_VALUE
)
winreg.SetValueEx(key, "PrinterOneManager", 0, winreg.REG_SZ, registry_path)
winreg.CloseKey(key)
return True, f"PrinterOne Manager added to Windows startup!"
except Exception as e:
return False, f"Error adding to startup: {e}"
@staticmethod
def remove_from_startup():
"""Remove PrinterOne Manager from Windows startup"""
try:
key = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Run",
0,
winreg.KEY_SET_VALUE
)
winreg.DeleteValue(key, "PrinterOneManager")
winreg.CloseKey(key)
return True, "PrinterOne Manager removed from Windows startup!"
except Exception as e:
return False, f"Error removing from startup: {e}"
@staticmethod
def check_startup_status():
"""Check if PrinterOne Manager is in startup"""
try:
key = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Run",
0,
winreg.KEY_READ
)
try:
value, _ = winreg.QueryValueEx(key, "PrinterOneManager")
winreg.CloseKey(key)
return True, value
except FileNotFoundError:
winreg.CloseKey(key)
return False, "Not in startup"
except Exception as e:
return False, f"Error checking startup status: {e}"
class PrinterOneGUI:
"""Integrated GUI for PrinterOne"""
def __init__(self, root):
# Setup GUI initialization logging
self.init_logger = None
try:
self.init_logger = logging.getLogger('gui_init')
if not self.init_logger.handlers: # Avoid duplicate handlers
self.init_logger.setLevel(logging.INFO)
# Create logs directory if it doesn't exist - use temp fallback if permission denied
logs_dir = "logs"
try:
if not os.path.exists(logs_dir):
os.makedirs(logs_dir)
except PermissionError:
# Fallback to user temp directory if permission denied
import tempfile
logs_dir = os.path.join(tempfile.gettempdir(), "PrinterOne", "logs")
if not os.path.exists(logs_dir):
os.makedirs(logs_dir, exist_ok=True)
# Generate GUI initialization log filename
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
gui_init_log_filename = f"gui_init_{timestamp}.log"
gui_init_log_path = os.path.join(logs_dir, gui_init_log_filename)
# Create file handler for GUI initialization log
file_handler = logging.FileHandler(gui_init_log_path, encoding='utf-8')
file_handler.setLevel(logging.INFO)
# Create formatter
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
# Add handler to logger
self.init_logger.addHandler(file_handler)
except Exception as e:
print(f"Error setting up GUI init logging: {e}")
self.init_logger = None
try:
if self.init_logger:
self.init_logger.info("=== PrinterOneGUI Initialization Started ===")
self.init_logger.info(f"Tkinter root object: {root}")
self.root = root
self.root.title("PrinterOne - Network Print Server")
self.root.geometry("1200x700")
self.root.resizable(True, True)
if self.init_logger:
self.init_logger.info("Basic root window configuration completed")
# Initialize server with log callback
if self.init_logger:
self.init_logger.info("Initializing PrinterOneServer...")
self.server = PrinterOneServer(log_callback=self.log_message)
self.server_thread = None
if self.init_logger:
self.init_logger.info("PrinterOneServer initialized successfully")
# GUI variables
if self.init_logger:
self.init_logger.info("Setting up GUI variables...")
self.printer_var = tk.StringVar(value=self.server.config.get("printer_name", ""))
self.port_var = tk.IntVar(value=self.server.config.get("port", 9100))
self.test_host_var = tk.StringVar(value="localhost")
self.test_port_var = tk.IntVar(value=9100)
# System tray variables
self.tray_icon = None
self.minimize_to_tray = self.server.config.get("minimize_to_tray", True)
self.minimize_to_tray_var = tk.BooleanVar(value=self.minimize_to_tray)
if self.init_logger:
self.init_logger.info("GUI variables setup completed")
# Setup logging
if self.init_logger:
self.init_logger.info("Setting up application logging...")
self.logger = self.setup_logging()
if self.init_logger:
self.init_logger.info("Application logging setup completed")
# Set window icon
if self.init_logger: