-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslm.py
10821 lines (9335 loc) · 471 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, stream_with_context
from jinja2 import TemplateNotFound
import yt_dlp
# Top Controls
slm_environment_version = "PRERELEASE"
slm_environment_port = None
# Current Stable Release
slm_version = "v2025.03.05.2024"
slm_port = os.environ.get("SLM_PORT")
# Current Development State
if slm_environment_version == "PRERELEASE":
slm_version = "v2025.03.15.1425"
if slm_environment_port == "PRERELEASE":
slm_port = None
if slm_port is None:
slm_port = 5000
else:
try:
slm_port = int(slm_port)
except:
slm_port = 5000
app = Flask(__name__)
# Control how many data elements can be saved at a time from the webpage to the code. Modify values higher if continual 413 issues.
class CustomRequest(Request):
def __init__(self, *args, **kwargs):
super(CustomRequest, self).__init__(*args, **kwargs)
self.max_form_parts = 1000000 # Individual web components
app.request_class = CustomRequest
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024 * 200 # MB for submitting requests/files
# Home webpage
@app.route('/', methods=['GET', 'POST'])
@app.route('/home', methods=['GET', 'POST'])
def webpage_home():
return render_template(
'main/index.html',
segment = 'index',
html_slm_version = slm_version,
html_gen_upgrade_flag = gen_upgrade_flag,
html_slm_playlist_manager = slm_playlist_manager,
html_slm_stream_link_file_manager = slm_stream_link_file_manager,
html_slm_channels_dvr_integration = slm_channels_dvr_integration,
html_slm_media_tools_manager = slm_media_tools_manager,
html_plm_streaming_stations = plm_streaming_stations,
html_notifications = notifications
)
# Adds a notification
def notification_add(notification):
global notifications
notifications.insert(0, notification)
print(notification)
# Seach for and bookmark programs, or add manual ones
@app.route('/addprograms', methods=['GET', 'POST'])
def webpage_add_programs():
global program_search_results_prior
global country_code_input_prior
global language_code_input_prior
global entry_id_prior
global season_episodes_prior
global date_new_default_prior
global program_add_prior
global program_add_resort_panel
global program_add_filter_panel
global title_selected_prior
global release_year_selected_prior
global bookmark_action_prior
global select_program_to_bookmarks
settings = read_data(csv_settings)
country_code = settings[2]["settings"]
language_code = settings[3]["settings"]
num_results = settings[4]["settings"]
hide_bookmarked = settings[9]["settings"]
special_actions = []
special_actions = get_special_actions()
program_types = [
"MOVIE",
"SHOW",
"VIDEO"
]
program_type_default = "MOVIE"
program_add_message = ""
program_search_results = []
season_episodes = []
video_season_episodes = []
season_episode_manual_flag = None
video_manual_flag = None
end_season = None
season_episodes_manual = {}
stream_link_override_movie_flag = None
done_generate_flag = None
num_results_test = None
bookmark_actions = []
date_new_default = datetime.datetime.now().strftime('%Y-%m-%d')
if date_new_default_prior is None or date_new_default_prior == '':
date_new_default_prior = date_new_default
if request.method == 'POST':
add_programs_action = request.form['action']
program_add_input = request.form.get('program_add')
program_add_prior = program_add_input
# Cancel and restart the page
if add_programs_action == 'program_add_cancel':
program_add_prior = ''
program_add_resort_panel = ''
program_add_filter_panel = ''
# Search for a program
elif add_programs_action in ['program_add_search', 'program_new_search', 'program_new_today']:
country_code_input = request.form.get('country_code')
language_code_input = request.form.get('language_code')
hide_bookmarked_input = request.form.get('hide_bookmarked')
hide_bookmarked_input = "On" if hide_bookmarked_input == 'on' else "Off"
if add_programs_action == 'program_add_search':
num_results_input = request.form.get('num_results')
num_results_test = get_num_results(num_results_input)
if num_results_test == "pass":
program_search_results = search_bookmark(country_code_input, language_code_input, num_results_input, program_add_input)
country_code_input_prior = country_code_input
language_code_input_prior = language_code_input
program_add_resort_panel = 'on'
program_add_filter_panel = 'on'
else:
program_add_message = num_results_test
elif add_programs_action in ['program_new_search', 'program_new_today']:
if add_programs_action == 'program_new_search':
date_new_input = request.form.get('date_new')
elif add_programs_action == 'program_new_today':
date_new_input = date_new_default
date_new_default_prior = date_new_input
num_results_input = 100 # Maximum number of new programs
program_search_results = get_program_new(date_new_input, country_code_input, language_code_input, num_results_input)
program_search_results = sorted(program_search_results, key=lambda x: sort_key(x["title"].casefold()))
country_code_input_prior = country_code_input
language_code_input_prior = language_code_input
program_add_resort_panel = ''
program_add_filter_panel = 'on'
if program_search_results:
bookmarks = read_data(csv_bookmarks)
if hide_bookmarked_input == "On":
bookmarked_entry_ids = {bookmark['entry_id'] for bookmark in bookmarks}
program_search_results = [entry for entry in program_search_results if entry['entry_id'] not in bookmarked_entry_ids]
hidden_bookmarks = {bookmark['entry_id'] for bookmark in bookmarks if bookmark['bookmark_action'] == "Hide"}
program_search_results = [entry for entry in program_search_results if entry['entry_id'] not in hidden_bookmarks]
# Replace None in 'poster' with the default URL
default_poster_url = 'https://upload.wikimedia.org/wikipedia/commons/a/a9/Missing_barnstar.jpg'
for entry in program_search_results:
if entry['poster'] is None:
entry['poster'] = default_poster_url
program_search_results_prior = program_search_results
# Filter and resort search results
elif add_programs_action.startswith('program_add_resort_') or add_programs_action.startswith('hide_program_search_result_'):
if add_programs_action == 'program_add_resort_alpha':
program_search_results = sorted(program_search_results_prior, key=lambda x: sort_key(x["title"].casefold()))
program_add_resort_panel = ''
elif add_programs_action.startswith('program_add_resort_filter_'):
if add_programs_action == 'program_add_resort_filter_movie':
program_search_results = [item for item in program_search_results_prior if item['object_type'] == 'MOVIE']
elif add_programs_action == 'program_add_resort_filter_show':
program_search_results = [item for item in program_search_results_prior if item['object_type'] == 'SHOW']
program_add_filter_panel = ''
elif add_programs_action.startswith('hide_program_search_result_'):
hide_programs = []
if add_programs_action.endswith('selected'):
for key in request.form.keys():
if key.startswith('select_program_search_result_') and request.form.get(key) == 'on':
hide_program_index = int(key.split('_')[-1]) - 1
hide_programs.append(hide_program_index)
else:
hide_program_index = int(add_programs_action.split('_')[-1]) - 1
hide_programs.append(hide_program_index)
hide_programs.sort(reverse=True)
program_search_results = program_search_results_prior
for program_search_index in hide_programs:
program_search_results, program_add_message = hide_bookmark_select(program_search_results, program_search_index, country_code_input_prior, language_code_input_prior)
program_search_results_prior = program_search_results
# Select a program from the search
elif add_programs_action.startswith('program_search_result_'):
program_add_resort_panel = ''
program_add_filter_panel = ''
select_programs = []
if add_programs_action.endswith('selected'):
for key in request.form.keys():
if key.startswith('select_program_search_result_') and request.form.get(key) == 'on':
select_program_index = int(key.split('_')[-1]) - 1
select_programs.append(select_program_index)
else:
select_program_index = int(add_programs_action.split('_')[-1]) - 1
select_programs.append(select_program_index)
select_programs.sort(reverse=True)
for program_search_index in select_programs:
program_add_message, entry_id, season_episodes, object_type = search_bookmark_select(program_search_results_prior, program_search_index, country_code_input_prior, language_code_input_prior)
select_program_to_bookmarks.append({
'program_add_message': program_add_message,
'entry_id': entry_id,
'season_episodes': season_episodes,
'object_type': object_type
})
# Add a manual program
elif add_programs_action == 'program_add_manual':
release_year_input = request.form.get('release_year')
program_type_input = request.form.get('program_type')
if program_add_input is None or program_add_input == '':
program_add_message = f"{current_time()} ERROR: A program name is required for manual additions."
else:
release_year_test = get_release_year(release_year_input)
if release_year_test == "pass":
entry_id = get_manual_entry_id()
entry_id_prior = entry_id
set_bookmarks(entry_id, program_add_input, release_year_input, program_type_input, "N/A", "N/A", "N/A", "manual", "None")
program_add_message = f"{current_time()} You manually added: {program_add_input} ({release_year_input}) | {program_type_input} (ID: {entry_id})"
bookmarks = read_data(csv_bookmarks)
for bookmark in bookmarks:
if bookmark['entry_id'] == entry_id_prior:
title_selected_prior = bookmark['title']
release_year_selected_prior = bookmark['release_year']
bookmark_action_prior = bookmark['bookmark_action']
if program_type_input == "SHOW":
season_episode_manual_flag = True
elif program_type_input == "VIDEO":
video_manual_flag = True
else:
special_actions = special_actions_default.copy()
stream_link_override_movie_flag = True
done_generate_flag = True
bookmark_actions = get_bookmark_actions(program_type_input)
else:
program_add_message = release_year_test
# Create season/episode list for manual shows
elif add_programs_action == 'season_episode_manual_next':
end_season = int(request.form.get('last_season_number'))
for i in range(1, end_season + 1):
season_episodes_manual[i] = request.form.get(f'season_episode_number_{i}')
season_episodes = get_episode_list_manual(end_season, season_episodes_manual)
season_episodes_prior = season_episodes
done_generate_flag = True
special_actions = special_actions_default.copy()
bookmark_actions = get_bookmark_actions("SHOW")
# Create a video list for a manual video group
elif add_programs_action == 'video_manual_next':
number_of_videos_input = int(request.form.get('number_of_videos'))
video_season_episodes = []
for i in range(1, int(number_of_videos_input) + 1):
video_season_episode = f"Input name for Video {i:02d}"
video_season_episodes.append({
"season_episode_id": "VIDEO",
"season_episode": video_season_episode
})
season_episodes_prior = video_season_episodes
done_generate_flag = True
special_actions = special_actions_default.copy()
bookmark_actions = get_bookmark_actions("VIDEO")
# Finish or Generate Stream Links/Files. Also save Season/Episode statuses.
elif add_programs_action in [
'program_add_done',
'program_add_generate'
]:
bookmarks_statuses = read_data(csv_bookmarks_status)
# Get settings for season/episodes
if season_episodes_prior:
field_status_inputs = {}
field_season_episode_inputs = {}
field_stream_link_override_inputs = {}
field_season_episode_prefix_inputs = {}
field_special_action_inputs = {}
video_names = []
for key in request.form.keys():
if key.startswith('field_status_'):
index = key.split('_')[-1]
field_status_inputs[index] = 'unwatched' if request.form.get(key) == 'on' else 'watched'
if key.startswith('field_season_episode_'):
index = key.split('_')[-1]
field_season_episode_inputs[index] = request.form.get(key)
if key.startswith('field_stream_link_override_'):
index = key.split('_')[-1]
field_stream_link_override_inputs[index] = request.form.get(key)
if key.startswith('field_episode_prefix_'):
index = key.split('_')[-1]
field_season_episode_prefix_inputs[index] = request.form.get(key)
if key.startswith('field_special_action_'):
index = key.split('_')[-1]
field_special_action_inputs[index] = request.form.get(key)
for index in field_season_episode_inputs.keys():
season_episode_id = None
season_episode_prefix = field_season_episode_prefix_inputs.get(index)
season_episode = field_season_episode_inputs.get(index)
if season_episodes_prior[int(index) - 1]['season_episode_id'] == "VIDEO":
if season_episode is None or season_episode == '':
season_episode = season_episodes_prior[int(index) - 1]['season_episode']
elif season_episode in video_names:
season_episode = f"Duplicate Video Name {int(index):02d}"
else:
video_names.append(season_episode)
if field_status_inputs.get(index) == "unwatched":
status = field_status_inputs.get(index)
else:
status = "watched"
stream_link_override = field_stream_link_override_inputs.get(index)
special_action = field_special_action_inputs.get(index)
if season_episodes_prior[int(index) - 1]['season_episode_id'] == "VIDEO":
pass
else:
for item in season_episodes_prior:
if item["season_episode"] == season_episode:
season_episode_id = item["season_episode_id"]
break
bookmarks_statuses.append({
"entry_id": entry_id_prior,
"season_episode_id": season_episode_id,
"season_episode_prefix": season_episode_prefix,
"season_episode": season_episode,
"status": status,
"stream_link": None,
"stream_link_override": stream_link_override,
"stream_link_file": None,
"special_action": special_action,
"original_release_date": None
})
# Get settings for a Movie and write back
else:
status_movie_input = None
stream_link_override_movie_input = None
special_action_movie_input = None
status_movie_input = 'unwatched' if request.form.get('status_movie') == 'on' else 'watched'
if status_movie_input == "unwatched":
pass
else:
status_movie_input = "watched"
stream_link_override_movie_input = request.form.get('stream_link_override_movie')
special_action_movie_input = request.form.get('special_action_movie')
for bookmark_status in bookmarks_statuses:
if bookmark_status['entry_id'] == entry_id_prior:
bookmark_status['status'] = status_movie_input
bookmark_status['stream_link_override'] = stream_link_override_movie_input
bookmark_status['special_action'] = special_action_movie_input
write_data(csv_bookmarks_status, bookmarks_statuses)
if add_programs_action == 'program_add_generate':
program_add_message = generate_stream_links_single(entry_id_prior)
else:
program_add_message = f"{current_time()} INFO: Finished adding! Please remember to generate stream links and update in Channels to see this program."
# Get Bookmark Updates
field_title_input = request.form.get('field_title')
field_release_year_input = request.form.get('field_release_year')
field_bookmark_action_input = request.form.get('field_bookmark_action')
save_error_bookmarks = 0
release_year_test = get_release_year(field_release_year_input)
if release_year_test == "pass":
new_release_year = field_release_year_input
else:
program_add_message = release_year_test
program_add_message = f"{program_add_message} Saved with original 'Release Year'."
save_error_bookmarks = save_error_bookmarks + 1
if field_title_input != "":
new_title = field_title_input
else:
program_add_message = f"{current_time()} ERROR: 'Title' cannot be empty. Saved with original 'Title'."
save_error_bookmarks = save_error_bookmarks + 1
new_bookmark_action = field_bookmark_action_input
if save_error_bookmarks == 0:
bookmarks = read_data(csv_bookmarks)
for bookmark in bookmarks:
if bookmark["entry_id"] == entry_id_prior:
bookmark['title'] = new_title
bookmark['release_year'] = new_release_year
bookmark['bookmark_action'] = new_bookmark_action
write_data(csv_bookmarks, bookmarks)
if new_bookmark_action == "Hide":
remove_row_csv(csv_bookmarks_status, entry_id_prior)
program_search_results_prior = []
country_code_input_prior = None
language_code_input_prior = None
entry_id_prior = None
season_episodes_prior = []
program_add_prior = ''
title_selected_prior = None
release_year_selected_prior = None
bookmark_action_prior = None
if select_program_to_bookmarks:
for select_program_to_bookmark in select_program_to_bookmarks:
select_program_to_bookmarks.remove(select_program_to_bookmark)
program_add_message = select_program_to_bookmark['program_add_message']
entry_id = select_program_to_bookmark['entry_id']
season_episodes = select_program_to_bookmark['season_episodes']
object_type = select_program_to_bookmark['object_type']
test_terms = ("WARNING: ", "ERROR: ")
if any(term in program_add_message for term in test_terms):
pass
else:
entry_id_prior = entry_id
season_episodes_prior = season_episodes
if not season_episodes:
if object_type == "MOVIE":
stream_link_override_movie_flag = True
elif object_type == "SHOW":
program_add_message = f"{current_time()} WARNING: Selected show has no episodes, but is bookmarked in case episodes are added later."
done_generate_flag = True
bookmark_actions = get_bookmark_actions(object_type)
bookmarks = read_data(csv_bookmarks)
for bookmark in bookmarks:
if bookmark['entry_id'] == entry_id_prior:
title_selected_prior = bookmark['title']
release_year_selected_prior = bookmark['release_year']
bookmark_action_prior = bookmark['bookmark_action']
break
break
return render_template(
'main/addprograms.html',
segment='addprograms',
html_slm_version = slm_version,
html_gen_upgrade_flag = gen_upgrade_flag,
html_slm_playlist_manager = slm_playlist_manager,
html_slm_stream_link_file_manager = slm_stream_link_file_manager,
html_slm_channels_dvr_integration = slm_channels_dvr_integration,
html_slm_media_tools_manager = slm_media_tools_manager,
html_plm_streaming_stations = plm_streaming_stations,
html_valid_country_codes = valid_country_codes,
html_country_code = country_code,
html_valid_language_codes = valid_language_codes,
html_language_code = language_code,
html_num_results = num_results,
html_hide_bookmarked = hide_bookmarked,
html_program_types = program_types,
html_program_type_default = program_type_default,
html_program_add_message = program_add_message,
html_program_search_results = program_search_results,
html_season_episodes = season_episodes,
html_video_season_episodes = video_season_episodes,
html_season_episode_manual_flag = season_episode_manual_flag,
html_video_manual_flag = video_manual_flag,
html_stream_link_override_movie_flag = stream_link_override_movie_flag,
html_done_generate_flag = done_generate_flag,
html_date_new_default = date_new_default_prior,
html_program_add_prior = program_add_prior,
html_special_actions = special_actions,
html_program_add_resort_panel = program_add_resort_panel,
html_program_add_filter_panel = program_add_filter_panel,
html_bookmark_actions = bookmark_actions,
html_title_selected = title_selected_prior,
html_release_year_selected = release_year_selected_prior,
html_bookmark_action_selected = bookmark_action_prior
)
# Creates the dropdown list of 'Special Actions'
def get_special_actions():
services = []
check_services = []
services = read_data(csv_streaming_services)
check_services = [service for service in services if service["streaming_service_subscribe"] == "True"]
check_services.sort(key=lambda x: int(x.get("streaming_service_priority", float("inf"))))
# Initialize special_actions with a copy of the default list
special_actions = special_actions_default.copy()
for check_service in check_services:
prefer = f"Prefer: {check_service['streaming_service_name']}"
special_actions.append(prefer)
return special_actions
# Creates the dropdown list of 'Bookmark Actions'
def get_bookmark_actions(object_type):
bookmark_actions = bookmark_actions_default.copy()
if object_type == "SHOW":
for action in bookmark_actions_default_show_only:
action
bookmark_actions.append(action)
return bookmark_actions
# Input the number of search results to return
def get_num_results(num_results_input):
num_results_test = None
try:
if not num_results_input:
num_results_test = f"{current_time()} ERROR: 'Number of Results' is required."
num_results = int(num_results_input)
if num_results > 0:
num_results_test = "pass"
else:
num_results_test = f"{current_time()} ERROR: For 'Number of Results', please enter a positive integer."
except ValueError:
num_results_test = f"{current_time()} ERROR: 'Number of Results' must be a number."
return num_results_test
# Rules for a release year
def get_release_year(release_year_input):
release_year_test = None
release_year_min = 1888
release_year_max = datetime.datetime.now().year + 2
try:
if not release_year_input:
release_year_test = f"{current_time()} ERROR: 'Release Year' is required."
release_year = int(release_year_input)
if release_year_min <= release_year <= release_year_max:
release_year_test = "pass"
else:
release_year_test = f"{current_time()} ERROR: For 'Release Year', please enter a valid 4-digit year between {release_year_min} and {release_year_max}."
except ValueError:
release_year_test = f"{current_time()} ERROR: For 'Release Year', please enter a numeric value."
return release_year_test
# Search for a program to bookmark
def search_bookmark(country_code, language_code, num_results, program_search):
program_search_base = get_program_search(program_search, country_code, language_code, num_results)
program_search_results = extract_program_search(program_search_base)
return program_search_results
# Search for a Program on JustWatch
def get_program_search(program_search, country_code, language_code, num_results):
program_search_results = []
program_search_results_json = []
_GRAPHQL_GetSearchTitles = """
query GetSearchTitles($allowSponsoredRecommendations: SponsoredRecommendationsInput, $backdropProfile: BackdropProfile, $country: Country!, $first: Int! = 5, $format: ImageFormat, $language: Language!, $platform: Platform! = WEB, $profile: PosterProfile, $searchAfterCursor: String, $searchTitlesFilter: TitleFilter, $searchTitlesSortBy: PopularTitlesSorting! = POPULAR, $sortRandomSeed: Int! = 0) {
popularTitles(
after: $searchAfterCursor
allowSponsoredRecommendations: $allowSponsoredRecommendations
country: $country
filter: $searchTitlesFilter
first: $first
sortBy: $searchTitlesSortBy
sortRandomSeed: $sortRandomSeed
) {
edges {
...SearchTitleGraphql
__typename
}
pageInfo {
startCursor
endCursor
hasPreviousPage
hasNextPage
__typename
}
sponsoredAd {
...SponsoredAd
__typename
}
totalCount
__typename
}
}
fragment SearchTitleGraphql on PopularTitlesEdge {
cursor
node {
id
objectId
objectType
content(country: $country, language: $language) {
title
fullPath
originalReleaseYear
shortDescription
genres {
shortName
__typename
}
scoring {
imdbScore
imdbVotes
tmdbScore
tmdbPopularity
__typename
}
posterUrl(profile: $profile, format: $format)
backdrops(profile: $backdropProfile, format: $format) {
backdropUrl
__typename
}
upcomingReleases(releaseTypes: [DIGITAL]) {
releaseDate
__typename
}
__typename
}
watchNowOffer(country: $country, platform: WEB) {
id
standardWebURL
__typename
}
offers(country: $country, platform: WEB) {
monetizationType
presentationType
standardWebURL
package {
id
packageId
icon
clearName
__typename
}
id
__typename
}
__typename
}
__typename
}
fragment SponsoredAd on SponsoredRecommendationAd {
bidId
holdoutGroup
campaign {
name
externalTrackers {
type
data
__typename
}
hideRatings
hideDetailPageButton
promotionalImageUrl
promotionalVideo {
url
__typename
}
promotionalTitle
promotionalText
promotionalProviderLogo
watchNowLabel
watchNowOffer {
standardWebURL
presentationType
monetizationType
package {
id
packageId
shortName
clearName
icon
__typename
}
__typename
}
nodeOverrides {
nodeId
promotionalImageUrl
watchNowOffer {
standardWebURL
__typename
}
__typename
}
node {
nodeId: id
__typename
... on MovieOrShowOrSeason {
content(country: $country, language: $language) {
fullPath
posterUrl
title
originalReleaseYear
scoring {
imdbScore
__typename
}
externalIds {
imdbId
__typename
}
backdrops(format: $format, profile: $backdropProfile) {
backdropUrl
__typename
}
isReleased
__typename
}
objectId
objectType
offers(country: $country, platform: $platform) {
monetizationType
presentationType
package {
id
packageId
icon
clearName
__typename
}
id
__typename
}
__typename
}
... on MovieOrShow {
watchlistEntryV2 {
createdAt
__typename
}
__typename
}
... on Show {
seenState(country: $country) {
seenEpisodeCount
__typename
}
__typename
}
... on Season {
content(country: $country, language: $language) {
seasonNumber
__typename
}
show {
__typename
id
content(country: $country, language: $language) {
originalTitle
__typename
}
watchlistEntryV2 {
createdAt
__typename
}
}
__typename
}
... on GenericTitleList {
followedlistEntry {
createdAt
name
__typename
}
id
type
content(country: $country, language: $language) {
name
visibility
__typename
}
titles(country: $country, first: 40) {
totalCount
edges {
cursor
node: nodeV2 {
content(country: $country, language: $language) {
fullPath
posterUrl
title
originalReleaseYear
scoring {
imdbScore
__typename
}
isReleased
__typename
}
id
objectId
objectType
__typename
}
__typename
}
__typename
}
__typename
}
}
__typename
}
__typename
}
"""
json_data = {
'query': _GRAPHQL_GetSearchTitles,
'variables': {
"first": num_results,
"platform": "WEB",
"searchTitlesSortBy": "POPULAR",
"sortRandomSeed": 0,
"searchAfterCursor": "",
"searchTitlesFilter": {
"personId": None,
"includeTitlesWithoutUrl": True,
"searchQuery": program_search
},
"language": language_code,
"country": country_code,
"allowSponsoredRecommendations": {
"pageType": "VIEW_SEARCH",
"placement": "SEARCH_PAGE",
"language": language_code,
"country": country_code,
"geoCountry": country_code,
"appId": "3.8.2-webapp#eb6ba36",
"platform": "WEB",
"supportedFormats": [
"IMAGE",
"VIDEO"
],
"supportedObjectTypes": [
"MOVIE",
"SHOW",
"GENERIC_TITLE_LIST",
"SHOW_SEASON"
],
"testingMode": False,
"testingModeCampaignName": None
}
},
'operationName': 'GetSearchTitles',
}
try:
program_search_results = requests.post(_GRAPHQL_API_URL, headers=url_headers, json=json_data)
program_search_results_json = program_search_results.json()
except requests.RequestException as e:
print(f"\n{current_time()} WARNING: {e}. Skipping, please try again.")
return program_search_results_json
# Extract the entry_id, title, release_year, object_type, url, and short_description from the response
def extract_program_search(program_search_json):
extracted_data = []
edges = program_search_json.get("data", {}).get("popularTitles", {}).get("edges", [])
for edge in edges:
node = edge.get("node", {})
entry_id = node.get("id")
title = node.get("content", {}).get("title")
release_year = node.get("content", {}).get("originalReleaseYear")
object_type = node.get("objectType")
href = node.get("content", {}).get("fullPath")
if href is not None and href != '':
url = f"{engine_url}{href}" # Concatenate with the prefix
else:
url = None
short_description = node.get("content", {}).get("shortDescription")
poster_raw = node.get("content", {}).get("posterUrl")
if poster_raw is not None and poster_raw != '':
poster = f"{engine_image_url}{poster_raw}"
poster = poster.replace('{profile}', engine_image_profile_poster)
poster = poster.replace('{format}', 'jpg')
else:
poster = None
score_raw = node.get("content", {}).get("scoring", {}).get("imdbScore")
try:
score = f"{float(score_raw):.1f}"
except (ValueError, TypeError):
score = "N/A" # Handle the case where the score is not a valid number
offers_raw = node.get("offers")
offers_raw_list = []
for offer_raw in offers_raw:
offer_raw_icon = offer_raw["package"]["icon"]
offer_raw_icon = f"{engine_image_url}{offer_raw_icon}"
offer_raw_icon = offer_raw_icon.replace('{profile}', engine_image_profile_icon)
offer_raw_icon = offer_raw_icon.replace('{format}', 'png')
offer_raw_clearname = offer_raw["package"]["clearName"]
offers_raw_list.append({"icon": offer_raw_icon, "sort": offer_raw_clearname})
offers_raw_list_sorted = sorted(offers_raw_list, key=lambda x: sort_key(x["sort"]))
icons_list = []
icons_list = [offer["icon"] for offer in offers_raw_list_sorted]
offers_list = list(dict.fromkeys(icons_list))
extracted_data.append({
"entry_id": entry_id,
"title": title,
"release_year": release_year,
"object_type": object_type,
"url": url,
"short_description": short_description,
"poster": poster,
"score": score,
"offers_list": offers_list
})
return extracted_data