-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathadd.py
1629 lines (1396 loc) · 73.2 KB
/
add.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
# =============================================================================
# Soluify | Your #1 IT Problem Solver | {list-sync v0.5.6}
# =============================================================================
# __ _
# (_ _ | .(_
# __)(_)||_||| \/
# /
# © 2024
# -----------------------------------------------------------------------------
import base64
import getpass
import json
import logging
import os
import sqlite3
import time
import readline
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List, Dict, Any
import re
import requests
from colorama import Style, init
from cryptography.fernet import Fernet
from halo import Halo
from seleniumbase import SB
from dotenv import load_dotenv
# Initialize colorama for cross-platform colored terminal output
init(autoreset=True)
# Define paths for config and database
DATA_DIR = "./data"
CONFIG_FILE = os.path.join(DATA_DIR, "config.enc")
DB_FILE = os.path.join(DATA_DIR, "list_sync.db")
# Load environment variables if .env exists
if os.path.exists('.env'):
load_dotenv()
class SyncResults:
def __init__(self):
self.start_time = time.time()
self.not_found_items = [] # For #1
self.error_items = [] # For #4
self.media_type_counts = {"movie": 0, "tv": 0} # For #5
self.year_distribution = {
"pre-1980": 0,
"1980-1999": 0,
"2000-2019": 0,
"2020+": 0
} # For #8
self.total_items = 0
self.results = {
"requested": 0,
"already_requested": 0,
"already_available": 0,
"not_found": 0,
"error": 0,
"skipped": 0
}
def custom_input(prompt):
readline.set_startup_hook(lambda: readline.insert_text(''))
try:
return input(prompt)
finally:
readline.set_startup_hook()
def ensure_data_directory_exists():
os.makedirs(DATA_DIR, exist_ok=True)
def setup_logging():
# Create a formatter
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
# Set up file handler for general logging (DEBUG and above)
file_handler = logging.FileHandler(os.path.join(DATA_DIR, "list_sync.log"), encoding='utf-8')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
# Create a custom filter to block non-colored output
class ColoredOutputFilter(logging.Filter):
def filter(self, record):
# Only allow ERROR level messages that are explicitly marked for console
return False # Block all logging to console
# Set up console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.ERROR)
console_handler.setFormatter(formatter)
console_handler.addFilter(ColoredOutputFilter())
# Set up the root logger
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG) # Capture all levels
# Remove any existing handlers
for handler in root_logger.handlers[:]:
root_logger.removeHandler(handler)
# Add our handlers
root_logger.addHandler(file_handler)
root_logger.addHandler(console_handler)
# Set up separate logger for added items
added_logger = logging.getLogger("added_items")
added_logger.setLevel(logging.INFO)
added_handler = logging.FileHandler(os.path.join(DATA_DIR, "added.log"))
added_handler.setFormatter(logging.Formatter("%(asctime)s - %(message)s"))
added_logger.addHandler(added_handler)
# Prevent added_logger from propagating to root logger
added_logger.propagate = False
selenium_logger = logging.getLogger('selenium')
selenium_logger.setLevel(logging.INFO)
selenium_logger.propagate = False
# Disable urllib3 logging to console
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.INFO)
urllib3_logger.propagate = False
return added_logger
def init_database():
with sqlite3.connect(DB_FILE) as conn:
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS lists (
id INTEGER PRIMARY KEY AUTOINCREMENT,
list_type TEXT NOT NULL,
list_id TEXT NOT NULL,
UNIQUE(list_type, list_id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS synced_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
media_type TEXT NOT NULL,
imdb_id TEXT,
overseerr_id INTEGER,
status TEXT,
last_synced TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS sync_interval (
id INTEGER PRIMARY KEY AUTOINCREMENT,
interval_hours INTEGER NOT NULL
)
''')
conn.commit()
def color_gradient(text, start_color, end_color):
def hex_to_rgb(hex_code):
return tuple(int(hex_code[i : i + 2], 16) for i in (0, 2, 4))
start_rgb = hex_to_rgb(start_color.lstrip("#"))
end_rgb = hex_to_rgb(end_color.lstrip("#"))
gradient_text = ""
steps = len(text)
for i, char in enumerate(text):
ratio = i / steps
r = int(start_rgb[0] + (end_rgb[0] - start_rgb[0]) * ratio)
g = int(start_rgb[1] + (end_rgb[1] - start_rgb[1]) * ratio)
b = int(start_rgb[2] + (end_rgb[2] - start_rgb[2]) * ratio)
gradient_text += f"\033[38;2;{r};{g};{b}m{char}"
return gradient_text + Style.RESET_ALL
def display_ascii_art():
ascii_art = r"""
_ _ _ ___
| | (_) ___ | |_ / __| _ _ _ _ __
| |__ | | (_-< | _| \__ \ | || | | ' \ / _|
|____| |_| /__/ \__| |___/ \_, | |_||_| \__|
|__/
"""
art_lines = ascii_art.split("\n")
for line in art_lines:
print(color_gradient(line, "#00aaff", "#00ffaa"))
time.sleep(0.1)
print(Style.RESET_ALL)
def display_banner():
"""Display the banner."""
banner = """
==============================================================
Soluify - {servarr-tools_list-sync_v0.5.6}
==============================================================
"""
print(color_gradient(banner, "#00aaff", "#00ffaa"))
def encrypt_config(data, password):
key = base64.urlsafe_b64encode(password.encode().ljust(32)[:32])
fernet = Fernet(key)
return fernet.encrypt(json.dumps(data).encode())
def decrypt_config(encrypted_data, password):
key = base64.urlsafe_b64encode(password.encode().ljust(32)[:32])
fernet = Fernet(key)
return json.loads(fernet.decrypt(encrypted_data).decode())
def save_config(overseerr_url, api_key, requester_user_id):
config = {"overseerr_url": overseerr_url, "api_key": api_key, "requester_user_id": requester_user_id}
print(color_gradient("🔐 Enter a password to encrypt your API details: ", "#ff0000", "#aa0000"), end="")
password = getpass.getpass("")
encrypted_config = encrypt_config(config, password)
with open(CONFIG_FILE, "wb") as f:
f.write(encrypted_config)
print(f'\n{color_gradient("✅ Details encrypted. Remember your password!", "#00ff00", "#00aa00")}\n')
def load_config():
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, "rb") as f:
encrypted_config = f.read()
max_attempts = 3
current_attempt = 0
while current_attempt < max_attempts:
print() # Ensure password prompt is on a new line
password = getpass.getpass(color_gradient("🔑 Enter your password: ", "#ff0000", "#aa0000"))
try:
config = decrypt_config(encrypted_config, password)
print() # Add a newline after successful password entry
return config["overseerr_url"], config["api_key"], config["requester_user_id"]
except Exception:
current_attempt += 1
if current_attempt < max_attempts:
print(color_gradient("\n❌ Incorrect password. Please try again.", "#ff0000", "#aa0000"))
else:
print(color_gradient("\n❌ Maximum password attempts reached.", "#ff0000", "#aa0000"))
if custom_input("\n🗑️ Delete this config and start over? (y/n): ").lower() == "y":
os.remove(CONFIG_FILE)
print(color_gradient("\n🔄 Config deleted. Rerun the script to set it up again.", "#ffaa00", "#ff5500") + "\n")
return None, None, None
return None, None, None
def test_overseerr_api(overseerr_url, api_key):
headers = {"X-Api-Key": api_key, "Content-Type": "application/json"}
test_url = f"{overseerr_url}/api/v1/status"
spinner = Halo(text=color_gradient("🔍 Testing API connection...", "#ffaa00", "#ff5500"), spinner="dots")
spinner.start()
try:
response = requests.get(test_url, headers=headers)
response.raise_for_status()
spinner.succeed(color_gradient("🎉 API connection successful!", "#00ff00", "#00aa00"))
logging.info("Overseerr API connection successful!")
except Exception as e:
spinner.fail(color_gradient(f"❌ Overseerr API connection failed. Error: {str(e)}", "#ff0000", "#aa0000"))
logging.error(f"Overseerr API connection failed. Error: {str(e)}")
raise
def set_requester_user(overseerr_url, api_key):
headers = {"X-Api-Key": api_key, "Content-Type": "application/json"}
users_url = f"{overseerr_url}/api/v1/user"
try:
requester_user_id = "1"
response = requests.get(users_url, headers=headers)
response.raise_for_status()
jsonResult = response.json()
if jsonResult['pageInfo']['results'] > 1:
print(color_gradient("\n📋 Multiple users detected, you can choose which user will make the requests on ListSync behalf.\n", "#00aaff", "#00ffaa"))
for result in jsonResult['results']:
print(color_gradient(f"{result['id']}. {result['displayName']}", "#ffaa00", "#ff5500"))
requester_user_id = custom_input(color_gradient("\nEnter the number of the list to use as requester user: ", "#ffaa00", "#ff5500"))
if not next((x for x in jsonResult['results'] if str(x['id']) == requester_user_id), None):
requester_user_id = "1"
print(color_gradient("\n❌ Invalid option, using admin as requester user.", "#ff0000", "#aa0000"))
logging.info("Requester user set!")
return requester_user_id
except Exception as e:
logging.error(f"Overseerr API connection failed. Error: {str(e)}")
return 1
def fetch_imdb_list(list_id):
"""Fetch IMDb list using Selenium with pagination"""
media_items = []
print(color_gradient("📚 Fetching IMDB list...", "#ffaa00", "#ff5500"))
try:
with SB(uc=True, headless=True) as sb:
# Handle full URLs vs list IDs
if list_id.startswith(('http://', 'https://')):
url = list_id.rstrip('/') # Use the provided URL directly
if '/chart/' in url:
is_chart = True
elif '/list/' in url or '/user/' in url:
is_chart = False
else:
raise ValueError("Invalid IMDb URL format")
else:
# Existing logic for list IDs
if list_id in ['top', 'boxoffice', 'moviemeter', 'tvmeter']:
url = f"https://www.imdb.com/chart/{list_id}"
is_chart = True
elif list_id.startswith("ls"):
url = f"https://www.imdb.com/list/{list_id}"
is_chart = False
elif list_id.startswith("ur"):
url = f"https://www.imdb.com/user/{list_id}/watchlist"
is_chart = False
else:
raise ValueError("Invalid IMDb list ID format")
logging.info(f"Attempting to load URL: {url}")
sb.open(url)
if is_chart:
# Wait for chart content to load
sb.wait_for_element_present('.ipc-metadata-list.ipc-metadata-list--dividers-between', timeout=20)
# Get total number of items
try:
total_element = sb.find_element('[data-testid="chart-layout-total-items"]')
total_text = total_element.text
total_items = int(re.search(r'(\d+)\s+Titles?', total_text).group(1))
logging.info(f"Total items in chart: {total_items}")
except Exception as e:
logging.warning(f"Could not determine total items: {str(e)}")
total_items = None
# Process items in the chart
items = sb.find_elements(".ipc-metadata-list-summary-item__tc")
logging.info(f"Found {len(items)} items in chart")
for item in items:
try:
# Get title element
title_element = item.find_element("css selector", ".ipc-title__text")
full_title = title_element.text
# Remove ranking number if present (e.g., "1. The Shawshank Redemption" -> "The Shawshank Redemption")
title = re.sub(r'^\d+\.\s*', '', full_title)
# Get year from metadata
year = None
try:
metadata = item.find_element("css selector", ".cli-title-metadata")
year_element = metadata.find_element("css selector", ".cli-title-metadata-item")
year = int(year_element.text)
logging.debug(f"Extracted year for {title}: {year}")
except Exception as e:
logging.warning(f"Could not extract year for {title}: {str(e)}")
# Get IMDB ID from the title link
title_link = item.find_element("css selector", "a.ipc-title-link-wrapper")
imdb_id = title_link.get_attribute("href").split("/")[4]
# For charts, all items are movies unless explicitly marked as TV
media_type = "movie"
try:
if "TV" in metadata.text:
media_type = "tv"
except Exception:
pass
media_items.append({
"title": title.strip(),
"imdb_id": imdb_id,
"media_type": media_type,
"year": year
})
logging.info(f"Added {media_type}: {title} ({year}) (IMDB ID: {imdb_id})")
except Exception as e:
logging.warning(f"Failed to parse IMDb chart item: {str(e)}")
continue
else:
# Wait for list content to load
sb.wait_for_element_present('[data-testid="list-page-mc-list-content"]', timeout=20)
# Get total number of items
try:
total_element = sb.find_element('[data-testid="list-page-mc-total-items"]')
total_text = total_element.text
total_items = int(re.search(r'(\d+)\s+titles?', total_text).group(1))
logging.info(f"Total items in list: {total_items}")
expected_pages = (total_items + 249) // 250 # Round up division by 250
logging.info(f"Expected number of pages: {expected_pages}")
except Exception as e:
logging.warning(f"Could not determine total items: {str(e)}")
total_items = None
expected_pages = None
current_page = 1
# Process items on the page
while True:
items = sb.find_elements(".sc-2bfd043a-3.jpWwpQ")
logging.info(f"Processing page {current_page}: Found {len(items)} items")
for item in items:
try:
# Get title element
title_element = item.find_element("css selector", ".ipc-title__text")
full_title = title_element.text
title = full_title.split(". ", 1)[1] if ". " in full_title else full_title
# Get year from metadata
year = None
try:
metadata = item.find_element("css selector", ".dli-title-metadata")
metadata_text = metadata.text
# Extract year from formats like "2008–2013" or "2024"
year_match = re.search(r'(\d{4})', metadata_text)
if year_match:
year = int(year_match.group(1))
logging.debug(f"Extracted year for {title}: {year}")
except Exception as e:
logging.warning(f"Could not extract year for {title}: {str(e)}")
# More robust media type detection
media_type = "movie" # default
try:
type_element = item.find_element("css selector", ".dli-title-type-data")
if "TV Series" in type_element.text or "TV Mini Series" in type_element.text:
media_type = "tv"
except Exception:
try:
if "eps" in metadata_text or "episodes" in metadata_text.lower():
media_type = "tv"
except Exception:
logging.warning(f"Could not determine media type from metadata for {title}")
# Get IMDB ID from the title link
title_link = item.find_element("css selector", "a.ipc-title-link-wrapper")
imdb_id = title_link.get_attribute("href").split("/")[4]
media_items.append({
"title": title.strip(),
"imdb_id": imdb_id,
"media_type": media_type,
"year": year
})
logging.info(f"Added {media_type}: {title} ({year}) (IMDB ID: {imdb_id})")
except Exception as e:
logging.warning(f"Failed to parse IMDb item: {str(e)}")
continue
# Check if we've processed all expected pages
if expected_pages and current_page >= expected_pages:
logging.info(f"Reached final page {current_page} of {expected_pages}")
break
# Try to navigate to next page
try:
# First try clicking the button using a more specific selector
try:
next_button = sb.find_element(
"css selector",
"button.ipc-responsive-button[aria-label='Next']:not([disabled])"
)
if next_button:
sb.execute_script("arguments[0].scrollIntoView(true);", next_button)
sb.sleep(1) # Give time for scrolling
next_button.click()
# Wait for loading spinner to disappear and content to load
sb.wait_for_element_present('[data-testid="list-page-mc-list-content"]', timeout=10)
sb.sleep(3) # Additional wait for content to fully render
# Verify we have items on the page
new_items = sb.find_elements(".sc-2bfd043a-3.jpWwpQ")
if not new_items:
logging.warning(f"No items found after navigation to page {current_page + 1}, retrying...")
# Fall back to direct URL navigation
next_page = current_page + 1
next_url = f"{url}/?page={next_page}"
sb.open(next_url)
sb.wait_for_element_present('[data-testid="list-page-mc-list-content"]', timeout=10)
sb.sleep(3)
except Exception as e:
logging.info(f"Could not click next button: {str(e)}")
# Fall back to direct URL navigation
next_page = current_page + 1
next_url = f"{url}/?page={next_page}"
logging.info(f"Attempting to navigate directly to page {next_page}: {next_url}")
sb.open(next_url)
sb.wait_for_element_present('[data-testid="list-page-mc-list-content"]', timeout=10)
sb.sleep(3)
current_page += 1
sb.sleep(2)
except Exception as e:
logging.info(f"No more pages available: {str(e)}")
break
# Validate total items found
if total_items and len(media_items) < total_items:
logging.warning(f"Only found {len(media_items)} items out of {total_items} total")
print(color_gradient(f"✨ Found {len(media_items)} items from IMDB list {list_id}!", "#00ff00", "#00aa00"))
logging.info(f"IMDB list {list_id} fetched successfully. Found {len(media_items)} items.")
return media_items
except Exception as e:
print(color_gradient(f"💥 Failed to fetch IMDB list {list_id}. Error: {str(e)}", "#ff0000", "#aa0000"))
logging.error(f"Error fetching IMDB list {list_id}: {str(e)}")
raise
def fetch_trakt_list(list_id):
"""Fetch Trakt list using Selenium with pagination"""
media_items = []
print(color_gradient("📚 Fetching Trakt list...", "#ffaa00", "#ff5500"))
try:
with SB(uc=True, headless=True) as sb:
# Handle full URLs vs list IDs
if list_id.startswith(('http://', 'https://')):
url = list_id.rstrip('/') # Use the provided URL directly
if not ('trakt.tv/lists/' in url or 'trakt.tv/users/' in url):
raise ValueError("Invalid Trakt URL format")
else:
# Existing logic for numeric list IDs
if not list_id.isdigit():
raise ValueError("Invalid Trakt list ID format - must be numeric")
url = f"https://trakt.tv/lists/{list_id}"
logging.info(f"Attempting to load URL: {url}")
sb.open(url)
# Wait for container to load
sb.wait_for_element_present(".container", timeout=10)
while True:
# Wait for either movies or shows container to load
sb.wait_for_element_present(".row.posters", timeout=10)
# Get all items on current page (both movies and shows)
items = sb.find_elements(".grid-item.col-xs-6.col-md-2.col-sm-3")
logging.info(f"Found {len(items)} items on current page")
for item in items:
try:
# Get the full title and media type
watch_button = item.find_element("css selector", "a.watch")
full_title = watch_button.get_attribute("data-full-title")
media_type = item.get_attribute("data-type")
# Remove year from title if present (movies only typically have years)
title = full_title
if " (" in full_title and media_type == "movie":
title = full_title.split(" (")[0]
media_items.append({
"title": title.strip(),
"media_type": "tv" if media_type == "show" else "movie"
})
logging.info(f"Added {media_type}: {title}")
except Exception as e:
logging.warning(f"Failed to parse Trakt item: {str(e)}")
continue
# Check for next page button
try:
next_button = sb.find_element(".pagination-top .next:not(.disabled)")
if not next_button:
logging.info("No more pages to process")
break
next_link = next_button.find_element("css selector", "a")
next_link.click()
sb.sleep(3) # Wait for new page to load
except Exception as e:
logging.info(f"No more pages available: {str(e)}")
break
print(color_gradient(f"✨ Found {len(media_items)} items from Trakt list {list_id}!", "#00ff00", "#00aa00"))
logging.info(f"Trakt list {list_id} fetched successfully. Found {len(media_items)} items.")
return media_items
except Exception as e:
print(color_gradient(f"💥 Failed to fetch Trakt list {list_id}. Error: {str(e)}", "#ff0000", "#aa0000"))
logging.error(f"Error fetching Trakt list {list_id}: {str(e)}")
raise
def fetch_letterboxd_list(list_id):
"""Fetch Letterboxd list using Selenium with pagination"""
media_items = []
print(color_gradient("📚 Fetching Letterboxd list...", "#ffaa00", "#ff5500"))
try:
with SB(uc=True, headless=True) as sb:
# Handle full URLs vs list IDs
if list_id.startswith(('http://', 'https://')):
base_url = list_id.rstrip('/')
else:
base_url = f"https://letterboxd.com/{list_id}"
page = 1
while True:
# Construct page URL
current_url = base_url if page == 1 else f"{base_url}/page/{page}"
logging.info(f"Loading URL: {current_url}")
sb.open(current_url)
# Wait for the list container to load
sb.wait_for_element_present("ul.poster-list", timeout=20)
logging.info(f"Processing page {page}")
# Get all movie items on current page
items = sb.find_elements("li.poster-container")
items_count = len(items)
logging.info(f"Found {items_count} items on page {page}")
# If we find 0 items, we've gone too far - break
if items_count == 0:
logging.info(f"No items found on page {page}, ending pagination")
break
for item in items:
try:
# Get the film details link
film_link = item.find_element("css selector", "div.film-poster")
# Extract title from data-film-slug
film_slug = film_link.get_attribute("data-film-slug")
if film_slug:
# Convert slug to title (e.g., "the-matrix" -> "The Matrix")
title = " ".join(word.capitalize() for word in film_slug.split("-"))
else:
# Fallback to alt text of poster image
title = item.find_element("css selector", "img").get_attribute("alt")
# Remove year from title if it exists
if '(' in title and ')' in title and title.rstrip()[-1] == ')':
title = title[:title.rindex('(')].strip()
# Try to get year from data attribute
try:
year = int(film_link.get_attribute("data-film-release-year"))
except (ValueError, TypeError, AttributeError):
year = None
media_items.append({
"title": title.strip(),
"media_type": "movie",
"year": year
})
logging.info(f"Added movie: {title} ({year if year else 'year unknown'})")
except Exception as e:
logging.warning(f"Failed to parse movie item: {str(e)}")
continue
# If we found exactly 100 items, there might be more pages
if items_count == 100:
page += 1
logging.info(f"Found exactly 100 items, trying page {page}")
else:
logging.info(f"Found {items_count} items (< 100), must be the last page")
break
print(color_gradient(f"✨ Found {len(media_items)} items from Letterboxd list!", "#00ff00", "#00aa00"))
logging.info(f"Letterboxd list fetched successfully. Found {len(media_items)} items across {page} pages.")
return media_items
except Exception as e:
print(color_gradient(f"💥 Failed to fetch Letterboxd list. Error: {str(e)}", "#ff0000", "#aa0000"))
logging.error(f"Error fetching Letterboxd list: {str(e)}")
raise
def normalize_title(title: str) -> str:
"""Normalize a title for comparison by removing special characters and converting to lowercase."""
# Remove special characters, keeping only alphanumeric and spaces
normalized = re.sub(r'[^a-zA-Z0-9\s]', '', title)
# Convert to lowercase and remove extra spaces
normalized = ' '.join(normalized.lower().split())
return normalized
def calculate_title_similarity(title1: str, title2: str) -> float:
"""Calculate fuzzy match similarity between two titles."""
# Convert to lowercase for comparison but keep articles
t1 = title1.lower()
t2 = title2.lower()
# Calculate Levenshtein distance
def levenshtein(s1, s2):
if len(s1) < len(s2):
return levenshtein(s2, s1)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
# Get the Levenshtein distance
distance = levenshtein(t1, t2)
max_length = max(len(t1), len(t2))
# Convert distance to similarity score (0 to 1)
similarity = 1 - (distance / max_length)
return similarity
def search_media_in_overseerr(overseerr_url, api_key, media_title, media_type, release_year=None):
headers = {"X-Api-Key": api_key}
overseerr_url = overseerr_url.rstrip('/')
search_url = f"{overseerr_url}/api/v1/search"
# Always search with just the title
search_title = media_title
page = 1
best_match = None
best_score = 0
while True:
try:
encoded_query = requests.utils.quote(search_title)
url = f"{search_url}?query={encoded_query}&page={page}&language=en"
logging.debug(f"Searching for '{search_title}' (Year: {release_year})")
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 429:
logging.warning("Rate limited, waiting 5 seconds...")
time.sleep(5)
continue
response.raise_for_status()
search_results = response.json()
if not search_results.get("results"):
break
for result in search_results["results"]:
result_type = result.get("mediaType")
if result_type != media_type:
continue
# Get the title based on media type
result_title = result.get("title") if media_type == "movie" else result.get("name")
if not result_title:
continue
# Get year
result_year = None
try:
if media_type == "movie" and "releaseDate" in result:
result_year = int(result["releaseDate"][:4])
elif media_type == "tv" and "firstAirDate" in result:
result_year = int(result["firstAirDate"][:4])
except (ValueError, TypeError):
pass
# Calculate title similarity
similarity = calculate_title_similarity(search_title, result_title)
# Calculate final score
score = similarity
# Year matching
if release_year and result_year:
if release_year == result_year:
score *= 2 # Double score for exact year match
logging.debug(f"Exact year match for '{result_title}' ({result_year}) - Base similarity: {similarity}")
elif abs(release_year - result_year) <= 1:
score *= 1.5 # 1.5x score for off-by-one year
logging.debug(f"Close year match for '{result_title}' ({result_year}) - Base similarity: {similarity}")
logging.debug(f"Match candidate: '{result_title}' ({result_year}) - Score: {score}")
# Update best match if we have a better score
# For exact year matches, require a lower similarity threshold
min_similarity = 0.5 if (release_year and result_year and release_year == result_year) else 0.7
if score > best_score and similarity >= min_similarity:
best_score = score
best_match = result
logging.info(f"New best match: '{result_title}' ({result_year}) - Score: {score}")
# Only continue to next page if we haven't found a good match
if best_score > 1.5 or page >= search_results.get("totalPages", 1):
break
page += 1
except requests.exceptions.RequestException as e:
logging.error(f'Error searching for "{search_title}": {str(e)}')
if "429" in str(e):
time.sleep(5)
continue
raise
if best_match:
result_title = best_match.get("title") if media_type == "movie" else best_match.get("name")
result_year = None
try:
if media_type == "movie" and "releaseDate" in best_match:
result_year = best_match["releaseDate"][:4]
elif media_type == "tv" and "firstAirDate" in best_match:
result_year = best_match["firstAirDate"][:4]
except (ValueError, TypeError):
pass
logging.info(f"Final match for '{media_title}' ({release_year}): '{result_title}' ({result_year}) - Score: {best_score}")
return {
"id": best_match["id"],
"mediaType": best_match["mediaType"],
}
logging.warning(f'No matching results found for "{media_title}" ({release_year}) of type "{media_type}"')
return None
def extract_number_of_seasons(media_data):
number_of_seasons = media_data.get("numberOfSeasons")
logging.debug(f"Extracted number of seasons: {number_of_seasons}")
return number_of_seasons if number_of_seasons is not None else 1
def confirm_media_status(overseerr_url, api_key, media_id, media_type):
headers = {"X-Api-Key": api_key, "Content-Type": "application/json"}
media_url = f"{overseerr_url}/api/v1/{media_type}/{media_id}"
try:
response = requests.get(media_url, headers=headers)
response.raise_for_status()
media_data = response.json()
logging.debug(f"Detailed response for {media_type} ID {media_id}: {json.dumps(media_data)}")
media_info = media_data.get("mediaInfo", {})
status = media_info.get("status")
number_of_seasons = extract_number_of_seasons(media_data)
logging.debug(f"Status for {media_type} ID {media_id}: {status}")
logging.debug(f"Number of seasons for {media_type} ID {media_id}: {number_of_seasons}")
# Status codes:
# 2: PENDING
# 3: PROCESSING
# 4: PARTIALLY_AVAILABLE
# 5: AVAILABLE
is_available_to_watch = status in [4, 5]
is_requested = status in [2, 3]
return is_available_to_watch, is_requested, number_of_seasons
except Exception as e:
logging.error(f"Error confirming status for {media_type} ID {media_id}: {str(e)}")
raise
def request_media_in_overseerr(overseerr_url, api_key, requester_user_id, media_id, media_type, is_4k=False):
headers = {"X-Api-Key": api_key, "X-Api-User": requester_user_id, "Content-Type": "application/json"}
request_url = f"{overseerr_url}/api/v1/request"
payload = {
"mediaId": media_id,
"mediaType": media_type,
"is4k": is_4k
}
try:
response = requests.post(request_url, headers=headers, json=payload)
response.raise_for_status()
logging.debug(f"Request response for {media_type} ID {media_id}: {json.dumps(response.json())}")
return "success"
except Exception as e:
logging.error(f"Error requesting {media_type} ID {media_id}: {str(e)}")
return "error"
def request_tv_series_in_overseerr(overseerr_url, api_key, requester_user_id, tv_id, number_of_seasons, is_4k=False):
headers = {"X-Api-Key": api_key, "X-Api-User": requester_user_id, "Content-Type": "application/json"}
request_url = f"{overseerr_url}/api/v1/request"
seasons_list = [i for i in range(1, number_of_seasons + 1)]
logging.debug(f"Seasons list for TV series ID {tv_id}: {seasons_list}")
payload = {
"mediaId": tv_id,
"mediaType": "tv",
"is4k": is_4k,
"seasons": seasons_list
}
logging.debug(f"Request payload for TV series ID {tv_id}: {json.dumps(payload, indent=4)}")
try:
response = requests.post(request_url, headers=headers, json=payload)
response.raise_for_status()
logging.debug(f"Request response for TV series ID {tv_id}: {response.json()}")
return "success"
except Exception as e:
logging.error(f"Error requesting TV series ID {tv_id}: {str(e)}")
return "error"
def save_list_id(list_id: str, list_type: str):
"""Save list ID to database, converting URLs to IDs if needed"""
with sqlite3.connect(DB_FILE) as conn:
cursor = conn.cursor()
# For IMDb URLs, store the full URL
if list_type == "imdb" and list_id.startswith(('http://', 'https://')):
# Keep the full URL as is
id_to_save = list_id.rstrip('/')
# For IMDb chart names, store as is
elif list_type == "imdb" and list_id in ['top', 'boxoffice', 'moviemeter', 'tvmeter']:
id_to_save = list_id
# For Trakt URLs, store the full URL
elif list_type == "trakt" and list_id.startswith(('http://', 'https://')):
id_to_save = list_id.rstrip('/')
else:
# For traditional IDs (ls, ur, numeric), store as is
id_to_save = list_id
cursor.execute(
"INSERT OR REPLACE INTO lists (list_type, list_id) VALUES (?, ?)",
(list_type, id_to_save)
)
conn.commit()
def load_list_ids() -> List[Dict[str, str]]:
with sqlite3.connect(DB_FILE) as conn:
cursor = conn.cursor()
cursor.execute("SELECT list_type, list_id FROM lists")
return [{"type": row[0], "id": row[1]} for row in cursor.fetchall()]
def display_lists():
lists = load_list_ids()
print(color_gradient("\nSaved Lists:", "#00aaff", "#00ffaa"))
for idx, list_info in enumerate(lists, 1):
print(color_gradient(f"{idx}. {list_info['type'].upper()}: {list_info['id']}", "#ffaa00", "#ff5500"))
def delete_list():
lists = load_list_ids()
display_lists()
choice = custom_input(color_gradient("\nEnter the number of the list to delete (or 'c' to cancel): ", "#ffaa00", "#ff5500"))
if choice.lower() == 'c':
return
try:
idx = int(choice) - 1
if 0 <= idx < len(lists):
list_to_delete = lists[idx]
with sqlite3.connect(DB_FILE) as conn:
cursor = conn.cursor()
cursor.execute(
"DELETE FROM lists WHERE list_type = ? AND list_id = ?",
(list_to_delete['type'], list_to_delete['id'])
)
conn.commit()
print(color_gradient(f"\nList {list_to_delete['type'].upper()}: {list_to_delete['id']} deleted.", "#00ff00", "#00aa00"))
else:
print(color_gradient("\nInvalid list number.", "#ff0000", "#aa0000"))
except ValueError:
print(color_gradient("\nInvalid input. Please enter a number.", "#ff0000", "#aa0000"))
def edit_lists():
lists = load_list_ids()
display_lists()
print(color_gradient("\nEnter new list IDs (or press Enter to keep the current ID):", "#00aaff", "#00ffaa"))
updated_lists = []
for list_info in lists:
new_id = custom_input(color_gradient(f"{list_info['type'].upper()}: {list_info['id']} -> ", "#ffaa00", "#ff5500"))
updated_lists.append({
"type": list_info['type'],
"id": new_id if new_id else list_info['id']
})
with sqlite3.connect(DB_FILE) as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM lists")
cursor.executemany(
"INSERT INTO lists (list_type, list_id) VALUES (?, ?)",
[(list_info['type'], list_info['id']) for list_info in updated_lists]
)
conn.commit()
print(color_gradient("\nLists updated successfully.", "#00ff00", "#00aa00"))
def configure_sync_interval():
interval = custom_input(color_gradient("\n🕒 How often do you want to sync your lists (in hours)? ", "#ffaa00", "#ff5500"))
with sqlite3.connect(DB_FILE) as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM sync_interval")
cursor.execute("INSERT INTO sync_interval (interval_hours) VALUES (?)", (int(interval),))
conn.commit()
print(f'\n{color_gradient("✅ Sync interval configured.", "#00ff00", "#00aa00")}\n')
def load_sync_interval():
with sqlite3.connect(DB_FILE) as conn:
cursor = conn.cursor()
cursor.execute("SELECT interval_hours FROM sync_interval")
result = cursor.fetchone()
return result[0] if result else 0 # Default to 0 hours if not set
def should_sync_item(overseerr_id):