-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdynamiX.py
1688 lines (1410 loc) · 72.4 KB
/
dynamiX.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 os
import sys
import time
import threading
import logging
import random
import json
import queue
import traceback
from datetime import datetime, timedelta
from xml.etree import ElementTree as ET
import tkinter as tk
from tkinter import ttk, messagebox
from tkinter import font as tkfont
from ttkbootstrap import Style
from plexapi.server import PlexServer
import requests
# ------------------------------ Constants and Configuration ------------------------------
# Define file paths for logs and configuration
LOG_DIR = 'logs'
LOG_FILE = os.path.join(LOG_DIR, 'DynamiX.log')
CONFIG_FILE = 'config.json'
USED_COLLECTIONS_FILE = 'used_collections.json'
USER_EXEMPTIONS_FILE = 'user_exemptions.json'
# Ensure the logs directory exists
os.makedirs(LOG_DIR, exist_ok=True)
# Configure logging to file and stdout
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(message)s',
handlers=[
logging.FileHandler(LOG_FILE, mode='w', encoding='utf-8'),
logging.StreamHandler(sys.stdout)
]
)
# ------------------------------ Helper Functions ------------------------------
def apply_pinning(collection, pinning_targets, action="promote"):
"""
Apply pinning or unpinning based on user-selected targets.
:param collection: The Plex collection object.
:param pinning_targets: A dictionary indicating the selected pinning targets.
:param action: Either 'promote' or 'demote'.
"""
try:
hub = collection.visibility()
if action == "promote":
if pinning_targets.get("library_recommended", False):
hub.promoteRecommended()
if pinning_targets.get("home", False):
hub.promoteHome()
if pinning_targets.get("shared_home", False):
hub.promoteShared()
elif action == "demote":
if pinning_targets.get("library_recommended", False):
hub.demoteRecommended()
if pinning_targets.get("home", False):
hub.demoteHome()
if pinning_targets.get("shared_home", False):
hub.demoteShared()
except Exception as e:
logging.error(f"Error during {action} for collection '{collection.title}': {e}")
def sanitize_time_blocks(time_blocks):
"""
Ensure time_blocks is properly formatted as a dictionary.
"""
if not isinstance(time_blocks, dict):
logging.warning(f"Sanitizing time_blocks: expected dict but got {type(time_blocks)}. Resetting to empty.")
return {}
sanitized = {}
for day, blocks in time_blocks.items():
if not isinstance(blocks, dict):
logging.warning(f"Invalid blocks for day '{day}': resetting to empty dictionary.")
sanitized[day] = {}
else:
sanitized[day] = blocks
return sanitized
def load_config():
"""
Load configuration from the CONFIG_FILE.
"""
if not os.path.exists(CONFIG_FILE):
logging.error(f"Configuration file '{CONFIG_FILE}' not found. Creating a default configuration.")
return {}
try:
with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
config = json.load(f)
except json.JSONDecodeError:
logging.error(f"Configuration file '{CONFIG_FILE}' is empty or invalid. Resetting to default.")
return {}
# Sanitize libraries_settings and time_blocks
libraries_settings = config.get("libraries_settings", {})
if not isinstance(libraries_settings, dict):
logging.warning(f"Sanitizing libraries_settings: resetting to empty dictionary.")
libraries_settings = {}
for library, settings in libraries_settings.items():
time_blocks = settings.get("time_blocks", {})
settings["time_blocks"] = sanitize_time_blocks(time_blocks)
config["libraries_settings"] = libraries_settings
# Ensure seasonal_blocks is a list
if "seasonal_blocks" not in config or not isinstance(config["seasonal_blocks"], list):
config["seasonal_blocks"] = []
return config
def save_config(config):
"""
Save the configuration dictionary to CONFIG_FILE.
"""
try:
logging.info(f"Final configuration to save: {json.dumps(config, indent=4)}")
with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
json.dump(config, f, indent=4, ensure_ascii=False)
logging.info("Configuration file saved successfully.")
except Exception as e:
logging.error(f"Error saving configuration file: {e}")
raise
def load_used_collections():
"""
Load used collections from USED_COLLECTIONS_FILE.
"""
if not os.path.exists(USED_COLLECTIONS_FILE):
return {}
with open(USED_COLLECTIONS_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
def save_used_collections(used_collections):
"""
Save used collections to USED_COLLECTIONS_FILE.
"""
with open(USED_COLLECTIONS_FILE, 'w', encoding='utf-8') as f:
json.dump(used_collections, f, ensure_ascii=False, indent=4)
logging.info("Used collections file saved.")
def load_user_exemptions():
"""
Load user exemptions from USER_EXEMPTIONS_FILE.
"""
if not os.path.exists(USER_EXEMPTIONS_FILE):
return []
with open(USER_EXEMPTIONS_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
def save_user_exemptions(user_exemptions):
"""
Save user exemptions to USER_EXEMPTIONS_FILE.
"""
with open(USER_EXEMPTIONS_FILE, 'w', encoding='utf-8') as f:
json.dump(user_exemptions, f, ensure_ascii=False, indent=4)
logging.info("User exemptions file saved.")
def reset_exclusion_list_file():
"""
Reset the exclusion list by clearing USED_COLLECTIONS_FILE.
"""
with open(USED_COLLECTIONS_FILE, 'w', encoding='utf-8') as f:
f.write("{}")
logging.info("Exclusion list file has been reset.")
def connect_to_plex(config):
"""
Connect to the Plex server using the provided configuration.
"""
logging.info("Connecting to Plex server...")
plex = PlexServer(config['plex_url'], config['plex_token'])
logging.info("Connected to Plex server successfully.")
return plex
def handle_new_episodes_pinning(plex, libraries, always_pin_new_episodes, pinning_targets):
"""
Handle pinning or unpinning of 'New Episodes' collections based on configuration.
"""
logging.info("Handling 'New Episodes' collections...")
for library_name in libraries:
try:
library = plex.library.section(library_name)
for collection in library.collections():
if collection.title.lower() == "new episodes":
if always_pin_new_episodes:
apply_pinning(collection, pinning_targets, action="promote")
logging.info(f"'New Episodes' collection pinned in '{library_name}'.")
else:
apply_pinning(collection, pinning_targets, action="demote")
logging.info(f"'New Episodes' collection unpinned in '{library_name}'.")
break
except Exception as e:
logging.error(f"Error accessing library '{library_name}': {e}")
def unpin_collections(plex, libraries, always_pin_new_episodes, pinning_targets):
"""
Unpin all collections except 'New Episodes' if always_pin_new_episodes is True.
"""
logging.info("Unpinning currently pinned collections...")
for library_name in libraries:
try:
library = plex.library.section(library_name)
for collection in library.collections():
if always_pin_new_episodes and collection.title.lower() == "new episodes":
continue # Skip unpinning 'New Episodes' if always_pin_new_episodes is enabled
apply_pinning(collection, pinning_targets, action="demote")
logging.info(f"Collection '{collection.title}' unpinned in '{library_name}'.")
except Exception as e:
logging.error(f"Error accessing library '{library_name}': {e}")
def log_and_update_exclusion_list(previous_pinned, used_collections, exclusion_days):
"""
Log pinned collections and update the exclusion list with their expiration dates.
"""
current_date = datetime.now().date()
for collection in previous_pinned:
expiration_date = (current_date + timedelta(days=exclusion_days)).strftime('%Y-%m-%d')
used_collections[collection.title] = expiration_date
logging.info(f"Added '{collection.title}' to exclusion list (expires: {expiration_date}).")
save_used_collections(used_collections)
def get_current_time_block(config, library_name):
"""
Determine the current time block and its corresponding limit for a given library.
"""
now = datetime.now()
current_day = now.strftime("%A") # e.g., "Monday"
current_time = now.strftime("%H:%M")
library_settings = config.get("libraries_settings", {}).get(library_name, {})
time_blocks = library_settings.get("time_blocks", {})
default_limits = config.get("default_limits", {})
library_default_limit = default_limits.get(library_name, 5)
day_blocks = time_blocks.get(current_day, {})
if not isinstance(day_blocks, dict):
logging.error(f"Invalid time_blocks for day '{current_day}' in library '{library_name}'")
return "Default", library_default_limit
for block, details in day_blocks.items():
if details.get("start_time") <= current_time < details.get("end_time"):
return block, details.get("limit", library_default_limit)
return "Default", library_default_limit
def pin_seasonal_blocks(plex, seasonal_blocks):
"""
Pin specific collections based on active seasonal blocks.
Month and day are compared without considering the year.
"""
current_date = datetime.now().date()
current_month_day = (current_date.month, current_date.day)
pinned_collections = []
for block in seasonal_blocks:
# Parse start and end dates (MM-DD)
try:
start_month, start_day = map(int, block["start_date"].split("-"))
end_month, end_day = map(int, block["end_date"].split("-"))
except Exception as e:
logging.error(f"Invalid seasonal block dates for block '{block.get('name', 'Unnamed')}': {e}")
continue
start_month_day = (start_month, start_day)
end_month_day = (end_month, end_day)
# Handle date ranges that may wrap around the year (e.g., Dec 15 - Jan 10)
if start_month_day <= end_month_day:
is_active = (start_month_day <= current_month_day <= end_month_day)
else:
# Spans year-end
is_active = (current_month_day >= start_month_day or current_month_day <= end_month_day)
if is_active:
collection_name = block.get("collection")
libraries = block.get("libraries", [])
logging.info(f"Activating seasonal block '{block['name']}' for collection '{collection_name}'.")
for library_name in libraries:
try:
library = plex.library.section(library_name)
collection = next((c for c in library.collections() if c.title == collection_name), None)
if collection:
hub = collection.visibility()
hub.promoteHome()
hub.promoteShared()
logging.info(f"Pinned collection '{collection_name}' in library '{library_name}' due to seasonal block '{block['name']}'.")
pinned_collections.append(collection)
else:
logging.warning(f"Collection '{collection_name}' not found in library '{library_name}'.")
except Exception as e:
logging.error(f"Error processing library '{library_name}': {e}")
return pinned_collections
# ------------------------------ Main Automation Function ------------------------------
def main(gui_instance=None, stop_event=None):
logging.info("Starting DynamiX automation...")
try:
# Load configuration
config = load_config()
if not config:
logging.error("Configuration could not be loaded. Exiting.")
return
logging.info("Configuration loaded successfully.")
# Connect to Plex server
plex = connect_to_plex(config)
# Retrieve configuration settings
libraries = config.get("libraries", [])
min_items = config.get("minimum_items", 1)
exclusion_days = config.get("exclusion_days", 3)
always_pin_new_episodes = config.get("always_pin_new_episodes", False)
pinning_interval = config.get("pinning_interval", 30) * 60 # Convert minutes to seconds
# Seasonal blocks
seasonal_blocks = config.get("seasonal_blocks", [])
# Load persistent state
used_collections = load_used_collections()
user_exemptions = load_user_exemptions()
sys_random = random.SystemRandom()
logging.info("Entering main automation loop.")
while not stop_event.is_set():
current_date = datetime.now().date()
# 1: Clean up expired exclusions
logging.info("Cleaning up expired exclusions...")
used_collections = {
name: date for name, date in used_collections.items()
if datetime.strptime(date, '%Y-%m-%d').date() > current_date
}
save_used_collections(used_collections)
logging.info("Updated exclusion list.")
# Retrieve pinning targets from config
pinning_targets = config.get("pinning_targets", {})
# Handle 'New Episodes' pinning based on preferences
handle_new_episodes_pinning(plex, libraries, always_pin_new_episodes, pinning_targets)
# Unpin collections based on preferences
unpin_collections(plex, libraries, always_pin_new_episodes, pinning_targets)
# 4: Pin seasonal blocks (if active)
pinned_seasonal = pin_seasonal_blocks(plex, seasonal_blocks)
# Seasonal blocks now do NOT skip normal logic; they are pinned like 'New Episodes'.
# 5: Proceed with normal time-block based pinning
logging.info("Proceeding with time block-based pinning after seasonal blocks...")
previous_pinned = []
reset_needed = False
for library_name in libraries:
try:
logging.info(f"Processing library: {library_name}")
library = plex.library.section(library_name)
collections = library.collections()
# Determine the current time block and limit
current_block, current_limit = get_current_time_block(config, library_name)
logging.info(f"Library '{library_name}' - Time Block: {current_block}, Limit: {current_limit}")
# Filter valid collections for pinning
valid_collections = [
collection for collection in collections
if len(collection.items()) >= min_items
and collection.title not in used_collections
and collection.title not in user_exemptions
]
if len(valid_collections) < current_limit:
logging.warning(
f"Not enough valid collections for '{library_name}'. "
f"Required: {current_limit}, Available: {len(valid_collections)}."
)
continue
# Select collections to pin based on the limit
collections_to_pin = random.sample(valid_collections, current_limit)
for collection in collections_to_pin:
apply_pinning(collection, pinning_targets, action="promote")
logging.info(f"Collection '{collection.title}' pinned in '{library_name}'.")
previous_pinned.append(collection)
except Exception as e:
logging.error(f"Error processing library '{library_name}': {e}")
if reset_needed:
if gui_instance:
logging.info("Resetting exclusion list due to insufficient collections.")
gui_instance.reset_exclusion_list()
used_collections = load_used_collections() # Reload after reset
else:
reset_exclusion_list_file()
used_collections = {}
continue # Restart loop
# 6: Log exclusions for normally pinned collections (seasonal blocks are treated like New Episodes and not excluded)
if previous_pinned:
log_and_update_exclusion_list(previous_pinned, used_collections, exclusion_days)
else:
logging.info("No new normal collections were pinned in this iteration.")
# GUI update scheduling (if applicable)
if gui_instance:
gui_instance.after(0, gui_instance.refresh_exclusion_list)
# Sleep for the configured pinning interval
logging.info(f"Sleeping for {pinning_interval // 60} minutes before next iteration.")
time.sleep(pinning_interval)
except Exception as e:
logging.error(f"An error occurred: {e}")
traceback.print_exc()
finally:
logging.info("Automation script terminated.")
# ------------------------------ Custom Logging Handler ------------------------------
class GuiHandler(logging.Handler):
"""
Custom logging handler for displaying logs in the GUI using a queue.
"""
def __init__(self, log_queue):
super().__init__()
self.log_queue = log_queue
def emit(self, record):
msg = self.format(record)
self.log_queue.put(msg)
# ------------------------------ Scrollable Frame Class ------------------------------
class ScrollableFrame(ttk.Frame):
"""
A scrollable frame that adjusts its content dynamically with mousewheel support.
"""
def __init__(self, container, *args, **kwargs):
super().__init__(container, *args, **kwargs)
self.canvas = tk.Canvas(self, highlightthickness=0)
self.scrollbar = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.scrollable_frame = ttk.Frame(self.canvas)
self.scrollable_frame.bind(
"<Configure>",
lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all"))
)
self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
self.canvas.configure(yscrollcommand=self.scrollbar.set)
self.canvas.pack(side="left", fill="both", expand=True)
self.scrollbar.pack(side="right", fill="y")
# Mousewheel binding
self.canvas.bind("<Enter>", self._bind_mousewheel)
self.canvas.bind("<Leave>", self._unbind_mousewheel)
def display_widget(self):
"""
Returns the frame for adding child widgets.
"""
return self.scrollable_frame
def _bind_mousewheel(self, event):
"""
Binds the mousewheel to the canvas for scrolling.
"""
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
def _unbind_mousewheel(self, event):
"""
Unbinds the mousewheel to prevent interaction when not in focus.
"""
self.canvas.unbind_all("<MouseWheel>")
def _on_mousewheel(self, event):
"""
Handles mousewheel scrolling.
"""
self.canvas.yview_scroll(-1 * (event.delta // 120), "units")
# ------------------------------ Seasonal Block Dialog ------------------------------
class SeasonalBlockDialog(tk.Toplevel):
"""
A dialog for adding/editing seasonal blocks with MM-DD date format.
"""
def __init__(self, parent, title="Add Seasonal Block", block=None, callback=None):
super().__init__(parent)
self.title(title)
self.geometry("400x300")
self.resizable(False, False)
self.block = block
self.callback = callback
self.parent = parent
# Widgets
ttk.Label(self, text="Block Name:").grid(row=0, column=0, padx=10, pady=5, sticky="e")
self.name_entry = ttk.Entry(self, width=30)
self.name_entry.grid(row=0, column=1, padx=10, pady=5)
ttk.Label(self, text="Start Date (MM-DD):").grid(row=1, column=0, padx=10, pady=5, sticky="e")
self.start_date_entry = ttk.Entry(self, width=30)
self.start_date_entry.grid(row=1, column=1, padx=10, pady=5)
ttk.Label(self, text="End Date (MM-DD):").grid(row=2, column=0, padx=10, pady=5, sticky="e")
self.end_date_entry = ttk.Entry(self, width=30)
self.end_date_entry.grid(row=2, column=1, padx=10, pady=5)
ttk.Label(self, text="Libraries (comma-separated):").grid(row=3, column=0, padx=10, pady=5, sticky="e")
self.libraries_entry = ttk.Entry(self, width=30)
self.libraries_entry.grid(row=3, column=1, padx=10, pady=5)
ttk.Label(self, text="Collection Name:").grid(row=4, column=0, padx=10, pady=5, sticky="e")
self.collection_entry = ttk.Entry(self, width=30)
self.collection_entry.grid(row=4, column=1, padx=10, pady=5)
# Buttons
button_frame = ttk.Frame(self)
button_frame.grid(row=5, column=0, columnspan=2, pady=10)
ttk.Button(button_frame, text="Save", command=self.save_block).pack(side="left", padx=5)
ttk.Button(button_frame, text="Cancel", command=self.destroy).pack(side="left", padx=5)
# Pre-fill if editing
if self.block:
self.name_entry.insert(0, self.block.get("name", ""))
self.start_date_entry.insert(0, self.block.get("start_date", ""))
self.end_date_entry.insert(0, self.block.get("end_date", ""))
self.libraries_entry.insert(0, ", ".join(self.block.get("libraries", [])))
self.collection_entry.insert(0, self.block.get("collection", ""))
def save_block(self):
name = self.name_entry.get().strip()
start_date = self.start_date_entry.get().strip()
end_date = self.end_date_entry.get().strip()
libs_str = self.libraries_entry.get().strip()
collection = self.collection_entry.get().strip()
if not (name and start_date and end_date and collection):
messagebox.showerror("Error", "Name, Start Date, End Date, and Collection fields are required.")
return
# Validate date format MM-DD
if not self._validate_mm_dd(start_date) or not self._validate_mm_dd(end_date):
messagebox.showerror("Error", "Invalid date format. Use MM-DD.")
return
libraries = [l.strip() for l in libs_str.split(",") if l.strip()]
new_block = {
"name": name,
"start_date": start_date, # MM-DD format
"end_date": end_date, # MM-DD format
"libraries": libraries,
"collection": collection
}
if self.callback:
self.callback(new_block)
self.destroy()
def _validate_mm_dd(self, date_str):
try:
datetime.strptime(date_str, "%m-%d")
return True
except ValueError:
return False
# ------------------------------ GUI Application Class ------------------------------
class DynamiXGUI(tk.Tk):
"""
The main GUI application for DynamiX - Plex Recommendations Manager.
"""
def __init__(self):
super().__init__()
self.title("DynamiX - Plex Recommendations Manager")
self.geometry("920x875")
self.resizable(False, False)
icon_path = os.path.join("resources", "myicon.ico")
if os.path.exists(icon_path):
self.iconbitmap(icon_path)
self.center_window(920, 875)
self.style = Style(theme="darkly")
self.configure(bg="black")
self.script_thread = None
self.stop_event = threading.Event() # Event to signal stopping the script
self.config = load_config() or {}
self.user_exemptions = load_user_exemptions() or []
self.user_exemption_checkboxes = {}
self.select_all_vars = {} # Added for "Select All" functionality
self.plex = None
self.log_queue = queue.Queue() # Queue for log messages
self.default_font = tkfont.Font(family="Segoe UI", size=30)
self.create_widgets()
self.refresh_user_exemptions()
self.refresh_exclusion_list()
def center_window(self, width, height):
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
x_position = (screen_width // 2) - (width // 2)
y_position = (screen_height // 2) - (height // 2)
self.geometry(f"{width}x{height}+{x_position}+{y_position}")
def create_widgets(self):
self.tab_control = ttk.Notebook(self)
self.server_tab = ttk.Frame(self.tab_control)
self.settings_tab = ttk.Frame(self.tab_control)
self.logs_tab = ttk.Frame(self.tab_control)
self.exclusion_tab = ttk.Frame(self.tab_control)
self.user_exemptions_tab = ttk.Frame(self.tab_control)
if self._has_missing_fields():
self.missing_info_tab = ttk.Frame(self.tab_control)
self.tab_control.add(self.missing_info_tab, text="Missing Configuration Information")
self._create_missing_info_tab()
self.tab_control.add(self.logs_tab, text="Logs")
self.tab_control.add(self.exclusion_tab, text="Dynamic Exclusions")
self.tab_control.add(self.user_exemptions_tab, text="User-Set Exemptions")
self.tab_control.add(self.server_tab, text="Plex Server Config")
self.tab_control.add(self.settings_tab, text="Settings")
self.tab_control.pack(expand=True, fill="both")
self._create_server_tab()
self._create_settings_tab()
self._create_logs_tab()
self._create_exclusion_tab()
self._create_user_exemptions_tab()
def _has_missing_fields(self):
required_fields = ["plex_url", "plex_token", "libraries", "pinning_interval"]
for field in required_fields:
if field not in self.config or not self.config[field]:
return True
return False
def _create_missing_info_tab(self):
frame = ttk.Frame(self.missing_info_tab, padding=10)
frame.pack(fill="both", expand=True)
ttk.Label(frame, text="Fill in Missing Configuration Fields", font=("Segoe UI", 16, "bold")).pack(pady=10)
self.missing_fields_frame = ttk.Frame(frame)
self.missing_fields_frame.pack(fill="both", expand=True, pady=10)
self.missing_entries = {}
self._populate_missing_fields()
if "plex_token" in self.missing_entries:
plex_token_explanation = (
"\nHow to Find Your Plex Token (Easier Method):\n\n"
"1. Open the Plex Web App in your browser and log into your Plex server.\n"
"2. Select any movie or episode.\n"
"3. Click the 'Get Info' button (3 dot icon) for that item.\n"
"4. Select 'View XML'.\n"
"5. Your Plex token appears at the end of the URL after 'X-Plex-Token='.\n"
)
explanation_frame = ttk.Frame(frame)
explanation_frame.pack(expand=True, fill="both", pady=(0, 10))
ttk.Label(
explanation_frame, text=plex_token_explanation,
font=("Segoe UI", 9, "italic"), foreground="yellow",
wraplength=800, justify="center", anchor="center"
).pack(expand=True, fill="both", anchor='center')
save_button = ttk.Button(frame, text="Save Missing Information", command=self._save_missing_fields)
save_button.pack(pady=10)
def _populate_missing_fields(self):
for widget in self.missing_fields_frame.winfo_children():
widget.destroy()
self.missing_entries = {}
required_fields = {
"plex_url": "URL of your Plex server (Can't be 'localhost')",
"plex_token": "Token for accessing your Plex server",
"libraries": "Comma-separated list of libraries to manage",
"pinning_interval": "Time interval (in minutes) for pinning"
}
self.missing_fields_frame.grid_columnconfigure(0, weight=1)
self.missing_fields_frame.grid_columnconfigure(1, weight=2)
self.missing_fields_frame.grid_columnconfigure(2, weight=1)
row = 0
for key, description in required_fields.items():
if key not in self.config or not self.config[key]:
ttk.Label(
self.missing_fields_frame,
text=f"{key.replace('_', ' ').title()}:",
font=("Segoe UI", 12)
).grid(row=row, column=1, sticky="w", pady=5, padx=50)
entry = ttk.Entry(self.missing_fields_frame, width=40)
entry.grid(row=row, column=1, pady=5, padx=50)
entry.configure(justify="center")
ttk.Label(
self.missing_fields_frame,
text=f"({description})",
font=("Segoe UI", 10, "italic"),
foreground="gray"
).grid(row=row + 1, column=1, sticky="w", pady=2, padx=50)
self.missing_entries[key] = entry
row += 2
if not self.missing_entries:
ttk.Label(
self.missing_fields_frame,
text="No missing configuration fields detected!",
font=("Segoe UI", 12, "italic")
).grid(row=row, column=1, pady=20)
def _save_missing_fields(self):
try:
for key, widget in self.missing_entries.items():
value = widget.get().strip()
if key == "libraries":
self.config[key] = [lib.strip() for lib in value.split(",") if lib.strip()]
elif key == "pinning_interval":
self.config[key] = int(value) if value.isdigit() else 30
else:
self.config[key] = value
save_config(self.config)
messagebox.showinfo("Success", "Missing information saved successfully! Restarting the application...")
logging.info("Missing configuration fields updated. Restarting...")
self.restart_program()
except Exception as e:
logging.error(f"Error saving missing configuration fields: {e}")
messagebox.showerror("Error", f"Failed to save missing information: {e}")
def _create_server_tab(self):
frame = ttk.Frame(self.server_tab, padding="10", style="TFrame")
frame.pack(fill="both", expand=True)
for i in range(7):
frame.grid_rowconfigure(i, weight=0)
frame.grid_rowconfigure(0, weight=1)
frame.grid_rowconfigure(6, weight=1)
frame.grid_columnconfigure(0, weight=1)
frame.grid_columnconfigure(1, weight=1)
ttk.Label(
frame,
text="Plex Server Configuration",
font=("Segoe UI", 30, "bold"),
bootstyle="warning"
).grid(row=1, column=0, columnspan=2, pady=10)
ttk.Label(frame, text="Plex URL (Can't be 'localhost'):", font=("Segoe UI", 12)).grid(row=2, column=0, sticky="e", padx=10, pady=5)
self.plex_url_entry = ttk.Entry(frame, width=50)
self.plex_url_entry.grid(row=2, column=1, sticky="w", padx=10, pady=5)
self.plex_url_entry.insert(0, self.config.get("plex_url", ""))
ttk.Label(frame, text="Plex Token:", font=("Segoe UI", 12)).grid(row=3, column=0, sticky="e", padx=10, pady=5)
self.plex_token_entry = ttk.Entry(frame, width=50, show="*")
self.plex_token_entry.grid(row=3, column=1, sticky="w", padx=10, pady=5)
self.plex_token_entry.insert(0, self.config.get("plex_token", ""))
plex_token_explanation = (
"\nHow to Find Your Plex Token:\n\n"
"1. In the Plex Web App, navigate to a movie or TV episode.\n"
"2. Click 'Get Info', then 'View XML'.\n"
"3. Your token is at the end of the URL after 'X-Plex-Token='."
)
explanation_label = ttk.Label(
frame,
text=plex_token_explanation,
font=("Segoe UI", 9, "italic"),
foreground="yellow",
wraplength=600,
justify="center",
anchor="center"
)
explanation_label.grid(row=4, column=0, columnspan=2, sticky="ew", padx=10, pady=(0, 20))
ttk.Button(
frame,
text="Save Configuration",
command=self._save_and_refresh_server_name,
bootstyle="warning"
).grid(row=5, column=0, columnspan=2, pady=20)
self.server_name_label = ttk.Label(
frame,
text="Server Name: Fetching...",
font=("Segoe UI", 20, "bold"),
bootstyle="warning"
)
self.server_name_label.grid(row=6, column=0, columnspan=2, pady=10)
self._fetch_and_display_server_name()
def _save_and_refresh_server_name(self):
self.save_server_config()
self._fetch_and_display_server_name()
def save_server_config(self):
try:
plex_url = self.plex_url_entry.get().strip()
plex_token = self.plex_token_entry.get().strip()
if not plex_url or not plex_token:
messagebox.showerror("Error", "Plex URL and Token cannot be empty.")
return
self.config["plex_url"] = plex_url
self.config["plex_token"] = plex_token
save_config(self.config)
messagebox.showinfo("Success", "Plex server configuration saved successfully.")
logging.info("Plex server configuration saved.")
except Exception as e:
logging.error(f"Error saving Plex server configuration: {e}")
messagebox.showerror("Error", f"Failed to save Plex server configuration: {e}")
def _fetch_and_display_server_name(self):
plex_url = self.plex_url_entry.get()
plex_token = self.plex_token_entry.get()
if plex_url and plex_token:
try:
response = requests.get(f"{plex_url}/?X-Plex-Token={plex_token}", timeout=10)
if response.status_code == 200:
root = ET.fromstring(response.content)
server_name = root.attrib.get("friendlyName", "Unknown Server")
self.server_name_label.config(text=f"Server Name: {server_name}")
else:
self.server_name_label.config(text="Server Name: Unable to fetch")
except Exception as e:
self.server_name_label.config(text=f"Server Name: Error fetching ({str(e)})")
else:
self.server_name_label.config(text="Server Name: Missing URL or Token")
def _add_general_field(self, parent_frame, label_text, start_row, config_key, explanation=""):
ttk.Label(parent_frame, text=label_text).grid(row=start_row, column=0, sticky="w", padx=10, pady=5)
value = self.config.get(config_key, "")
if config_key == "libraries" and isinstance(value, list):
value = ", ".join(value)
entry = ttk.Entry(parent_frame, width=50)
entry.grid(row=start_row, column=1, sticky="w", padx=10, pady=5)
entry.insert(0, value)
setattr(self, f"{config_key}_entry", entry)
next_row = start_row + 1
if explanation:
ttk.Label(
parent_frame,
text=explanation,
font=("Segoe UI", 9, "italic"),
foreground="yellow",
wraplength=600
).grid(row=next_row, column=0, columnspan=2, sticky="w", padx=10, pady=(0, 10))
next_row += 1
else:
next_row += 1
return next_row
def _create_settings_tab(self):
container = ttk.Frame(self.settings_tab)
container.pack(fill="both", expand=True)
canvas = tk.Canvas(container, highlightthickness=0)
scrollbar = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas)
canvas.create_window((0, 0), window=scrollable_frame, anchor="n", width=900)
canvas.configure(yscrollcommand=scrollbar.set)
scrollable_frame.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
def _on_mousewheel(event):
canvas.yview_scroll(-1 * (event.delta // 120), "units")
canvas.bind("<Enter>",
lambda e: self.exemptions_canvas.bind_all("<MouseWheel>", _on_mousewheel))
canvas.bind("<Leave>", lambda e: self.exemptions_canvas.unbind_all("<MouseWheel>"))
ttk.Label(scrollable_frame, text="Settings", font=("Segoe UI", 24, "bold")).pack(pady=20)
save_settings_button = ttk.Button(
scrollable_frame,
text="Save Settings",
command=self.save_settings,
bootstyle="warning"
)
save_settings_button.pack(pady=10, padx=20, fill="x")
# General Config
general_config_frame = ttk.LabelFrame(scrollable_frame, text="General Configuration", padding=10)
general_config_frame.pack(fill="x", padx=20, pady=10)
current_row = 0
current_row = self._add_general_field(
general_config_frame,
"Library Names (comma-separated):",
current_row,
"libraries",
explanation="A comma-separated list of Plex libraries to manage."
)
current_row = self._add_general_field(
general_config_frame,
"Pinning Program Run Interval (minutes):",
current_row,
"pinning_interval",
explanation="How often the script attempts to pin/unpin collections."
)
current_row = self._add_general_field(
general_config_frame,
"Days to Exclude Collections after Pinning:",
current_row,
"exclusion_days",
explanation="Number of days a pinned collection is excluded from re-pinning."
)
current_row = self._add_general_field(
general_config_frame,
"Minimum Items for Valid Collection:",
current_row,
"minimum_items",
explanation="Minimum items required in a collection to be considered for pinning."
)
self.new_episodes_var = tk.BooleanVar(value=self.config.get("always_pin_new_episodes", False))
ttk.Checkbutton(
general_config_frame,
text="Always Pin 'New Episodes' if Available as a Collection",
variable=self.new_episodes_var
).grid(row=current_row, column=0, columnspan=2, sticky="w", padx=10, pady=5)
current_row += 1
ttk.Label(
general_config_frame,
text="If checked, 'New Episodes' will always be pinned if present.",
font=("Segoe UI", 9, "italic"),
foreground="yellow",
wraplength=600
).grid(row=current_row, column=0, columnspan=2, sticky="w", padx=10, pady=(0, 10))
current_row += 1
pinning_targets_frame = ttk.LabelFrame(scrollable_frame, text="Pinning Target Configuration", padding=10)
pinning_targets_frame.pack(fill="x", padx=20, pady=10)
# Add an explanatory label
ttk.Label(
pinning_targets_frame,
text=(
"Select where pinned collections will be configured:"
),
font=("Segoe UI", 9, "italic"),
wraplength=600,
justify="left",
foreground="yellow",
).grid(row=0, column=0, columnspan=2, sticky="w", padx=10, pady=(0, 10))
# Add the checkboxes for the pinning targets
self.library_recommended_var = tk.BooleanVar(
value=self.config.get("pinning_targets", {}).get("library_recommended", True))
self.home_var = tk.BooleanVar(value=self.config.get("pinning_targets", {}).get("home", True))
self.shared_home_var = tk.BooleanVar(value=self.config.get("pinning_targets", {}).get("shared_home", True))
ttk.Checkbutton(
pinning_targets_frame,
text="Library Recommended: Shows collections in the 'Recommended' section of a library.",
variable=self.library_recommended_var
).grid(row=1, column=0, sticky="w", padx=10, pady=5)