-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slm.py
8102 lines (7063 loc) · 323 KB
/
slm.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 shutil
import socket
import csv
import pandas as pd
import pandasql as psql
import json
import re
import urllib.parse
import requests
import datetime
import time
import threading
import logging
import aiohttp
import asyncio
import stat
import unicodedata
import gzip
import io
from flask import Flask, render_template, render_template_string, request, redirect, url_for, Response, send_file, Request, make_response
from jinja2 import TemplateNotFound
# Control how many data elements can be saved at a time from the webpage to the code
class CustomRequest(Request):
def __init__(self, *args, **kwargs):
super(CustomRequest, self).__init__(*args, **kwargs)
self.max_form_parts = 100000 # Modify value higher if continual 413 issues
# Global Variables
slm_version = "v2024.11.24.1123"
slm_port = os.environ.get("SLM_PORT")
if slm_port is None:
slm_port = 5000
else:
try:
slm_port = int(slm_port)
except:
slm_port = 5000
app = Flask(__name__)
app.request_class = CustomRequest
script_dir = os.path.dirname(os.path.abspath(__file__))
script_filename = os.path.basename(__file__)
log_filename = os.path.splitext(script_filename)[0] + '.log'
docker_channels_dir = os.path.join(script_dir, "channels_folder")
program_files_dir = os.path.join(script_dir, "program_files")
backup_dir = os.path.join(program_files_dir, "backups")
playlists_uploads_dir_name = "playlists_uploads"
playlists_uploads_dir = os.path.join(program_files_dir, playlists_uploads_dir_name)
max_backups = 3
csv_settings = "StreamLinkManager_Settings.csv"
csv_streaming_services = "StreamLinkManager_StreamingServices.csv"
csv_bookmarks = "StreamLinkManager_Bookmarks.csv"
csv_bookmarks_status = "StreamLinkManager_BookmarksStatus.csv"
csv_slmappings = "StreamLinkManager_SLMappings.csv"
# Playlist Manager files only get created when turned on in Settings
csv_playlistmanager_playlists = "PlaylistManager_Playlists.csv"
csv_playlistmanager_combined_m3us = "PlaylistManager_Combinedm3us.csv"
csv_playlistmanager_parents = "PlaylistManager_Parents.csv"
csv_playlistmanager_child_to_parent = "PlaylistManager_ChildToParent.csv"
csv_files = [
csv_settings,
csv_streaming_services,
csv_bookmarks,
csv_bookmarks_status,
csv_slmappings #,
# Add more rows as needed
]
program_files = csv_files + [log_filename]
engine_url = "https://www.justwatch.com"
url_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'}
_GRAPHQL_API_URL = "https://apis.justwatch.com/graphql"
engine_image_url = "https://images.justwatch.com"
engine_image_profile_poster = "s718"
engine_image_profile_backdrop = "s1920"
engine_image_profile_icon = "s100"
valid_country_codes = [
"AD",
"AE",
"AG",
"AL",
"AR",
"AT",
"AU",
"BA",
"BB",
"BE",
"BG",
"BH",
"BM",
"BO",
"BR",
"BS",
"CA",
"CH",
"CI",
"CL",
"CO",
"CR",
"CU",
"CV",
"CZ",
"DE",
"DK",
"DO",
"DZ",
"EC",
"EE",
"EG",
"ES",
"FI",
"FJ",
"FR",
"GB",
"GF",
"GG",
"GH",
"GI",
"GQ",
"GR",
"GT",
"HK",
"HN",
"HR",
"HU",
"ID",
"IE",
"IL",
"IN",
"IQ",
"IS",
"IT",
"JM",
"JO",
"JP",
"KE",
"KR",
"KW",
"LB",
"LI",
"LT",
"LV",
"LY",
"MA",
"MC",
"MD",
"MK",
"MT",
"MU",
"MX",
"MY",
"MZ",
"NE",
"NG",
"NL",
"NO",
"NZ",
"OM",
"PA",
"PE",
"PF",
"PH",
"PK",
"PL",
"PS",
"PT",
"PY",
"QA",
"RO",
"RS",
"RU",
"SA",
"SC",
"SE",
"SG",
"SI",
"SK",
"SM",
"SN",
"SV",
"TC",
"TH",
"TN",
"TR",
"TT",
"TW",
"TZ",
"UG",
"US",
"UY",
"VA",
"VE",
"XK",
"YE",
"ZA",
"ZM" #, Add more as needed
]
valid_language_codes = [
"ar",
"bg",
"bs",
"ca",
"cs",
"de",
"el",
"en",
"es",
"fi",
"fr",
"he",
"hr",
"hu",
"is",
"it",
"ja",
"ko",
"mk",
"mt",
"pl",
"pt",
"ro",
"ru",
"sk",
"sl",
"sq",
"sr",
"sw",
"tr",
"ur",
"zh" #, Add more as needed
]
special_actions_default = [
"None",
"Make STRM" #, Add more as needed
]
notifications = []
stream_link_ids_changed = []
program_search_results_prior = []
country_code_input_prior = None
language_code_input_prior = None
entry_id_prior = None
title_selected_prior = None
release_year_selected_prior = None
object_type_selected_prior = None
bookmark_action_prior = None
season_episodes_prior = []
bookmarks_statuses_selected_prior = []
edit_flag = None
channels_url_prior = None
date_new_default_prior = None
program_add_prior = ''
program_add_resort_panel = ''
program_add_filter_panel = ''
slm_query = None
slm_query_name = None
offer_icons = []
offer_icons_flag = None
select_file_prior = None
bookmark_actions_default = [
"None",
"Hide" #, Add more as needed
]
bookmark_actions_default_show_only = [
"Disable Get New Episodes" #, Add more as needed
]
plm_m3us_epgs_schedule_frequencies = [
"Every 1 hour",
"Every 3 hours",
"Every 6 hours",
"Every 12 hours",
"Every 24 hours"
]
slm_end_to_end_frequencies = [
"Every 8 hours",
"Every 12 hours",
"Every 24 hours"
]
stream_formats = [
"HLS",
"MPEG-TS"
]
select_program_to_bookmarks = []
# Adds a notification
def notification_add(notification):
global notifications
notifications.insert(0, notification)
print(notification)
# Get the full path for a file
def full_path(file):
full_path = os.path.join(program_files_dir, file)
return full_path
# Normalize the file path for systems that can't handle certain characters like 'é'
def normalize_path(path):
return unicodedata.normalize('NFKC', path)
# Create a directory if it doesn't exist.
def create_directory(directory_path):
directory_path = normalize_path(directory_path)
try:
if not os.path.exists(directory_path):
os.makedirs(directory_path)
except OSError as e:
print(f" Error creating directory {directory_path}: {e}")
# Create a backup of program files and remove old backups
def create_backup(src_dir, dst_dir, max_backups):
# Copy the contents of src_dir to the backup subdirectory
timestamp = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
backup_subdir = os.path.join(dst_dir, timestamp)
os.makedirs(backup_subdir, exist_ok=True)
for item in os.listdir(src_dir):
src_item = os.path.join(src_dir, item)
if os.path.isfile(src_item):
shutil.copy2(src_item, backup_subdir)
# Clean up old backups if there are more than max_backups
backups = sorted(os.listdir(dst_dir))
if len(backups) > max_backups:
oldest_backups = backups[:len(backups) - max_backups]
for old_backup in oldest_backups:
shutil.rmtree(os.path.join(dst_dir, old_backup))
# Make sure all files and directories are in the correct place
### Program directories
create_directory(program_files_dir)
create_directory(backup_dir)
### Make a backup and remove old backups
if os.path.exists(program_files_dir):
create_backup(program_files_dir, backup_dir, max_backups)
# Set up session logging
log_filename_fullpath = full_path(log_filename)
open(log_filename_fullpath, 'w', encoding="utf-8").close()
class logger(object):
def __init__(self, filename=log_filename_fullpath, mode="ab", buff=0):
self.stdout = sys.stdout
self.stdin = sys.stdin
self.file = open(filename, mode, buff)
sys.stdout = self
sys.stdin = self
def readline(self):
user_input = self.stdin.readline()
self.file.write(user_input.encode("utf-8"))
return user_input
def __del__(self):
self.close()
def __enter__(self):
pass
def __exit__(self, *args):
self.close()
def write(self, message):
self.stdout.write(message)
self.file.write(message.encode("utf-8"))
def flush(self):
self.stdout.flush()
self.file.flush()
os.fsync(self.file.fileno())
def close(self):
if self.stdout != None:
sys.stdout = self.stdout
self.stdout = None
if self.stdin != None:
sys.stdin = self.stdin
self.stdin = None
if self.file != None:
self.file.close()
self.file = None
logging.basicConfig(
level=logging.DEBUG,
format="[%(levelname)s | %(asctime)s] - %(message)s",
filename=log_filename_fullpath,
filemode="a",
)
log = logger()
# Current date/time for logging
def current_time():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") + ": "
notification_add(f"\n{current_time()} Beginning Initialization Process (see log for details)...\n")
# Start-up process and safety checks
def check_website(url):
while True:
try:
response = requests.get(url, headers=url_headers)
if response.status_code == 200:
print(f"\n{current_time()} SUCCESS: {url} is accessible. Continuing...")
break
else:
print(f"\n{current_time()} ERROR: {url} reports {response.status_code}")
except requests.RequestException as e:
print(f"\n{current_time()} ERROR: {url} reports {e}")
print(f"\n{current_time()} INFO: Retrying in 1 minute...")
time.sleep(60)
check_website(engine_url)
# Create missing data files, update data as needed
def check_and_create_csv(csv_file):
full_path_file = full_path(csv_file)
data = initial_data(csv_file)
# Check if the file is empty or only contains blank lines; if so, delete it to start over
if os.path.exists(full_path_file):
with open(full_path_file, 'r', encoding="utf-8") as file:
content = file.readlines()
if all(line.strip() == '' for line in content):
os.remove(full_path_file)
# Check if the file exists, if not create it
if not os.path.exists(full_path_file):
# Write data to the file
write_data(csv_file, data)
remove_empty_row(csv_file)
if csv_file == csv_settings:
print(f"\n*** First Time Setup ***")
settings = read_data(csv_settings)
settings[0]['settings'], channels_url_message = get_channels_url()
settings[1]['settings'] = find_channels_dvr_path()
settings[2]['settings'] = get_country_code()
write_data(csv_settings, settings)
# Append/Remove rows to data that may update
if csv_file == csv_streaming_services:
id_field = "streaming_service_name"
update_rows(csv_file, data, id_field, None)
# Add columns for new functionality
if csv_file == csv_bookmarks_status:
check_and_add_column(csv_file, 'special_action', 'None')
if csv_file == csv_bookmarks:
check_and_add_column(csv_file, 'bookmark_action', 'None')
# Add rows for new functionality
if csv_file == csv_settings:
check_and_append(csv_file, {"settings": "Off"}, 11, "Search Defaults: Filter out already bookmarked")
check_and_append(csv_file, {"settings": "Off"}, 12, "Playlist Manager: On/Off")
check_and_append(csv_file, {"settings": 10000}, 13, "Playlist Manager: Starting station number")
check_and_append(csv_file, {"settings": 750}, 14, "Playlist Manager: Max number of stations per m3u")
check_and_append(csv_file, {"settings": "Off"}, 15, "Playlist Manager: Update Stations Process Schedule On/Off")
check_and_append(csv_file, {"settings": datetime.datetime.now().strftime('%H:%M')}, 16, "Playlist Manager: Update Stations Process Schedule Time")
check_and_append(csv_file, {"settings": "Off"}, 17, "Playlist Manager: Update m3u(s) and XML EPG(s) Process Schedule On/Off")
check_and_append(csv_file, {"settings": datetime.datetime.now().strftime('%H:%M')}, 18, "Playlist Manager: Update m3u(s) and XML EPG(s) Process Schedule Start Time")
check_and_append(csv_file, {"settings": "Every 24 hours"}, 19, "Playlist Manager: Update m3u(s) and XML EPG(s) Process Schedule Frequency")
check_and_append(csv_file, {"settings": "Every 24 hours"}, 20, "SLM: End-to-End Process Schedule Frequency")
# Clean up empty data files
def remove_empty_row(csv_file):
# Create a temporary file to write non-empty rows
temp_file = full_path("temp.csv")
full_path_file = full_path(csv_file)
with open(full_path_file, "r", encoding="utf-8") as infile, open(temp_file, "w", newline="", encoding="utf-8") as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
# Write the header (first row) to the new file
header = next(reader)
writer.writerow(header)
# Process each row
for row in reader:
# Check if the row contains any data (non-empty)
if any(cell.strip() for cell in row):
writer.writerow(row)
# Replace the original file with the temporary file
os.replace(temp_file, full_path_file)
# Appends new rows. removes old rows, and updates modified rows from initialization data to be written to data files
def update_rows(csv_file, data, id_field, modify_flag):
if data:
new_rows = extract_new_rows(csv_file, data, id_field)
if new_rows:
print(f"\n{current_time()} INFO: Adding new rows to {csv_file}...\n")
for new_row in new_rows:
append_data(csv_file, new_row)
notification_add(f" ADDED: {new_row[id_field]}")
print(f"\n{current_time()} INFO: Finished adding new rows.\n")
old_rows = extract_old_rows(csv_file, data, id_field)
if old_rows:
print(f"\n{current_time()} INFO: Removing old rows from {csv_file}...\n")
for old_row in old_rows:
notification_add(f" REMOVED: {old_row[id_field]}")
remove_data(csv_file, old_rows, id_field)
print(f"\n{current_time()} INFO: Finished removing old rows.\n")
if modify_flag:
modified_rows, no_notify_rows = extract_modified_rows(csv_file, data, id_field)
if modified_rows:
print(f"\n{current_time()} INFO: Updating modified rows in {csv_file}...\n")
for modified_row in modified_rows:
if modified_row not in no_notify_rows:
notification_add(f" MODIFIED: {modified_row[id_field]}")
update_data(csv_file, modified_rows, id_field)
print(f"\n{current_time()} INFO: Finished updating modified rows.\n")
remove_duplicate_rows(csv_file)
else:
print(f"\n{current_time()} WARNING: No data to compare, skipping adding and removing rows in {csv_file}.\n")
# Extracts new rows from the library data that are not already present in the CSV file
def extract_new_rows(csv_file, data, id_field):
full_path_file = full_path(csv_file)
# Read existing data (if any)
existing_data = []
if os.path.exists(full_path_file):
with open(full_path_file, "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
existing_data = [row for row in reader]
# Check for duplicate IDs
existing_ids = {row[id_field] for row in existing_data}
# Extract new rows
new_rows = []
for row in data:
if row[id_field] not in existing_ids:
new_rows.append(row)
return new_rows
# Extracts old rows from the CSV File that are no longer present in the library data
def extract_old_rows(csv_file, data, id_field):
full_path_file = full_path(csv_file)
# Read existing data (if any)
existing_data = []
if os.path.exists(full_path_file):
with open(full_path_file, "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
existing_data = [row for row in reader]
# Check for duplicate IDs
existing_ids = {row[id_field] for row in data}
# Extract old rows
old_rows = []
for row in existing_data:
if row[id_field] not in existing_ids:
old_rows.append(row)
return old_rows
# Extracts modified rows from the library data that are present in the CSV file but have different content
def extract_modified_rows(csv_file, data, id_field):
full_path_file = full_path(csv_file)
# Read existing data (if any)
existing_data = []
if os.path.exists(full_path_file):
with open(full_path_file, "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
existing_data = [row for row in reader]
# Create a dictionary for quick lookup of existing rows by id_field
existing_data_dict = {row[id_field]: row for row in existing_data}
# Extract modified rows and rows to not notify
modified_rows = []
no_notify_rows = []
for row in data:
if row[id_field] in existing_data_dict:
existing_row = existing_data_dict[row[id_field]]
if any(row[key] != existing_row[key] for key in row.keys() if key != id_field):
modified_rows.append(row)
# Check for ?X-Plex-Token= difference
differing_keys = [key for key in row.keys() if key != id_field and row[key] != existing_row[key]]
if all('X-Plex-Token' in key or row[key].startswith(existing_row[key].split('?X-Plex-Token=')[0]) for key in differing_keys):
no_notify_rows.append(row)
return modified_rows, no_notify_rows
# Updates rows in the CSV file with modified content
def update_data(csv_file, modified_rows, id_field):
full_path_file = full_path(csv_file)
# Read existing data (if any)
existing_data = []
if os.path.exists(full_path_file):
with open(full_path_file, "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
existing_data = [row for row in reader]
# Create a dictionary for quick lookup of modified rows by id_field
modified_data_dict = {row[id_field]: row for row in modified_rows}
# Update the existing data with modified rows
updated_data = [
modified_data_dict[row[id_field]] if row[id_field] in modified_data_dict else row
for row in existing_data
]
# Write the updated data back to the CSV file
fieldnames = updated_data[0].keys() if updated_data else []
with open(full_path_file, "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(updated_data)
# Removes duplicate rows from the CSV file
def remove_duplicate_rows(csv_file):
full_path_file = full_path(csv_file)
if os.path.exists(full_path_file):
with open(full_path_file, "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
existing_data = [row for row in reader]
# Remove duplicates
unique_data = {tuple(row.items()): row for row in existing_data}.values()
# Write the deduplicated data back to the CSV file
fieldnames = existing_data[0].keys() if existing_data else []
with open(full_path_file, "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(unique_data)
print(f"\n{current_time()} INFO: Removed duplicate rows from {csv_file}.\n")
# Add new columns during upgrades
def check_and_add_column(csv_file, column_name, default_value):
full_path_file = full_path(csv_file)
# Read the CSV file
with open(full_path_file, mode='r', newline='', encoding="utf-8") as infile:
reader = csv.DictReader(infile)
fieldnames = reader.fieldnames
rows = list(reader)
# Check if the column exists
if column_name not in fieldnames:
fieldnames.append(column_name)
for row in rows:
row[column_name] = default_value
# Write the updated data back to the CSV file
with open(full_path_file, mode='w', newline='', encoding="utf-8") as outfile:
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
# Data records for initialization files
def initial_data(csv_file):
if csv_file == csv_settings:
data = [
{"settings": f"http://dvr-{socket.gethostname().lower()}.local:8089"}, # [0] Channels URL
{"settings": script_dir}, # [1] Channels Folder
{"settings": "US"}, # [2] Search Defaults: Country Code
{"settings": "en"}, # [3] Search Defaults: Language Code
{"settings": "9"}, # [4] Search Defaults: Number of Results
{"settings": "Off"}, # DEPRECATED: [5] Hulu to Disney+ Automatic Conversion
{"settings": datetime.datetime.now().strftime('%H:%M')}, # [6] SLM: End-to-End Process Schedule Time
{"settings": "On"}, # [7] Channels Prune
{"settings": "Off"}, # [8] SLM: End-to-End Process Schedule On/Off
{"settings": "Off"}, # [9] Search Defaults: Filter out already bookmarked
{"settings": "Off"}, # [10] Playlist Manager: On/Off
{"settings": 10000}, # [11] Playlist Manager: Starting station number
{"settings": 750}, # [12] Playlist Manager: Max number of stations per m3u
{"settings": "Off"}, # [13] Playlist Manager: Update Stations Process Schedule On/Off
{"settings": datetime.datetime.now().strftime('%H:%M')}, # [14] Playlist Manager: Update Stations Process Schedule Time
{"settings": "Off"}, # [15] Playlist Manager: Update m3u(s) and XML EPG(s) Process Schedule On/Off
{"settings": datetime.datetime.now().strftime('%H:%M')}, # [16] Playlist Manager: Update m3u(s) and XML EPG(s) Process Schedule Start Time
{"settings": "Every 24 hours"}, # [17] Playlist Manager: Update m3u(s) and XML EPG(s) Process Schedule Frequency
{"settings": "Every 24 hours"} #, # [18] SLM: End-to-End Process Schedule Frequency
# Add more rows as needed
]
elif csv_file == csv_streaming_services:
data = get_streaming_services()
elif csv_file == csv_bookmarks:
data = [
{"entry_id": None,"title": None, "release_year": None, "object_type": None, "url": None, "country_code": None, "language_code": None, "bookmark_action": None}
]
elif csv_file == csv_bookmarks_status:
data = [
{"entry_id": None, "season_episode_id": None, "season_episode_prefix": None, "season_episode": None, "status": None, "stream_link": None, "stream_link_override": None, "stream_link_file": None, "special_action": None}
]
elif csv_file == csv_slmappings:
data = [
{"active": "Off", "contains_string": "hulu.com/watch", "object_type": "MOVIE or SHOW", "replace_type": "Replace string with...", "replace_string": "disneyplus.com/play"},
{"active": "On", "contains_string": "netflix.com/title", "object_type": "MOVIE", "replace_type": "Replace string with...", "replace_string": "netflix.com/watch"},
{"active": "On", "contains_string": "watch.amazon.com/detail?gti=", "object_type": "MOVIE or SHOW", "replace_type": "Replace string with...", "replace_string": "www.amazon.com/gp/video/detail/"},
{"active": "Off", "contains_string": "vudu.com", "object_type": "MOVIE or SHOW", "replace_type": "Replace entire Stream Link with...", "replace_string": "fandangonow://"} #,
# Add more rows as needed
]
# Playlist Manager
elif csv_file == csv_playlistmanager_playlists:
data = [
{"m3u_id": None, "m3u_name": None, "m3u_url": None, "epg_xml": None, "stream_format": None, "m3u_priority": None}
]
elif csv_file == csv_playlistmanager_parents:
data = [
{"parent_channel_id": None, "parent_title": None, "parent_tvg_id_override": None, "parent_tvg_logo_override": None, "parent_channel_number_override": None, "parent_tvc_guide_stationid_override": None, "parent_tvc_guide_art_override": None, "parent_tvc_guide_tags_override": None, "parent_tvc_guide_genres_override": None, "parent_tvc_guide_categories_override": None, "parent_tvc_guide_placeholders_override": None, "parent_tvc_stream_vcodec_override": None, "parent_tvc_stream_acodec_override": None, "parent_preferred_playlist": None}
]
elif csv_file == csv_playlistmanager_child_to_parent:
data = [
{"child_m3u_id_channel_id": None, "parent_channel_id": None}
]
elif csv_file == csv_playlistmanager_combined_m3us:
data = [
{"station_playlist": None, "m3u_id": None, "title": None, "tvc_guide_title": None, "channel_id": None, "tvg_id": None, "tvg_name": None, "tvg_logo": None, "tvg_chno": None, "channel_number": None, "tvg_description": None, "tvc_guide_description": None, "group_title": None, "tvc_guide_stationid": None, "tvc_guide_art": None, "tvc_guide_tags": None, "tvc_guide_genres": None, "tvc_guide_categories": None, "tvc_guide_placeholders": None, "tvc_stream_vcodec": None, "tvc_stream_acodec": None, "url": None}
]
return data
# Handler for timeout errors
def timeout_handler():
global timeout_occurred
timeout_occurred = True
# Attempts to find the Channels DVR path
def find_channels_dvr_path():
global timeout_occurred
timeout_occurred = False
channels_dvr_path = script_dir
channels_dvr_path_search = None
root_path = os.path.abspath(os.sep)
search_directory = "Imports"
print(f"\n{current_time()} Searching for Channels DVR folder...")
print(f"{current_time()} Please wait or press 'Ctrl+C' to stop and continue the initialization process.\n")
# Search times out after 60 seconds
timer = threading.Timer(60, timeout_handler)
timer.start()
try:
for root, dirs, _ in os.walk(root_path):
if timeout_occurred:
raise TimeoutError # Timeout if serach going for too long
if search_directory in dirs or search_directory.lower() in dirs:
if os.path.abspath(os.path.join(root)).lower().endswith("dvr") or os.path.abspath(os.path.join(root)).lower().endswith("channels_folder"):
channels_dvr_path_search = os.path.abspath(os.path.join(root))
break # Stop searching once found
except TimeoutError:
print(f"{current_time()} INFO: Search timed out. Continuing to next step...\n")
except KeyboardInterrupt:
print(f"{current_time()} INFO: Search interrupted by user. Continuing to next step...\n")
finally:
timer.cancel() # Disable the timer
if channels_dvr_path_search:
print(f"{current_time()} INFO: Channels DVR folder found!")
channels_dvr_path = channels_dvr_path_search
else:
if os.path.exists(docker_channels_dir):
print(f"{current_time()} INFO: Channels DVR folder not found, setting to Docker default...")
channels_dvr_path = docker_channels_dir
else:
print(f"{current_time()} INFO: Channels DVR folder not found, defaulting to current directory. Please set your Channels DVR folder in 'Settings'.")
print(f"{current_time()} INFO: Channels DVR folder set to '{channels_dvr_path}'\n")
return channels_dvr_path
# Find all available streaming services for the country
def get_streaming_services():
settings = read_data(csv_settings)
country_code = settings[2]['settings']
provider_results = []
provider_results_json = []
provider_results_json_array = []
provider_results_json_array_results = []
_GRAPHQL_GetProviders = """
query GetProviders($country: Country!, $platform: Platform!) {
packages(country: $country, platform: $platform) {
clearName
addons(country: $country, platform: $platform) {
clearName
}
}
}
"""
json_data = {
'query': _GRAPHQL_GetProviders,
'variables': {
"country": country_code,
"platform": "WEB"
},
'operationName': 'GetProviders',
}
try:
provider_results = requests.post(_GRAPHQL_API_URL, headers=url_headers, json=json_data)
except requests.RequestException as e:
print(f"\n{current_time()} WARNING: {e}. Skipping, please try again.")
if provider_results:
provider_results_json = provider_results.json()
provider_results_json_array = provider_results_json["data"]["packages"]
for provider in provider_results_json_array :
provider_addons = []
entry = {
"streaming_service_name": provider["clearName"],
"streaming_service_subscribe": False,
"streaming_service_priority": None
}
provider_results_json_array_results.append(entry)
provider_addons = provider["addons"]
if provider_addons:
for provider_addon in provider_addons:
entry = {
"streaming_service_name": provider_addon["clearName"],
"streaming_service_subscribe": False,
"streaming_service_priority": None
}
provider_results_json_array_results.append(entry)
return provider_results_json_array_results
# Update Streaming Services
def update_streaming_services():
data = get_streaming_services()
update_rows(csv_streaming_services, data, "streaming_service_name", None)
# Read data from a CSV file.
def read_data(csv_file):
full_path_file = full_path(csv_file)
data = []
try:
with open(full_path_file, "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
data.append(row)
return data
except Exception as e:
print(f"\n{current_time()} ERROR: Reading data... {e}\n")
return None
# Write data back to a CSV file.
def write_data(csv_file, data):
full_path_file = full_path(csv_file)
try:
with open(full_path_file, "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=data[0].keys())
writer.writeheader() # Write the header row
# Write each row from the data list
writer.writerows(data)
except Exception as e:
print(f"\n{current_time()} ERROR: Writing data... {e}\n")
# Appends a new row to an existing CSV file.
def append_data(csv_file, new_row):
# Get the full path to the CSV file
full_path_file = full_path(csv_file)
# Check if the file is empty (contains only the header row)
is_empty = os.path.getsize(full_path_file) == 0
try:
# Open the file in append mode with UTF-8 encoding
with open(full_path_file, "a", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=new_row.keys())
# Write the header row if the file is empty
if is_empty:
writer.writeheader()
# Append the new row
writer.writerow(new_row)
except Exception as e:
print(f"\n{current_time()} ERROR: Appending data... {e}\n")
# Function to count rows in the CSV file
def count_rows(csv_file):
full_path_file = full_path(csv_file)
with open(full_path_file, "r", encoding="utf-8") as file:
reader = csv.reader(file)
return sum(1 for row in reader)
# Function to add a new row if the row count is less than a certain number
def check_and_append(csv_file, new_row, threshold, purpose):
row_count = count_rows(csv_file)
if row_count < threshold:
append_data(csv_file, new_row)
notification_add(f"\n{current_time()} INFO: New row added to {csv_file}... it was for '{purpose}'.")
# Removes rows from the CSV file
def remove_data(csv_file, old_rows, id_field):
full_path_file = full_path(csv_file)
# Read existing data (if any)
existing_data = []
if os.path.exists(full_path_file):
with open(full_path_file, "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
existing_data = [row for row in reader]
# Check for duplicate IDs
existing_ids = set()
if old_rows:
existing_ids = {row[id_field] for row in old_rows}
# Filter out matching rows
new_rows = [row for row in existing_data if row[id_field] not in existing_ids]
# Write the new rows back to the CSV file
write_data(csv_file, new_rows)
# Search for country code
def get_country_code():
settings = read_data(csv_settings)
country_code = settings[2]["settings"]
country_code_input = None
country_code_new = None
global timeout_occurred
timeout_occurred = False
print(f"\n{current_time()} Searching for country code for Streaming Services...")
print(f"{current_time()} Please wait or press 'Ctrl+C' to stop and continue the initialization process.\n")
# Search times out after 30 seconds
timer = threading.Timer(30, timeout_handler)
timer.start()
try:
response = requests.get('https://ipinfo.io', headers=url_headers)
data = response.json()
user_country_code = data.get('country').upper()
if user_country_code in valid_country_codes:
country_code_input = user_country_code
except TimeoutError:
print(f"{current_time()} INFO: Search timed out. Continuing to next step...\n")
except KeyboardInterrupt:
print(f"{current_time()} INFO: Search interrupted by user. Continuing to next step...\n")
except Exception as e:
print(f"{current_time()} INFO: Error getting geolocation: {e}. Continuing to next step...\n")
finally:
timer.cancel() # Disable the timer
if country_code_input:
print(f"{current_time()} INFO: Country found!")
country_code_new = country_code_input.upper()
else:
print(f"{current_time()} INFO: Country not found, using default value. Please set your Country in 'Settings'.")
country_code_new = country_code
print(f"{current_time()} INFO: Country Code set to '{country_code_new}'\n")
return country_code_new
# Check if Channels URL is correct
def check_channels_url(channels_url_input):
if channels_url_input:
channels_url = channels_url_input
else:
settings = read_data(csv_settings)
channels_url = settings[0]["settings"]
channels_url_okay = None
try:
response = requests.get(channels_url, headers=url_headers)
if response:
channels_url_okay = True
except requests.RequestException:
print(f"\n{current_time()} WARNING: Channels URL not found at {channels_url}")
print(f"{current_time()} WARNING: Please change Channels URL in settings")
return channels_url_okay
# Searches for an IP Address on the LAN that responds to Port 8089
def get_channels_url():
local_ip = socket.gethostbyname(socket.gethostname())
ip_parts = local_ip.split('.')
base_ip = '.'.join(ip_parts[:-1]) + '.'
start_ip = int(ip_parts[-1])