forked from KorryKatti/Mirage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
1579 lines (1332 loc) · 59.6 KB
/
client.py
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
import sys
import json
import socket
import threading
import os
import base64
from datetime import datetime
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QSplitter, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QPushButton, QLineEdit, QTextEdit, QStackedWidget, QMessageBox,
QScrollArea, QButtonGroup, QDialog, QFormLayout, QTableWidget, QTableWidgetItem, QHeaderView,
QFileDialog, QProgressBar, QProgressDialog, QInputDialog, QDialogButtonBox
)
from PyQt6.QtCore import Qt, QUrl, pyqtSignal, QObject, QTimer, QThread, Qt
from PyQt6.QtGui import QIcon, QDesktopServices, QPixmap, QTextCursor
import requests
from requests_toolbelt.multipart import MultipartEncoder, MultipartEncoderMonitor
class ChatClient:
def __init__(self):
self.socket = None
self.username = None
self.avatar_url = None
self.bio = None
self.server_url = 'localhost:12345' # Changed to use full URL format
def connect(self):
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host, port = self.server_url.split(':')
self.socket.connect((host, int(port)))
return True
except Exception as e:
print(f"Connection error: {e}")
return False
def send_message(self, message):
try:
self.socket.send(message.encode())
except:
return False
return True
def close(self):
self.socket.close()
def send_file(self, room, file_path):
"""
Send file link to room (deprecated, now handled by FileUploader)
"""
try:
# Validate file size (limit to 50MB)
file_size = os.path.getsize(file_path)
if file_size > 50 * 1024 * 1024: # 50MB
print("File too large")
return False
# Prepare file transfer message
file_info = {
'type': 'file_transfer',
'room': room,
'filename': os.path.basename(file_path)
}
# Send file info via socket
self.socket.send(json.dumps(file_info).encode('utf-8'))
return True
except Exception as e:
print(f"File transfer error: {e}")
return False
def upload_file(self, file_path):
"""
Deprecated method, now handled by FileUploader
"""
return None
def receive_file(self, file_info):
"""
Receive and save a file from another user.
:param file_info: Dictionary containing file transfer information
:return: Path to saved file or None
"""
try:
# Download file from transfer.sh
response = requests.get(file_info['download_link'])
if response.status_code == 200:
# Create downloads directory if it doesn't exist
downloads_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'downloads')
os.makedirs(downloads_dir, exist_ok=True)
# Save file
file_path = os.path.join(downloads_dir, file_info['filename'])
with open(file_path, 'wb') as file:
file.write(response.content)
return file_path
else:
print(f"File download failed: {response.status_code}")
return None
except Exception as e:
print(f"File receive error: {e}")
return None
def submit_profile_comment(self, comment_data):
"""
Submit a profile comment via the existing socket connection
:param comment_data: JSON string containing comment details
"""
try:
# Send comment to server
self.client.send_message(comment_data)
print("Comment submitted successfully")
except Exception as e:
print(f"Error submitting comment: {e}")
class MessageReceiver(QObject):
message_received = pyqtSignal(str)
room_changed = pyqtSignal(str)
room_list_updated = pyqtSignal(list)
room_created = pyqtSignal(bool, str)
explore_rooms_response = pyqtSignal(list)
member_list_response = pyqtSignal(list)
def __init__(self, socket):
super().__init__()
self.socket = socket
self.running = True
def receive_messages(self):
while self.running:
try:
message = self.socket.recv(1024).decode()
if not message:
continue
# Try to parse as JSON first
try:
data = json.loads(message)
# Handle different types of JSON messages
if data.get('action') == 'room_changed':
self.room_changed.emit(data['room'])
elif data.get('action') == 'chat_message':
self.message_received.emit(data['message'])
elif data.get('action') == 'room_list':
self.room_list_updated.emit(data['rooms'])
elif data.get('action') == 'create_room_response':
self.room_created.emit(data['success'], data['message'])
elif data.get('action') == 'explore_rooms_response':
self.explore_rooms_response.emit(data['rooms'])
elif data.get('action') == 'get_room_members_response':
self.member_list_response.emit(data['members'])
elif data.get('action') == 'error':
QMessageBox.warning(None, "Error", data['message'])
elif data.get('type') == 'file_transfer':
# Handle file transfer
file_path = self.socket.recv(1024).decode()
file_data = self.socket.recv(int(file_path)).decode()
file_info = json.loads(file_data)
file_path = self.socket.recv(int(file_info['filesize'])).decode()
print(f"Received file: {file_info['filename']}")
except json.JSONDecodeError:
# If it's not JSON, treat as plain chat message
self.message_received.emit(message)
except Exception as e:
print(f"Error receiving message: {e}")
break
def stop(self):
self.running = False
def run(self):
self.receive_messages()
class FileUploader(QThread):
upload_progress = pyqtSignal(int)
upload_complete = pyqtSignal(str, str)
upload_error = pyqtSignal(str)
def __init__(self, file_path, client_socket, username, current_room):
super().__init__()
self.file_path = file_path
self.client_socket = client_socket
self.username = username
self.current_room = current_room
def run(self):
try:
# Get file details
import os
filename = os.path.basename(self.file_path)
filesize = os.path.getsize(self.file_path)
# Prepare file transfer metadata
file_transfer_data = {
'action': 'file_transfer',
'filename': filename,
'filesize': filesize,
'sender': self.username,
'room': self.current_room
}
# Send metadata
self.client_socket.send_message(json.dumps(file_transfer_data))
# Open and send file contents
with open(self.file_path, 'rb') as f:
bytes_sent = 0
while True:
chunk = f.read(4096)
if not chunk:
break
self.client_socket.socket.send(chunk)
bytes_sent += len(chunk)
progress = int((bytes_sent / filesize) * 100)
self.upload_progress.emit(progress)
# Wait for server confirmation
response = self.client_socket.socket.recv(1024).decode()
response_data = json.loads(response)
if response_data.get('action') == 'file_transfer_complete':
# Emit success signal with original filename and unique filename
self.upload_complete.emit(
filename,
response_data.get('unique_filename', filename)
)
else:
self.upload_error.emit("File transfer failed")
except Exception as e:
self.upload_error.emit(str(e))
class DownloadableFileButton(QPushButton):
"""
Custom button for downloadable files with embedded download link
"""
def __init__(self, filename, download_link, parent=None):
super().__init__(f"📥 Download: {filename}", parent)
self.filename = filename
self.download_link = download_link
self.setStyleSheet("""
QPushButton {
background-color: #4CAF50;
color: white;
border: none;
padding: 5px 10px;
text-align: left;
border-radius: 5px;
}
QPushButton:hover {
background-color: #45a049;
}
""")
self.clicked.connect(self.download_file)
def download_file(self):
"""
Download the file when button is clicked
"""
try:
# Open file save dialog
save_path, _ = QFileDialog.getSaveFileName(
self,
"Save Downloaded File",
self.filename,
"All Files (*.*)"
)
if not save_path:
return # User cancelled
# Download file in a thread
self.downloader = FileDownloader(self.download_link, save_path)
self.downloader.download_complete.connect(self.on_download_complete)
self.downloader.download_error.connect(self.on_download_error)
self.downloader.start()
except Exception as e:
QMessageBox.warning(self, "Download Error", str(e))
def on_download_complete(self, save_path):
"""
Show success message when download is complete
"""
QMessageBox.information(
self,
"Download Complete",
f"File saved to: {save_path}"
)
def on_download_error(self, error):
"""
Show error message if download fails
"""
QMessageBox.warning(
self,
"Download Failed",
str(error)
)
class FileDownloader(QThread):
"""
Threaded file downloader
"""
download_complete = pyqtSignal(str)
download_error = pyqtSignal(str)
def __init__(self, download_url, save_path):
super().__init__()
self.download_url = download_url
self.save_path = save_path
def run(self):
"""
Download file in a separate thread
"""
try:
# Download file
response = requests.get(self.download_url, timeout=30)
if response.status_code == 200:
# Save file
with open(self.save_path, 'wb') as file:
file.write(response.content)
# Emit success signal
self.download_complete.emit(self.save_path)
else:
self.download_error.emit(f"Download failed: {response.status_code}")
except requests.exceptions.RequestException as e:
self.download_error.emit(f"Network error: {str(e)}")
except Exception as e:
self.download_error.emit(f"Download error: {str(e)}")
class RoomJoinHandler(QObject):
password_required = pyqtSignal(str)
join_error = pyqtSignal(str)
room_changed = pyqtSignal(str)
class PasswordHandler(QObject):
show_password_dialog = pyqtSignal(str, str)
join_room_with_password = pyqtSignal(str, str)
class SettingsUpdater(QObject):
update_finished = pyqtSignal(bool, str, dict)
def __init__(self, client, data):
super().__init__()
self.client = client
self.data = data
def update_settings(self):
try:
self.client.send_message(json.dumps(self.data))
response = json.loads(self.client.socket.recv(1024).decode())
print("Settings update response:", response)
if response['success']:
user_data = {
'avatar_url': response.get('avatar_url', ''),
'bio': response.get('bio', '')
}
self.update_finished.emit(True, response['message'], user_data)
else:
self.update_finished.emit(False, response['message'], {})
except Exception as e:
print("Error in settings update:", str(e))
self.update_finished.emit(False, str(e), {})
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.client = ChatClient()
self.message_receiver = None
self.receiver_thread = None
self.settings_thread = None
self.room_buttons = {} # Initialize room_buttons dictionary
self.button_group = QButtonGroup() # Initialize button group
self.button_group.setExclusive(True)
self.last_attempted_room = None # Initialize last_attempted_room
# Create password handler
self.password_handler = PasswordHandler()
self.password_handler.show_password_dialog.connect(self._show_password_dialog)
self.password_handler.join_room_with_password.connect(self._join_room_with_password)
# Create room join handler
self.room_join_handler = RoomJoinHandler()
self.room_join_handler.password_required.connect(self.handle_password_prompt)
self.room_join_handler.join_error.connect(self.handle_join_error)
self.room_join_handler.room_changed.connect(self.update_current_room)
# Create messages directory if it doesn't exist
self.messages_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'messages')
os.makedirs(self.messages_dir, exist_ok=True)
self.setup_ui()
def setup_ui(self):
self.setWindowTitle("Mirage v0.0.2")
self.setWindowIcon(QIcon("assets/img/icon.png"))
self.stacked_widget = QStackedWidget()
self.setCentralWidget(self.stacked_widget)
self.create_welcome_screen()
self.create_login_screen()
self.create_register_screen()
self.create_chat_screen()
self.stacked_widget.setCurrentWidget(self.welcome_screen)
def create_welcome_screen(self):
self.welcome_screen = QWidget()
layout = QVBoxLayout(self.welcome_screen)
layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
title = QLabel("Mirage")
title.setStyleSheet("font-size: 36px; font-weight: bold; color: #e0def4;")
layout.addWidget(title, alignment=Qt.AlignmentFlag.AlignCenter)
subtitle = QLabel("Your go-to chat app")
subtitle.setStyleSheet("font-size: 18px; color: #9ccfd8;")
layout.addWidget(subtitle, alignment=Qt.AlignmentFlag.AlignCenter)
login_btn = QPushButton("Login")
login_btn.setStyleSheet(self.get_button_style())
login_btn.clicked.connect(lambda: self.stacked_widget.setCurrentWidget(self.login_screen))
layout.addWidget(login_btn)
register_btn = QPushButton("Register")
register_btn.setStyleSheet(self.get_button_style())
register_btn.clicked.connect(lambda: self.stacked_widget.setCurrentWidget(self.register_screen))
layout.addWidget(register_btn)
self.welcome_screen.setStyleSheet("background-color: #191724;")
self.stacked_widget.addWidget(self.welcome_screen)
def create_login_screen(self):
self.login_screen = QWidget()
layout = QVBoxLayout(self.login_screen)
layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
title = QLabel("Login")
title.setStyleSheet("font-size: 24px; font-weight: bold; color: #e0def4;")
layout.addWidget(title, alignment=Qt.AlignmentFlag.AlignCenter)
self.login_username = QLineEdit()
self.login_username.setPlaceholderText("Username")
self.login_username.setStyleSheet(self.get_input_style())
layout.addWidget(self.login_username)
self.login_password = QLineEdit()
self.login_password.setPlaceholderText("Password")
self.login_password.setEchoMode(QLineEdit.EchoMode.Password)
self.login_password.setStyleSheet(self.get_input_style())
layout.addWidget(self.login_password)
login_btn = QPushButton("Login")
login_btn.setStyleSheet(self.get_button_style())
login_btn.clicked.connect(self.handle_login)
layout.addWidget(login_btn)
back_btn = QPushButton("Back")
back_btn.setStyleSheet(self.get_button_style())
back_btn.clicked.connect(lambda: self.stacked_widget.setCurrentWidget(self.welcome_screen))
layout.addWidget(back_btn)
self.login_screen.setStyleSheet("background-color: #191724;")
self.stacked_widget.addWidget(self.login_screen)
def create_register_screen(self):
self.register_screen = QWidget()
layout = QVBoxLayout(self.register_screen)
layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
title = QLabel("Register")
title.setStyleSheet("font-size: 24px; font-weight: bold; color: #e0def4;")
layout.addWidget(title, alignment=Qt.AlignmentFlag.AlignCenter)
self.register_username = QLineEdit()
self.register_username.setPlaceholderText("Username")
self.register_username.setStyleSheet(self.get_input_style())
layout.addWidget(self.register_username)
self.register_email = QLineEdit()
self.register_email.setPlaceholderText("Email")
self.register_email.setStyleSheet(self.get_input_style())
layout.addWidget(self.register_email)
self.register_password = QLineEdit()
self.register_password.setPlaceholderText("Password")
self.register_password.setEchoMode(QLineEdit.EchoMode.Password)
self.register_password.setStyleSheet(self.get_input_style())
layout.addWidget(self.register_password)
self.register_confirm_password = QLineEdit()
self.register_confirm_password.setPlaceholderText("Confirm Password")
self.register_confirm_password.setEchoMode(QLineEdit.EchoMode.Password)
self.register_confirm_password.setStyleSheet(self.get_input_style())
layout.addWidget(self.register_confirm_password)
self.register_avatar = QLineEdit()
self.register_avatar.setPlaceholderText("Avatar URL (optional)")
self.register_avatar.setStyleSheet(self.get_input_style())
layout.addWidget(self.register_avatar)
self.register_bio = QLineEdit()
self.register_bio.setPlaceholderText("Bio (optional)")
self.register_bio.setStyleSheet(self.get_input_style())
layout.addWidget(self.register_bio)
register_btn = QPushButton("Register")
register_btn.setStyleSheet(self.get_button_style())
register_btn.clicked.connect(self.handle_register)
layout.addWidget(register_btn)
back_btn = QPushButton("Back")
back_btn.setStyleSheet(self.get_button_style())
back_btn.clicked.connect(lambda: self.stacked_widget.setCurrentWidget(self.welcome_screen))
layout.addWidget(back_btn)
self.register_screen.setStyleSheet("background-color: #191724;")
self.stacked_widget.addWidget(self.register_screen)
def create_chat_screen(self):
self.chat_screen = QWidget()
layout = QHBoxLayout()
# Left panel for room list
left_panel = QWidget()
left_layout = QVBoxLayout()
# Room list label
room_label = QLabel("Your Rooms")
room_label.setStyleSheet("font-size: 18px; font-weight: bold; color: #e0def4;")
left_layout.addWidget(room_label)
# Room list
self.room_list = QVBoxLayout()
left_layout.addLayout(self.room_list)
left_layout.addStretch()
# Settings button
settings_btn = QPushButton("Settings")
settings_btn.clicked.connect(self.show_settings_dialog)
left_layout.addWidget(settings_btn)
# Member list button
member_list_btn = QPushButton("Member List")
member_list_btn.clicked.connect(self.show_member_list)
left_layout.addWidget(member_list_btn)
left_panel.setLayout(left_layout)
left_panel.setFixedWidth(200)
layout.addWidget(left_panel)
# Center chat area
center_panel = QWidget()
center_layout = QVBoxLayout()
# Current room label
self.current_room_label = QLabel("global")
self.current_room_label.setStyleSheet("font-size: 16px; font-weight: bold;")
center_layout.addWidget(self.current_room_label)
# Chat display
self.chat_display = QTextEdit()
self.chat_display.setReadOnly(True)
center_layout.addWidget(self.chat_display)
# Message input
input_layout = QHBoxLayout()
self.message_input = QLineEdit()
self.message_input.returnPressed.connect(self.send_message)
send_button = QPushButton("Send")
send_button.clicked.connect(self.send_message)
file_transfer_btn = QPushButton("📁 Send File")
file_transfer_btn.setStyleSheet(self.get_button_style())
file_transfer_btn.clicked.connect(self.send_file_dialog)
input_layout.addWidget(self.message_input)
input_layout.addWidget(send_button)
input_layout.addWidget(file_transfer_btn)
center_layout.addLayout(input_layout)
center_panel.setLayout(center_layout)
layout.addWidget(center_panel)
# Right panel for room management
right_panel = QWidget()
right_layout = QVBoxLayout()
# Room management label
manage_label = QLabel("Room Management")
manage_label.setStyleSheet("font-size: 18px; font-weight: bold; color: #e0def4;")
right_layout.addWidget(manage_label)
# Create room button
create_room_btn = QPushButton("Create New Room")
create_room_btn.clicked.connect(self.create_room_dialog)
right_layout.addWidget(create_room_btn)
# Explore rooms button
explore_rooms_btn = QPushButton("Explore Rooms")
explore_rooms_btn.clicked.connect(self.explore_rooms_dialog)
right_layout.addWidget(explore_rooms_btn)
right_layout.addStretch()
right_panel.setLayout(right_layout)
right_panel.setFixedWidth(200)
layout.addWidget(right_panel)
self.chat_screen.setLayout(layout)
self.stacked_widget.addWidget(self.chat_screen)
def create_room_buttons(self, rooms):
"""Create buttons for each room"""
# Clear existing buttons first
while self.room_list.count():
item = self.room_list.takeAt(0)
if item.widget():
item.widget().deleteLater()
for btn in self.room_buttons.values():
self.button_group.removeButton(btn)
self.room_buttons.clear()
# Create new buttons
for room in sorted(set(rooms)): # Use set to remove duplicates
btn = QPushButton(room)
btn.setCheckable(True)
self.button_group.addButton(btn)
btn.clicked.connect(lambda checked, r=room: self.join_room(r))
self.room_buttons[room] = btn
self.room_list.addWidget(btn)
# Set button style
btn.setStyleSheet("""
QPushButton {
background-color: #26233a;
color: #e0def4;
border: none;
padding: 10px;
border-radius: 4px;
text-align: left;
margin: 2px;
}
QPushButton:hover {
background-color: #2d2a41;
}
QPushButton:checked {
background-color: #9ccfd8;
color: #191724;
}
""")
# Select global room by default if no room is selected
if not self.button_group.checkedButton() and 'global' in self.room_buttons:
self.room_buttons['global'].setChecked(True)
self.room_list.addStretch()
def load_room_messages(self, room):
"""Load messages for a specific room"""
try:
# Clean room name to be safe for filenames
safe_room = "".join(x for x in room if x.isalnum() or x in (' ', '-', '_')).strip()
filename = os.path.join(self.messages_dir, f"{safe_room}.txt")
if os.path.exists(filename):
print(f"Loading messages from {filename}") # Debug print
with open(filename, 'r', encoding='utf-8') as f:
messages = f.readlines()
# Only show last 100 messages to avoid overwhelming the display
messages = [msg.strip() for msg in messages if msg.strip()] # Remove empty lines
if messages:
self.chat_display.clear()
for msg in messages[-100:]:
self.chat_display.append(msg)
# Scroll to bottom
self.chat_display.verticalScrollBar().setValue(
self.chat_display.verticalScrollBar().maximum()
)
print(f"Loaded {len(messages[-100:])} messages") # Debug print
else:
print("No messages found in file") # Debug print
else:
print(f"No message file found at {filename}") # Debug print
except Exception as e:
print(f"Error loading room messages: {e}")
def update_current_room(self, room):
"""Update the current room label and chat display"""
old_room = self.current_room_label.text()
if old_room != room: # Only update if actually changing rooms
print(f"Changing room from {old_room} to {room}") # Debug print
self.current_room_label.setText(room)
self.chat_display.clear()
self.load_room_messages(room)
def join_room(self, room):
"""Join a new room"""
if room == self.current_room_label.text():
return
# Send join request to server
join_request = json.dumps({
'action': 'join_room',
'username': self.client.username,
'room': room
})
try:
self.client.send_message(join_request)
except Exception as e:
QMessageBox.warning(self, "Room Join Error", f"Failed to join room: {str(e)}")
def handle_password_prompt(self, error_message):
"""Handle password prompt for private rooms"""
password, ok = QInputDialog.getText(
self,
"Private Room",
error_message,
QLineEdit.EchoMode.Password
)
if ok and password and self.last_attempted_room:
# Send join request with password
join_request = json.dumps({
'action': 'join_room',
'username': self.client.username,
'room': self.last_attempted_room,
'password': password
})
try:
# Use a separate thread to send message
threading.Thread(target=self._send_join_request, args=(join_request,), daemon=True).start()
except Exception as e:
self.room_join_handler.join_error.emit(f"Failed to join room: {str(e)}")
def handle_join_error(self, error_message):
"""Handle join room errors"""
QMessageBox.warning(self, "Room Join Error", error_message)
def handle_login(self):
if not self.client.connect():
QMessageBox.critical(self, "Error", "Could not connect to server")
return
data = {
'action': 'login',
'username': self.login_username.text().strip(),
'password': self.login_password.text().strip()
}
self.client.send_message(json.dumps(data))
# Receive data in a more robust way
buffer = b''
response = None
room_data = None
try:
while True:
chunk = self.client.socket.recv(1024)
if not chunk:
print("No data received from server")
break
buffer += chunk
# Try to split multiple JSON objects
try:
# Split the buffer into potential JSON objects
json_objects = buffer.decode().split('}{')
# If we have multiple objects, reconstruct them
if len(json_objects) > 1:
json_objects = [
json_objects[0] + '}' if not json_objects[0].endswith('}') else json_objects[0],
'{' + json_objects[1] if not json_objects[1].startswith('{') else json_objects[1]
]
# Try to parse each object
for obj_str in json_objects:
try:
parsed_obj = json.loads(obj_str)
# Determine which object we've received
if 'success' in parsed_obj:
response = parsed_obj
elif 'action' in parsed_obj and parsed_obj['action'] == 'room_list':
room_data = parsed_obj
except json.JSONDecodeError:
# If parsing fails, continue
continue
# If we have both response and room_data, we're done
if response and room_data:
break
except Exception as e:
print(f"Error parsing JSON: {e}")
break
except Exception as e:
print(f"Error receiving login response: {e}")
return
if not response:
print("No valid login response received from server")
return
if response.get('success'):
# Store user data
self.client.username = data['username']
self.client.avatar_url = response.get('avatar_url', '')
self.client.bio = response.get('bio', '')
print("Logged in with data:", {
'username': self.client.username,
'avatar_url': self.client.avatar_url,
'bio': self.client.bio
})
if not room_data:
print("No room list received")
return
if room_data['action'] == 'room_list':
self.create_room_buttons(room_data['rooms'])
self.stacked_widget.setCurrentWidget(self.chat_screen)
# Load initial room messages
print("Loading initial room messages") # Debug print
self.load_room_messages('global')
self.start_message_receiver()
QMessageBox.information(self, "Success", "Login successful!")
else:
QMessageBox.warning(self, "Login Failed", response['message'])
self.client.close()
def handle_register(self):
if self.register_password.text() != self.register_confirm_password.text():
QMessageBox.warning(self, "Error", "Passwords do not match!")
return
if not self.client.connect():
QMessageBox.critical(self, "Error", "Could not connect to server")
return
data = {
'action': 'register',
'username': self.register_username.text().strip(),
'email': self.register_email.text().strip(),
'password': self.register_password.text().strip(),
'avatar_url': self.register_avatar.text().strip() or "https://i.pinimg.com/736x/0c/da/40/0cda4058d21f8101ffcc223eec55c18f.jpg",
'bio': self.register_bio.text().strip() or "No bio provided"
}
self.client.send_message(json.dumps(data))
response = json.loads(self.client.socket.recv(1024).decode())
if response['success']:
self.client.username = data['username']
self.client.avatar_url = data['avatar_url']
self.client.bio = data['bio']
print("Registered with data:", {
'username': self.client.username,
'avatar_url': self.client.avatar_url,
'bio': self.client.bio
})
room_data = json.loads(self.client.socket.recv(1024).decode())
if room_data['action'] == 'room_list':
self.create_room_buttons(room_data['rooms'])
self.stacked_widget.setCurrentWidget(self.chat_screen)
self.start_message_receiver()
QMessageBox.information(self, "Success", "Registration successful!")
else:
QMessageBox.warning(self, "Registration Failed", response['message'])
self.client.close()
def send_message(self):
"""Send a message"""
message = self.message_input.text().strip()
if message:
data = {
'action': 'send_message',
'username': self.client.username,
'message': message,
'room': self.current_room_label.text()
}
try:
self.client.send_message(json.dumps(data))
self.message_input.clear()
# No need to save here as we'll receive our own message back
except Exception as e:
QMessageBox.warning(self, "Error", f"Failed to send message: {str(e)}")
def display_message(self, message):
"""Display and save received message"""
# Only append if it's not already the last message
last_message = self.chat_display.toPlainText().split('\n')[-1] if self.chat_display.toPlainText() else ''
if message != last_message:
self.chat_display.append(message)
self.save_message_to_file(message, self.current_room_label.text())
# Scroll to bottom
self.chat_display.verticalScrollBar().setValue(
self.chat_display.verticalScrollBar().maximum()
)
def save_message_to_file(self, message, room):
"""Save message to room-specific file"""
try:
# Clean room name to be safe for filenames
safe_room = "".join(x for x in room if x.isalnum() or x in (' ', '-', '_')).strip()
filename = os.path.join(self.messages_dir, f"{safe_room}.txt")
# Check if message already exists in last line
last_line = ''
if os.path.exists(filename):
with open(filename, 'r', encoding='utf-8') as f:
# Move to the last line
try:
f.seek(-2, 2) # Go to 2nd last byte
while f.read(1) != '\n': # Until EOL is found
try:
f.seek(-2, 1) # Go back 2 bytes and read
except:
f.seek(0) # Go to start of file
break
last_line = f.readline().strip()
except:
f.seek(0) # If file is too small, start from beginning
last_line = f.readline().strip()
# Only write if it's not a duplicate of the last line
if message.strip() != last_line:
# Ensure parent directory exists
os.makedirs(os.path.dirname(filename), exist_ok=True)
# Append message to file
with open(filename, 'a', encoding='utf-8') as f:
f.write(f"{message}\n")
except Exception as e:
print(f"Error saving message to file: {e}")
def get_button_style(self):
return """
QPushButton {
background-color: #9ccfd8;
color: #191724;
border: none;
font-size: 16px;
padding: 8px 16px;
border-radius: 4px;
margin: 5px;
}
QPushButton:hover {
background-color: #7fbcc5;
}
"""
def get_input_style(self):
return """
QLineEdit {
background-color: #1f1d2e;
color: #e0def4;
border: 1px solid #9ccfd8;
padding: 8px;
border-radius: 4px;
margin: 5px;
}
"""
def show_settings_dialog(self):
dialog = QDialog(self)
dialog.setWindowTitle("Settings")
dialog.setStyleSheet("""
QDialog {
background-color: #191724;
}
QLabel {
color: #e0def4;
font-size: 14px;
}
QLineEdit {
background-color: #1f1d2e;
color: #e0def4;
border: 1px solid #9ccfd8;
padding: 8px;
border-radius: 4px;
margin: 5px;
}
QPushButton {
background-color: #9ccfd8;