-
Notifications
You must be signed in to change notification settings - Fork 0
/
dev.py
1774 lines (1492 loc) · 78.5 KB
/
dev.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
# main.py
from PyQt6.QtWidgets import (QDialog, QMenu, QGroupBox, QFileDialog, QComboBox, QApplication, QMainWindow, QTabWidget, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
QLineEdit, QPushButton, QListWidget, QTableWidget, QTableWidgetItem, QMessageBox,
QProgressDialog, QAbstractItemView, QHeaderView)
from PyQt6.QtGui import QAction, QImage, QIcon, QPixmap, QDragEnterEvent, QDropEvent, QFont, QDesktopServices, QBrush
from PyQt6.QtCore import Qt, QFile, QTextStream, QIODevice, pyqtSignal, QThread, QTimer, QObject, QUrl
from datetime import datetime
from pathlib import Path
from PIL import Image
from io import BytesIO
import requests
import logging
import base64
from functools import partial
from io import BytesIO
import os
import json
import sys
import urllib.parse
import subprocess
# Import worker classes from workers.py
from dialogs import HelpDialog, LogViewerDialog, ManualAddAlbumDialog, SubmitDialog, UpdateDialog
from workers import DownloadWorker, SubmitWorker, Worker
from image_handler import ImageWidget
from delegates import (
ComboBoxDelegate, RatingDelegate, SearchHighlightDelegate, GenreSearchDelegate, strip_html_tags
)
from telegram_bot import TelegramBot
def setup_logging():
# Define the logs directory within the user's application data folder
app_name = 'SuSheApp'
log_dir = os.path.join(os.getenv('APPDATA'), app_name, 'logs')
os.makedirs(log_dir, exist_ok=True) # Create the directory if it doesn't exist
# Use a more detailed timestamp for the log filename
log_filename = os.path.join(log_dir, datetime.now().strftime("SuShe_%Y-%m-%d_%H-%M-%S.log"))
logging.basicConfig(
filename=log_filename,
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
# Add the QTextEditLogger handler
text_edit_logger = QTextEditLogger()
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
text_edit_logger.setFormatter(formatter)
logging.getLogger().addHandler(text_edit_logger)
def handle_exception(exc_type, exc_value, exc_traceback):
logging.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
print("Uncaught exception:", exc_type, exc_value, exc_traceback) # Add this line
sys.excepthook = handle_exception
logging.getLogger().setLevel(logging.DEBUG)
logging.info("Logging setup complete")
return text_edit_logger
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def read_file_lines(filepath):
correct_path = resource_path(filepath)
logging.debug(f"Reading file: {correct_path}")
with open(correct_path, 'r') as file:
lines = set(line.strip() for line in file)
if 'genres.txt' in filepath:
lines = {line.title() for line in lines}
logging.debug(f"Read {len(lines)} lines from {filepath}")
return sorted(lines)
class QTextEditLogger(logging.Handler, QObject):
log_signal = pyqtSignal(str)
def __init__(self):
QObject.__init__(self)
logging.Handler.__init__(self)
self.log_viewer = None
self.buffer = [] # Buffer to store log messages before log_viewer is set
self.log_signal.connect(self._append_log)
def emit(self, record):
msg = self.format(record)
self.buffer.append(msg)
self.log_signal.emit(msg)
def _append_log(self, msg):
if self.log_viewer:
self.log_viewer.append_log(msg)
def set_log_viewer(self, log_viewer):
self.log_viewer = log_viewer
# Flush the buffered messages to the log viewer
for msg in self.buffer:
self.log_viewer.append_log(msg)
self.buffer.clear()
class SpotifyAlbumAnalyzer(QMainWindow):
def __init__(self, text_edit_logger):
super().__init__()
self.text_edit_logger = text_edit_logger
self.version = self.get_app_version() # Initialize version early
self.current_file_path = None
self.last_opened_file = None
self.recent_files = []
self.client_id = None
self.client_secret = None
self.bot_token = None
self.chat_id = None
self.message_thread_id = None
self.dataChanged = False
# Initialize search-related variables
self.matches = []
self.current_match_index = -1
def perform_initialization(self):
# Initialize UI and other components
self.initUI() # Initialize UI elements before loading settings
self.load_config()
self.load_settings()
self.update_recent_files_menu()
if self.last_opened_file and os.path.exists(self.last_opened_file):
self.load_album_data(self.last_opened_file)
self.current_file_path = self.last_opened_file
self.update_window_title()
self.dataChanged = False
# Perform the update check and decide whether to show the main window
should_show = self.check_for_updates()
if should_show:
# Show the main window after update check is done
self.show()
else:
# The user chose to download an update; exit the application
logging.info("Exiting application after initiating update download.")
def initUI(self):
self.client_id = None
self.client_secret = None
self.dataChanged = False
self.preferred_music_player = 'Spotify' # Initialize with default value
self.update_window_title()
self.artist_id_map = {}
self.album_id_map = {}
# Initialize worker attributes
self.artist_search_worker = None
self.albums_fetch_worker = None
self.album_details_worker = None
self.setAcceptDrops(True)
self.resize(1500, 800)
self.setWindowTitle("SuShe!")
self.setWindowIcon(QIcon(resource_path(os.path.join("logos", "logo.ico"))))
self.setup_menu_bar()
# Initialize genres and countries before setting up tabs
self.genres = read_file_lines('genres.txt')
self.countries = read_file_lines('countries.txt')
self.setup_tabs()
# Add a QLabel for notifications
self.notification_label = QLabel(self)
self.notification_label.setStyleSheet(
"background-color: #2D2D30; "
"font-weight: bold; "
"border-radius: 3px; "
"color: white; "
"padding: 5px; "
"border: 2px solid white;"
)
self.notification_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.notification_label.setGeometry(0, 0, 450, 100)
self.notification_label.hide()
# Add a QLabel for the cover image inside the notification
self.notification_image_label = QLabel(self)
self.notification_image_label.setStyleSheet("border: none;")
self.notification_image_label.setGeometry(0, 0, 100, 100)
self.notification_image_label.hide()
def open_log_viewer(self):
if not hasattr(self, 'log_viewer_dialog'):
self.log_viewer_dialog = LogViewerDialog(self)
# Set the log_viewer in text_edit_logger
self.text_edit_logger.set_log_viewer(self.log_viewer_dialog)
self.log_viewer_dialog.show()
def load_config(self):
config_path = resource_path('config.json')
if os.path.exists(config_path):
try:
with open(config_path, 'r') as file:
config = json.load(file)
# Load Spotify credentials
self.client_id = config.get('spotify', {}).get('client_id', '')
self.client_secret = config.get('spotify', {}).get('client_secret', '')
self.client_id_input.setText(self.client_id)
self.client_secret_input.setText(self.client_secret)
# Load Telegram credentials
self.bot_token = config.get('telegram', {}).get('bot_token', '')
self.chat_id = config.get('telegram', {}).get('chat_id', '')
self.message_thread_id = config.get('telegram', {}).get('message_thread_id', '')
self.bot_token_input.setText(self.bot_token)
self.chat_id_input.setText(self.chat_id)
self.message_thread_id_input.setText(self.message_thread_id)
# Load GitHub credentials
self.github_token = config.get('github', {}).get('personal_access_token', '')
self.github_owner = config.get('github', {}).get('owner', '')
self.github_repo = config.get('github', {}).get('repo', '')
# Load Preferred Music Player
self.preferred_music_player = config.get('application', {}).get('preferred_music_player', 'Spotify')
index = self.preferred_music_player_combo.findText(self.preferred_music_player)
if index >= 0:
self.preferred_music_player_combo.setCurrentIndex(index)
else:
self.preferred_music_player_combo.setCurrentIndex(0)
logging.info("Configuration loaded successfully.")
except json.JSONDecodeError as e:
logging.error(f"Error parsing config.json: {e}")
QMessageBox.critical(self, "Configuration Error", "Failed to parse config.json. Please check the file format.")
else:
logging.warning("config.json not found. Telegram submission will not work.")
QMessageBox.warning(self, "Configuration Missing", "config.json not found. Telegram submission will not work.")
def check_for_updates(self):
if not all([self.github_token, self.github_owner, self.github_repo]):
logging.warning("GitHub credentials are missing. Update check will not proceed.")
return True # Proceed to show the main window
current_version = self.version
latest_version, download_url, release_notes_url = self.get_latest_github_release()
if latest_version and download_url:
from packaging import version
if version.parse(latest_version) > version.parse(current_version):
logging.info(f"A new version {latest_version} is available.")
update_dialog = UpdateDialog(latest_version, current_version, release_notes_url)
reply = update_dialog.exec()
if reply == QDialog.DialogCode.Accepted:
self.download_and_install_update(download_url)
# User chose to download the update; do not show the main window
return False
else:
logging.info("User chose not to update.")
else:
logging.error("Failed to fetch the latest release information.")
return True # Proceed to show the main window
def get_latest_github_release(self):
url = f"https://api.github.com/repos/{self.github_owner}/{self.github_repo}/releases/latest"
headers = {
"Authorization": f"token {self.github_token}",
"Accept": "application/vnd.github.v3+json"
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
release_info = response.json()
latest_version = release_info.get('tag_name')
release_notes_url = release_info.get('html_url') # URL to the release page with notes
assets = release_info.get('assets', [])
if assets:
# Log the names of available assets
logging.info(f"Available assets in the release: {[asset['name'] for asset in assets]}")
# Find the asset that matches the expected installer name
for asset in assets:
if asset['name'].endswith('.exe'):
download_url = asset.get('url') # Use 'url' for API endpoint
return latest_version, download_url, release_notes_url
logging.error("No executable (.exe) assets found in the latest release.")
return None, None, release_notes_url
else:
logging.error("No assets found in the latest release.")
return None, None, release_notes_url
except requests.exceptions.RequestException as e:
logging.error(f"Error fetching latest release: {e}")
return None, None, None
def download_and_install_update(self, download_url):
self.progress_dialog = QProgressDialog("Downloading Update...", "Cancel", 0, 100, self)
self.progress_dialog.setWindowModality(Qt.WindowModality.WindowModal)
self.progress_dialog.canceled.connect(self.cancel_download)
self.progress_dialog.show()
self.download_thread = QThread()
self.download_worker = DownloadWorker(download_url, self.github_token)
self.download_worker.moveToThread(self.download_thread)
self.download_thread.started.connect(self.download_worker.start_download)
self.download_worker.progress_changed.connect(self.progress_dialog.setValue)
self.download_worker.download_finished.connect(self.on_download_finished)
self.download_worker.download_failed.connect(self.on_download_failed)
self.download_worker.download_finished.connect(self.download_thread.quit)
self.download_worker.download_failed.connect(self.download_thread.quit)
self.download_worker.download_finished.connect(self.download_worker.deleteLater)
self.download_worker.download_failed.connect(self.download_worker.deleteLater)
self.download_thread.finished.connect(self.download_thread.deleteLater)
self.download_thread.start()
def cancel_download(self):
if hasattr(self, 'download_worker') and self.download_worker:
self.download_worker.is_cancelled = True
def on_download_finished(self, file_path):
self.progress_dialog.close()
# Launch the installer
try:
if sys.platform.startswith('win'):
os.startfile(file_path)
elif sys.platform == 'darwin':
subprocess.call(['open', file_path])
else:
subprocess.call(['xdg-open', file_path])
except Exception as e:
logging.error(f"Failed to launch installer: {e}")
QMessageBox.critical(None, "Installation Failed", f"Failed to launch installer: {e}")
else:
QApplication.quit() # Exit the application after launching the installer
def on_download_failed(self, error_message):
self.progress_dialog.close()
QMessageBox.critical(self, "Download Failed", f"Failed to download update: {error_message}")
def load_settings(self):
is_packaged = getattr(sys, 'frozen', False)
settings_path = self.get_user_data_path('settings.json', packaged=is_packaged)
if os.path.exists(settings_path):
try:
with open(settings_path, 'r') as file:
settings = json.load(file)
self.last_opened_file = settings.get('last_opened_file', None)
self.recent_files = settings.get('recent_files', [])
except json.JSONDecodeError as e:
logging.error(f"Error parsing settings.json: {e}")
self.last_opened_file = None
self.recent_files = []
else:
# This is a fresh install or settings have been deleted
self.last_opened_file = None
self.recent_files = []
def save_settings(self):
is_packaged = getattr(sys, 'frozen', False)
logging.debug(f"Application is packaged: {is_packaged}")
settings_path = self.get_user_data_path('settings.json', packaged=is_packaged)
logging.debug(f"Saving settings to: {settings_path}")
settings = {
'last_opened_file': self.current_file_path,
'recent_files': self.recent_files,
}
try:
with open(settings_path, 'w') as file:
json.dump(settings, file, indent=4)
logging.info(f"Settings saved successfully to {settings_path}")
except Exception as e:
logging.error(f"Failed to save settings: {e}")
def get_app_version(self):
try:
version_file = resource_path('version.txt')
logging.info(f"Looking for version file at: {version_file}")
with open(version_file, 'r') as f:
version = f.read().strip()
return version
except Exception as e:
logging.error(f"Error reading version.txt: {e}")
return "Unknown"
def show_notification(self, message, image_path=None):
self.notification_label.setText(message)
self.notification_label.adjustSize()
self.notification_label.move(self.width() // 2 - self.notification_label.width() // 2, 80) # Adjust this value to move the notification down
self.notification_label.show()
if image_path:
pixmap = QPixmap(image_path)
scaled_pixmap = pixmap.scaled(70, 70, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
self.notification_image_label.setPixmap(scaled_pixmap)
self.notification_image_label.move(self.notification_label.x() - 75, 50) # Position the image to the left of the text
self.notification_image_label.show()
QTimer.singleShot(2000, self.notification_label.hide)
QTimer.singleShot(2000, self.notification_image_label.hide)
def setup_menu_bar(self):
self.menu_bar = self.menuBar()
self.file_menu = self.menu_bar.addMenu("File")
self.add_menu_actions()
self.help_menu = self.menu_bar.addMenu("Help")
self.help_menu.addAction("Help").triggered.connect(self.show_help)
# Add the About menu
self.about_menu = self.menu_bar.addMenu("About")
self.about_menu.addAction("About SuShe").triggered.connect(self.show_about_dialog)
# Add 'Edit' menu with 'Find' action
self.edit_menu = self.menu_bar.addMenu("Edit")
find_action = QAction("Find", self)
find_action.setShortcut("Ctrl+F")
find_action.triggered.connect(self.show_search_bar)
self.edit_menu.addAction(find_action)
def show_search_bar(self):
if not hasattr(self, 'search_widget'):
self.search_bar = QLineEdit(self)
self.search_bar.setPlaceholderText("Search...")
self.search_bar.returnPressed.connect(self.goto_next_match)
self.search_bar.textChanged.connect(self.search_album_list)
# 'Next' and 'Previous' buttons
self.search_prev_button = QPushButton("Previous")
self.search_next_button = QPushButton("Next")
self.search_close_button = QPushButton("X")
self.search_prev_button.clicked.connect(self.goto_previous_match)
self.search_next_button.clicked.connect(self.goto_next_match)
self.search_close_button.clicked.connect(self.hide_search_bar)
# Layout for the search bar and buttons
self.search_layout = QHBoxLayout()
self.search_layout.addWidget(self.search_bar)
self.search_layout.addWidget(self.search_prev_button)
self.search_layout.addWidget(self.search_next_button)
self.search_layout.addWidget(self.search_close_button)
# Container widget for the search layout
self.search_widget = QWidget()
self.search_widget.setLayout(self.search_layout)
# Add the search widget to the album_list_tab layout
self.album_list_tab.layout().insertWidget(0, self.search_widget)
self.search_widget.hide()
if self.search_widget.isVisible():
self.hide_search_bar() # Hide and clear highlights
else:
self.search_widget.show()
self.search_bar.setFocus()
def hide_search_bar(self):
self.search_widget.hide()
self.search_bar.clear()
# Clear search text in all delegates
self.search_delegate.set_search_text("")
self.genre_delegate_1.set_search_text("")
self.genre_delegate_2.set_search_text("")
# Clear matches
self.matches = []
self.current_match_index = -1
# Update the view to remove highlights
self.album_table.viewport().update()
def search_album_list(self):
search_text = self.search_bar.text().strip().lower()
self.search_delegate.set_search_text(search_text)
self.genre_delegate_1.set_search_text(search_text)
self.genre_delegate_2.set_search_text(search_text)
self.matches = []
if not search_text:
self.current_match_index = -1
return
# Columns to search
columns_to_search = [0, 1, 5, 6, 8] # Artist, Album, Genre 1, Genre 2, Comments
# Find matches
for row in range(self.album_table.rowCount()):
for column in columns_to_search:
item_text = ""
item = self.album_table.item(row, column)
widget = self.album_table.cellWidget(row, column)
if item:
item_text = item.text().lower()
elif widget and isinstance(widget, QLabel):
item_text = strip_html_tags(widget.text()).lower()
if search_text in item_text:
self.matches.append((row, column))
self.current_match_index = -1
if self.matches:
self.goto_next_match()
def clear_search_highlights(self):
for row in range(self.album_table.rowCount()):
for column in range(self.album_table.columnCount()):
item = self.album_table.item(row, column)
if item:
item.setBackground(QBrush(Qt.GlobalColor.white))
def goto_next_match(self):
if not self.matches:
return
self.current_match_index = (self.current_match_index + 1) % len(self.matches)
row, column = self.matches[self.current_match_index]
self.album_table.scrollToItem(self.album_table.item(row, column) or self.album_table.item(row, 0), QAbstractItemView.ScrollHint.PositionAtCenter)
self.album_table.setCurrentCell(row, column)
def goto_previous_match(self):
if not self.matches:
return
self.current_match_index = (self.current_match_index - 1) % len(self.matches)
row, column = self.matches[self.current_match_index]
self.album_table.scrollToItem(self.album_table.item(row, column) or self.album_table.item(row, 0), QAbstractItemView.ScrollHint.PositionAtCenter)
self.album_table.setCurrentCell(row, column)
def show_about_dialog(self):
version = self.get_app_version()
about_text = f"""
<h2>SuShe</h2>
<p><strong>Version:</strong> {version}</p>
<p>SuShe is an album list manager, aimed at creating superior album of the year lists.</p>
<p>Contact: <a href="mailto:[email protected]">[email protected]</a></p>
"""
msg_box = QMessageBox(self)
msg_box.setWindowTitle("About SuShe")
msg_box.setIcon(QMessageBox.Icon.Information)
msg_box.setText(about_text)
msg_box.setTextFormat(Qt.TextFormat.RichText) # Enable rich text
msg_box.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction) # Enable clickable links
msg_box.exec()
def update_recent_files_menu(self):
self.recent_files_menu.clear()
for file_path in self.recent_files:
if os.path.exists(file_path):
action = QAction(file_path, self)
action.triggered.connect(partial(self.trigger_load_album_data, file_path))
self.recent_files_menu.addAction(action)
def show_help(self):
help_file_path = resource_path('help.md')
if os.path.exists(help_file_path):
try:
with open(help_file_path, 'r', encoding='utf-8') as file:
markdown_text = file.read()
# Convert markdown to HTML
import markdown
html_content = markdown.markdown(markdown_text)
# Display the HTML content in a HelpDialog
help_dialog = HelpDialog(html_content, self)
help_dialog.exec()
except Exception as e:
logging.error(f"Error reading help file: {e}")
QMessageBox.warning(self, "Error", "An error occurred while reading the help file.")
else:
QMessageBox.warning(self, "Error", "Help file not found. Please ensure 'help.md' is in the application directory.")
logging.error("Help file 'help.md' not found.")
def add_menu_actions(self):
save_action = self.file_menu.addAction("Save")
save_action.setShortcut("Ctrl+S")
save_action.triggered.connect(self.trigger_save_album_data)
save_as_action = self.file_menu.addAction("Save As...")
save_as_action.setShortcut("Ctrl+Shift+S")
save_as_action.triggered.connect(self.trigger_save_as_album_data)
open_action = self.file_menu.addAction("Open")
open_action.setShortcut("Ctrl+O")
open_action.triggered.connect(self.trigger_load_album_data)
close_action = self.file_menu.addAction("Close File")
close_action.setShortcut("Ctrl+W")
close_action.triggered.connect(self.close_album_data)
# Move the 'Recent Files' submenu to just after 'Close'
self.recent_files_menu = self.file_menu.addMenu("Recent Files")
self.update_recent_files_menu()
# Add a separator between 'Close' and 'Submit via Telegram'
self.file_menu.addSeparator()
self.submitAction = QAction("Submit via Telegram", self)
self.file_menu.addAction(self.submitAction)
self.submitAction.triggered.connect(self.openSubmitDialog)
# Add a separator between 'Submit via Telegram' and 'Add Album Manually' if desired
# self.file_menu.addSeparator()
self.manualAddAlbumAction = QAction("Add Album Manually", self)
self.file_menu.addAction(self.manualAddAlbumAction)
self.manualAddAlbumAction.triggered.connect(self.open_manual_add_album_dialog)
log_viewer_action = QAction("View Logs", self)
self.file_menu.addAction(log_viewer_action)
log_viewer_action.triggered.connect(self.open_log_viewer)
# Add a separator before 'Quit' to group it separately
self.file_menu.addSeparator()
# Quit action
quit_action = QAction("Quit", self)
quit_action.setShortcut("Ctrl+Q")
quit_action.triggered.connect(self.close_application)
self.file_menu.addAction(quit_action)
def close_application(self):
self.close()
def setup_tabs(self):
self.tabs = QTabWidget()
self.setCentralWidget(self.tabs)
self.album_list_tab = QWidget()
self.search_tab = QWidget()
self.settings_tab = QWidget()
self.tabs.addTab(self.album_list_tab, "Album List")
self.tabs.addTab(self.search_tab, "Search Albums")
self.tabs.addTab(self.settings_tab, "Settings")
self.setup_album_list_tab()
self.setup_search_tab()
self.setup_settings_tab()
# Set the current tab to the "Album List" tab
self.tabs.setCurrentWidget(self.album_list_tab)
def openSubmitDialog(self):
if self.dataChanged:
reply = QMessageBox.question(
self, 'Unsaved Changes',
"You have unsaved changes. Do you want to save them before submitting?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No | QMessageBox.StandardButton.Cancel
)
if reply == QMessageBox.StandardButton.Yes:
self.trigger_save_album_data()
elif reply == QMessageBox.StandardButton.Cancel:
return # Abort submission
if not self.current_file_path:
QMessageBox.warning(self, "No File Open", "Please open or save a file before attempting to submit.")
logging.warning("Submit attempted without an open file")
return
if not all([self.bot_token, self.chat_id, self.message_thread_id]):
QMessageBox.warning(self, "Configuration Error", "Telegram credentials are missing. Please update the Telegram settings.")
logging.error("Telegram credentials are missing.")
return
dialog = SubmitDialog(
bot_token=self.bot_token,
chat_id=self.chat_id,
message_thread_id=self.message_thread_id,
file_path=self.current_file_path,
parent=self
)
dialog.exec()
def get_user_data_path(self, filename, packaged=False):
"""Get a path to the user-specific application data directory for storing the given filename."""
app_name = 'SuSheApp'
if sys.platform == 'win32':
app_data_dir = os.path.join(os.getenv('APPDATA'), app_name)
elif sys.platform == 'darwin':
app_data_dir = os.path.join(os.path.expanduser('~/Library/Application Support/'), app_name)
else: # Linux and other Unix-like OSes
app_data_dir = os.path.join(os.path.expanduser('~'), '.SuSheApp')
if packaged:
# Use a subdirectory for packaged application settings
app_data_dir = os.path.join(app_data_dir, 'packaged')
if not os.path.exists(app_data_dir):
os.makedirs(app_data_dir) # Ensure directory is created
return os.path.join(app_data_dir, filename)
def dragEnterEvent(self, event: QDragEnterEvent):
if event.mimeData().hasUrls(): # Check if the drag event contains URLs
event.acceptProposedAction() # Accept the drag event
else:
event.ignore() # Ignore the drag event if it does not contain URLs
def dropEvent(self, event: QDropEvent):
urls = event.mimeData().urls() # Extract URLs from the event
for url in urls:
self.process_spotify_uri(url.toString()) # Process each URL
def setup_search_tab(self):
layout = QVBoxLayout()
search_label = QLabel("Search:")
layout.addWidget(search_label)
search_layout = QHBoxLayout()
self.search_input = QLineEdit()
search_layout.addWidget(self.search_input)
self.search_button = QPushButton("Search")
search_layout.addWidget(self.search_button)
self.search_button.clicked.connect(self.search_artist)
layout.addLayout(search_layout)
artist_label = QLabel("Artists:")
layout.addWidget(artist_label)
self.artist_list = QListWidget()
layout.addWidget(self.artist_list)
album_label = QLabel("Albums:")
layout.addWidget(album_label)
self.album_list = QListWidget()
layout.addWidget(self.album_list)
self.search_input.returnPressed.connect(self.search_artist)
self.artist_list.itemDoubleClicked.connect(self.display_artist_albums)
self.album_list.itemDoubleClicked.connect(self.fetch_album_details)
self.search_tab.setLayout(layout)
def setup_album_list_tab(self):
layout = QVBoxLayout()
self.album_table = QTableWidget()
self.album_table.setColumnCount(9)
self.album_table.setHorizontalHeaderLabels([
"Artist", "Album", "Release Date", "Cover Image",
"Country", "Genre 1", "Genre 2", "Rating", "Comments"
])
layout.addWidget(self.album_table)
# Create separate delegate instances for countries and genres
country_delegate = ComboBoxDelegate(self.countries, self.album_table)
self.genre_delegate_1 = GenreSearchDelegate(self.genres, self.album_table, highlight_color=Qt.GlobalColor.darkYellow)
self.genre_delegate_2 = GenreSearchDelegate(self.genres, self.album_table, highlight_color=Qt.GlobalColor.darkYellow)
rating_delegate = RatingDelegate(self.album_table)
# Assign delegates to respective columns
self.album_table.setItemDelegateForColumn(4, country_delegate) # 'Country' column
self.album_table.setItemDelegateForColumn(5, self.genre_delegate_1) # 'Genre 1' column
self.album_table.setItemDelegateForColumn(6, self.genre_delegate_2) # 'Genre 2' column
self.album_table.setItemDelegateForColumn(7, rating_delegate) # 'Rating' column
# Set the search highlight delegate for specified columns
self.search_delegate = SearchHighlightDelegate(self.album_table, highlight_color=Qt.GlobalColor.darkYellow)
for column in [0, 1, 8]: # Columns to search: Artist, Album, Comments
self.album_table.setItemDelegateForColumn(column, self.search_delegate)
# Connect signals
self.album_table.cellClicked.connect(self.handleCellClick)
self.album_table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.album_table.customContextMenuRequested.connect(self.show_context_menu)
# Enable sorting
self.album_table.setSortingEnabled(True)
# Set the column widths here
self.set_album_table_column_widths()
# Set the layout for the album list tab
self.album_list_tab.setLayout(layout)
# Connect additional signals
self.album_table.horizontalHeader().sortIndicatorChanged.connect(self.on_sort_order_changed)
self.album_table.itemChanged.connect(self.on_album_item_changed)
def on_album_item_changed(self, item):
# Get the row and column of the changed item
row = item.row()
column = item.column()
column_name = self.album_table.horizontalHeaderItem(column).text()
new_value = item.text()
# Get the artist and album name for context
artist = self.album_table.item(row, 0).text() if self.album_table.item(row, 0) else ""
album = self.album_table.item(row, 1).text() if self.album_table.item(row, 1) else ""
logging.info(f"Data changed in row {row}, column '{column_name}': '{artist}' - '{album}' set '{column_name}' to '{new_value}'")
self.dataChanged = True
self.update_window_title()
def on_sort_order_changed(self, column, order):
column_name = self.album_table.horizontalHeaderItem(column).text()
order_str = 'ascending' if order == Qt.SortOrder.AscendingOrder else 'descending'
logging.info(f"Album table sorted by column '{column_name}' in {order_str} order")
def set_album_table_column_widths(self):
# Set the desired column widths
self.album_table.setColumnWidth(0, 130) # "Artist" column
self.album_table.setColumnWidth(1, 200) # "Album" column
self.album_table.setColumnWidth(2, 100) # "Release Date" column
self.album_table.setColumnWidth(3, 100) # "Cover Image" column (adjusted width)
self.album_table.setColumnWidth(4, 150) # "Country" column
self.album_table.setColumnWidth(5, 170) # "Genre 1" column
self.album_table.setColumnWidth(6, 170) # "Genre 2" column
self.album_table.setColumnWidth(7, 65) # "Rating" column
self.album_table.setColumnWidth(8, 340) # "Comments" column
# Set fixed column sizes
header = self.album_table.horizontalHeader()
for i in range(self.album_table.columnCount()):
header.setSectionResizeMode(i, QHeaderView.ResizeMode.Fixed)
def set_static_row_heights(self):
for row in range(self.album_table.rowCount()):
self.album_table.setRowHeight(row, 100) # Adjust the row height as needed
def setup_settings_tab(self):
layout = QVBoxLayout()
# Existing Spotify API Credentials Help GroupBox
info_group_box = QGroupBox("Spotify API Credentials Help")
info_group_box_layout = QVBoxLayout()
# Information text
info_text = QLabel("Enter your Spotify API credentials below. You can obtain these credentials by registering your application in the Spotify Developer Dashboard.")
info_text.setWordWrap(True)
info_group_box_layout.addWidget(info_text)
# Spotify documentation link
link_text = '<a href="https://developer.spotify.com/documentation/web-api/tutorials/getting-started">Creating your own credentials</a>'
link_label = QLabel(link_text)
link_label.setOpenExternalLinks(True)
info_group_box_layout.addWidget(link_label)
info_group_box.setLayout(info_group_box_layout)
layout.addWidget(info_group_box)
layout.addSpacing(30)
# Spotify Credentials GroupBox
spotify_credentials_group_box = QGroupBox("Spotify API Credentials")
spotify_credentials_layout = QVBoxLayout()
spotify_credentials_layout.setContentsMargins(10, 10, 10, 10)
# Client ID input
client_id_label = QLabel("Client ID:")
spotify_credentials_layout.addWidget(client_id_label)
self.client_id_input = QLineEdit()
spotify_credentials_layout.addWidget(self.client_id_input)
# Client Secret input
client_secret_label = QLabel("Client Secret:")
spotify_credentials_layout.addWidget(client_secret_label)
self.client_secret_input = QLineEdit()
spotify_credentials_layout.addWidget(self.client_secret_input)
# Save Spotify Settings Button
save_spotify_button = QPushButton("Save Spotify Settings")
spotify_credentials_layout.addWidget(save_spotify_button)
save_spotify_button.clicked.connect(self.save_credentials)
spotify_credentials_group_box.setLayout(spotify_credentials_layout)
layout.addWidget(spotify_credentials_group_box)
layout.addSpacing(30)
# Telegram settings group box
telegram_group_box = QGroupBox("Telegram Submission Settings")
telegram_layout = QVBoxLayout()
# Bot Token Input
bot_token_label = QLabel("Bot Token:")
telegram_layout.addWidget(bot_token_label)
self.bot_token_input = QLineEdit()
telegram_layout.addWidget(self.bot_token_input)
# Chat ID Input
chat_id_label = QLabel("Chat ID:")
telegram_layout.addWidget(chat_id_label)
self.chat_id_input = QLineEdit()
telegram_layout.addWidget(self.chat_id_input)
# Message Thread ID Input
message_thread_id_label = QLabel("Message Thread ID:")
telegram_layout.addWidget(message_thread_id_label)
self.message_thread_id_input = QLineEdit()
telegram_layout.addWidget(self.message_thread_id_input)
# Save Telegram Settings Button
save_telegram_button = QPushButton("Save Telegram Settings")
telegram_layout.addWidget(save_telegram_button)
save_telegram_button.clicked.connect(self.save_telegram_settings)
telegram_group_box.setLayout(telegram_layout)
layout.addWidget(telegram_group_box)
layout.addSpacing(30)
# Application Settings GroupBox
app_settings_group_box = QGroupBox("Application Settings")
app_settings_layout = QVBoxLayout()
# Preferred Music Player Setting
preferred_music_player_label = QLabel("Preferred Music Player:")
app_settings_layout.addWidget(preferred_music_player_label)
self.preferred_music_player_combo = QComboBox()
self.preferred_music_player_combo.addItems(["Spotify", "Tidal"])
app_settings_layout.addWidget(self.preferred_music_player_combo)
# Save Application Settings Button
save_app_settings_button = QPushButton("Save Application Settings")
app_settings_layout.addWidget(save_app_settings_button)
save_app_settings_button.clicked.connect(self.save_application_settings)
app_settings_group_box.setLayout(app_settings_layout)
layout.addWidget(app_settings_group_box)
layout.addStretch()
self.settings_tab.setLayout(layout)
def load_config_section(self, section_name):
config_path = resource_path('config.json')
try:
if os.path.exists(config_path):
with open(config_path, 'r') as file:
config = json.load(file)
return config.get(section_name, {})
else:
return {}
except json.JSONDecodeError as e:
logging.error(f"Error parsing config.json: {e}")
return {}
def save_config_section(self, section_name, data):
config_path = resource_path('config.json')
try:
if os.path.exists(config_path):
with open(config_path, 'r') as file:
config = json.load(file)
else:
config = {}
config[section_name] = data
with open(config_path, 'w') as file:
json.dump(config, file, indent=4)
logging.info(f"{section_name.capitalize()} settings saved successfully.")
except Exception as e:
logging.error(f"Failed to save {section_name} settings: {e}")
raise e # Re-raise exception for the calling method to handle
def save_credentials(self):
spotify_settings = {
"client_id": self.client_id_input.text().strip(),
"client_secret": self.client_secret_input.text().strip()
}
try:
self.save_config_section('spotify', spotify_settings)
self.client_id = spotify_settings["client_id"]
self.client_secret = spotify_settings["client_secret"]
QMessageBox.information(self, "Success", "Spotify settings saved successfully.")
except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to save Spotify settings. Details: {e}")
def save_telegram_settings(self):
telegram_settings = {
"bot_token": self.bot_token_input.text().strip(),
"chat_id": self.chat_id_input.text().strip(),
"message_thread_id": self.message_thread_id_input.text().strip()
}
try:
self.save_config_section('telegram', telegram_settings)
self.bot_token = telegram_settings["bot_token"]
self.chat_id = telegram_settings["chat_id"]
self.message_thread_id = telegram_settings["message_thread_id"]
QMessageBox.information(self, "Success", "Telegram settings saved successfully.")
except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to save Telegram settings. Details: {e}")
def save_application_settings(self):
preferred_music_player = self.preferred_music_player_combo.currentText()
app_settings = {
"preferred_music_player": preferred_music_player
}
try: