forked from ArdianaLeek/VodRecovery
-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
vod_recovery.py
2732 lines (2172 loc) · 98.4 KB
/
vod_recovery.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 hashlib
import json
import csv
import os
import random
import re
import subprocess
import tkinter as tk
import sys
from time import sleep
from shutil import rmtree, copyfileobj
from datetime import datetime, timedelta
from tkinter import filedialog
from urllib.parse import urlparse
from unicodedata import normalize
import asyncio
import grequests
import aiohttp
from bs4 import BeautifulSoup
from seleniumbase import SB
import requests
from packaging import version
import ffmpeg_downloader as ffdl
from tqdm import tqdm
from ffmpeg_progress_yield import FfmpegProgress
CURRENT_VERSION = "1.3.6"
SUPPORTED_FORMATS = [".mp4", ".mkv", ".mov", ".avi", ".ts"]
if sys.platform == 'win32':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
def read_config_by_key(config_file, key):
script_dir = os.path.dirname(os.path.realpath(__file__))
config_path = os.path.join(script_dir, "config", f"{config_file}.json")
with open(config_path, "r", encoding="utf-8") as input_config_file:
config = json.load(input_config_file)
return config.get(key, None)
def get_default_video_format():
default_video_format = read_config_by_key("settings", "DEFAULT_VIDEO_FORMAT")
if default_video_format in SUPPORTED_FORMATS:
return default_video_format
return ".mp4"
def get_ffmpeg_format(file_extension):
format_map = {
'.mp4': 'mp4',
'.mkv': 'matroska',
'.ts': 'mpegts',
'.mov': 'mov',
'.avi': 'avi'
}
return format_map.get(file_extension, 'mp4')
def get_default_directory():
default_directory = read_config_by_key("settings", "DEFAULT_DIRECTORY")
if not default_directory:
default_directory = "~/Downloads/"
default_directory = os.path.expanduser(default_directory)
if not os.path.exists(default_directory):
try:
os.makedirs(default_directory)
except Exception:
default_directory = os.path.expanduser("~/Downloads/")
if not os.path.exists(default_directory):
os.makedirs(default_directory)
if os.name == "nt":
default_directory = default_directory.replace("/", "\\")
return default_directory
def get_default_downloader():
try:
default_downloader = read_config_by_key("settings", "DEFAULT_DOWNLOADER")
if default_downloader in ["ffmpeg", "yt-dlp"]:
return default_downloader
return "ffmpeg"
except Exception:
return "ffmpeg"
def get_yt_dlp_custom_options():
try:
custom_options = read_config_by_key("settings", "YT_DLP_OPTIONS")
if custom_options:
return custom_options.split()
return []
except Exception:
return []
def print_main_menu():
default_video_format = get_default_video_format() or "mp4"
menu_options = [
"1) VOD Recovery",
"2) Clip Recovery",
f"3) Download VOD ({default_video_format.lstrip('.')})",
"4) Unmute & Check M3U8 Availability",
"5) Options",
"6) Exit",
]
while True:
print("\n".join(menu_options))
try:
choice = int(input("\nChoose an option: "))
if choice not in range(1, len(menu_options) + 1):
raise ValueError("Invalid option")
return choice
except ValueError:
print("\n✖ Invalid option! Please try again:\n")
def print_video_mode_menu():
vod_type_options = [
"1) Website Video Recovery",
"2) Manual Recovery",
"3) Bulk Video Recovery from SullyGnome CSV Export",
"4) Return",
]
while True:
print("\n".join(vod_type_options))
try:
choice = int(input("\nSelect VOD Recovery Type: "))
if choice not in range(1, len(vod_type_options) + 1):
raise ValueError("Invalid option")
return choice
except ValueError:
print("\n✖ Invalid option! Please try again:\n")
def print_video_recovery_menu():
vod_recovery_options = [
"1) Website Video Recovery",
"2) Manual Recovery",
"3) Return",
]
while True:
print("\n".join(vod_recovery_options))
try:
choice = int(input("\nSelect VOD Recovery Method: "))
if choice not in range(1, len(vod_recovery_options) + 1):
raise ValueError("Invalid option")
return choice
except ValueError:
print("\n✖ Invalid option! Please try again:\n")
def print_clip_type_menu():
clip_type_options = [
"1) Recover All Clips from a VOD",
"2) Find Random Clips from a VOD",
"3) Download Clip from Twitch URL",
"4) Bulk Recover Clips from SullyGnome CSV Export",
"5) Return",
]
while True:
print("\n".join(clip_type_options))
try:
choice = int(input("\nSelect Clip Recovery Type: "))
if choice not in range(1, len(clip_type_options) + 1):
raise ValueError("Invalid option")
return choice
except ValueError:
print("\n✖ Invalid option! Please try again:\n")
def print_clip_recovery_menu():
clip_recovery_options = [
"1) Website Clip Recovery",
"2) Manual Clip Recovery",
"3) Return",
]
while True:
print("\n".join(clip_recovery_options))
try:
choice = int(input("\nSelect Clip Recovery Method: "))
if choice not in range(1, len(clip_recovery_options) + 1):
raise ValueError("Invalid option")
return choice
except ValueError:
print("\n✖ Invalid option! Please try again:\n")
def print_bulk_clip_recovery_menu():
bulk_clip_recovery_options = [
"1) Single CSV File",
"2) Multiple CSV Files",
"3) Return",
]
while True:
print("\n".join(bulk_clip_recovery_options))
try:
choice = int(input("\nSelect Bulk Clip Recovery Source: "))
if choice not in range(1, len(bulk_clip_recovery_options) + 1):
raise ValueError("Invalid option")
return str(choice)
except ValueError:
print("\n✖ Invalid option! Please try again:\n")
def print_clip_format_menu():
clip_format_options = [
"1) Default Format ([VodID]-offset-[interval])",
"2) Alternate Format (vod-[VodID]-offset-[interval])",
"3) Legacy Format ([VodID]-index-[interval])",
"4) Return",
]
print()
while True:
print("\n".join(clip_format_options))
try:
choice = int(input("\nSelect Clip URL Format: "))
if choice == 4:
return run_vod_recover()
if choice not in range(1, len(clip_format_options) + 1):
raise ValueError("Invalid option")
else:
return str(choice)
except ValueError:
print("\n✖ Invalid option! Please try again:\n")
def print_download_type_menu():
download_type_options = [
"1) From M3U8 Link",
"2) From M3U8 File",
"3) From Twitch URL (Only for VODs or Highlights still up on Twitch)",
"4) Return",
]
while True:
print("\n".join(download_type_options))
try:
choice = int(input("\nSelect Download Type: "))
if choice not in range(1, len(download_type_options) + 1):
raise ValueError("Invalid option")
return choice
except ValueError:
print("\n✖ Invalid option! Please try again:\n")
def print_handle_m3u8_availability_menu():
handle_m3u8_availability_options = [
"1) Check if M3U8 file has muted segments",
"2) Unmute & Remove invalid segments",
"3) Return",
]
while True:
print("\n".join(handle_m3u8_availability_options))
try:
choice = int(input("\nSelect Option: "))
if choice not in range(1, len(handle_m3u8_availability_options) + 1):
raise ValueError("Invalid option")
return choice
except ValueError:
print("\n✖ Invalid option! Please try again:\n")
def print_options_menu():
options_menu = [
f"1) Set Default Video Format \033[94m({get_default_video_format().lstrip('.') or 'mp4'})\033[0m",
f"2) Set Download Directory \033[94m({get_default_directory() or '~/Downloads/'})\033[0m",
f"3) Set Default Downloader \033[94m({read_config_by_key('settings', 'DEFAULT_DOWNLOADER') or 'ffmpeg'})\033[0m",
"4) Check for Updates",
"5) Open settings.json File",
"6) Help",
"7) Return",
]
while True:
print("\n".join(options_menu))
try:
choice = int(input("\nSelect Option: "))
if choice not in range(1, len(options_menu) + 1):
raise ValueError("Invalid option")
return choice
except ValueError:
print("\n✖ Invalid option! Please try again:\n")
def print_get_m3u8_link_menu():
m3u8_url = input("Enter M3U8 Link: ").strip(" \"'")
if m3u8_url.endswith(".m3u8"):
return m3u8_url
print("\n✖ Invalid M3U8 link! Please try again:\n")
return print_get_m3u8_link_menu()
def quote_filename(filename):
if not filename.startswith("'") and not filename.endswith("'"):
filename = filename.replace("'", "'\"'\"'")
filename = f"'{filename}'"
return filename
def ask_to_redownload(output_path):
while True:
choice = input(f"\nFile already exists at {output_path}. Do you want to redownload it? (Y/N): ").strip().lower()
if choice in ['y', 'n']:
return choice == 'y'
print("Invalid input! Please enter 'Y' for Yes or 'N' for No.")
def get_websites_tracker_url():
while True:
tracker_url = input("Enter Twitchtracker/Streamscharts/Sullygnome url: ").strip()
if re.match(r"^(https?:\/\/)?(www\.)?(twitchtracker\.com|streamscharts\.com|sullygnome\.com)\/.*", tracker_url):
return tracker_url
print("\n✖ Invalid URL! Please enter a URL from Twitchtracker, Streamscharts, or Sullygnome.\n")
def print_get_twitch_url_menu():
twitch_url = input("Enter Twitch URL: ").strip(" \"'")
if "twitch.tv" in twitch_url:
return twitch_url
print("\n✖ Invalid Twitch URL! Please try again:\n")
return print_get_twitch_url_menu()
def get_twitch_or_tracker_url():
while True:
url = input("Enter Twitchtracker/Streamscharts/Sullygnome/Twitch URL: ").strip()
if re.match(r"^(https?:\/\/)?(www\.)?(twitchtracker\.com|streamscharts\.com|sullygnome\.com|twitch\.tv)\/.*", url):
return url
print("\n✖ Invalid URL! Please enter a URL from Twitchtracker, Streamscharts, Sullygnome, or Twitch.\n")
def get_latest_version(retries=3):
for attempt in range(retries):
try:
res = requests.get("https://api.github.com/repos/MacielG1/VodRecovery/releases/latest", timeout=30)
if res.status_code == 200:
release_info = res.json()
return release_info["tag_name"]
else:
return None
except Exception:
if attempt < retries - 1:
sleep(3)
continue
else:
return None
def check_for_updates():
latest_version = version.parse(get_latest_version())
current_version = version.parse(CURRENT_VERSION)
if latest_version and current_version:
if latest_version != current_version:
print(f"\n\033[34mNew version ({latest_version}) - Download at: https://github.com/MacielG1/VodRecovery/releases/latest\033[0m")
input("\nPress Enter to continue...")
return run_vod_recover()
else:
print(f"\n\033[92m\u2713 Vod Recovery is updated to {CURRENT_VERSION}!\033[0m")
input("\nPress Enter to continue...")
return
else:
print("\n✖ Could not check for updates!")
def sanitize_filename(filename, restricted=False):
if filename == "":
return ""
def replace_insane(char):
if not restricted and char == "\n":
return "\0 "
elif not restricted and char in '"*:<>?|/\\':
return {"/": "\u29f8", "\\": "\u29f9"}.get(char, chr(ord(char) + 0xFEE0))
elif char == "?" or ord(char) < 32 or ord(char) == 127:
return ""
elif char == '"':
return "" if restricted else "'"
elif char == ":":
return "\0_\0-" if restricted else "\0 \0-"
elif char in "\\/|*<>":
return "\0_"
if restricted and (
char in "!&'()[]{}$;`^,#" or char.isspace() or ord(char) > 127
):
return "\0_"
return char
if restricted:
filename = normalize("NFKC", filename)
filename = re.sub(
r"[0-9]+(?::[0-9]+)+", lambda m: m.group(0).replace(":", "_"), filename
)
result = "".join(map(replace_insane, filename))
result = re.sub(r"(\0.)(?:(?=\1)..)+", r"\1", result)
strip_re = r"(?:\0.|[ _-])*"
result = re.sub(f"^\0.{strip_re}|{strip_re}\0.$", "", result)
result = result.replace("\0", "") or "_"
while "__" in result:
result = result.replace("__", "_")
result = result.strip("_")
if restricted and result.startswith("-_"):
result = result[2:]
if result.startswith("-"):
result = "_" + result[len("-") :]
result = result.lstrip(".")
if not result:
result = "_"
return result
def read_config_file(config_file):
current_dir = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(current_dir, "config", f"{config_file}.json")
with open(config_path, encoding="utf-8") as config_file:
config = json.load(config_file)
return config
def open_file(file_path):
if sys.platform.startswith("darwin"):
subprocess.call(("open", file_path))
elif os.name == "nt":
subprocess.Popen(["start", file_path], shell=True)
elif os.name == "posix":
subprocess.call(("xdg-open", file_path))
else:
print(f"\nFile Location: {file_path}")
def print_help():
try:
help_data = read_config_file("help")
print("\n--------------- Help Section ---------------")
for menu, options in help_data.items():
print(f"\n{menu.replace('_', ' ').title()}:")
for option, description in options.items():
print(f" {option}: {description}")
print("\n --------------- End of Help Section ---------------\n")
except Exception as error:
print(f"An unexpected error occurred: {error}")
def read_text_file(text_file_path):
lines = []
with open(text_file_path, "r", encoding="utf-8") as text_file:
for line in text_file:
lines.append(line.rstrip())
return lines
def write_text_file(input_text, destination_path):
with open(destination_path, "a+", encoding="utf-8") as text_file:
text_file.write(input_text + "\n")
def write_m3u8_to_file(m3u8_link, destination_path, max_retries=5):
attempt = 0
while attempt < max_retries:
try:
response = requests.get(m3u8_link, timeout=10)
response.raise_for_status()
with open(destination_path, "w", encoding="utf-8") as m3u8_file:
m3u8_file.write(response.text)
return m3u8_file
except Exception:
attempt += 1
sleep(1)
raise Exception(f"Failed to write M3U8 after {max_retries} attempts.")
def read_csv_file(csv_file_path):
with open(csv_file_path, "r", encoding="utf-8") as csv_file:
return list(csv.reader(csv_file))
def get_use_progress_bar():
try:
use_progress_bar = read_config_by_key("settings", "USE_PROGRESS_BAR")
return use_progress_bar if use_progress_bar is not None else True
except Exception:
return True
def get_current_version():
current_version = read_config_by_key("settings", "CURRENT_VERSION")
if current_version:
return current_version
else:
sys.exit("\033[91m \n✖ Unable to retrieve CURRENT_VERSION from the settings.json files \n\033[0m")
def get_log_filepath(streamer_name, video_id):
log_filename = os.path.join(get_default_directory(), f"{streamer_name}_{video_id}_log.txt")
return log_filename
def get_vod_filepath(streamer_name, video_id):
vod_filename = os.path.join(get_default_directory(), f"{streamer_name}_{video_id}.m3u8")
return vod_filename
def get_script_directory():
return os.path.dirname(os.path.realpath(__file__))
def return_user_agent():
script_dir = os.path.dirname(os.path.abspath(__file__))
user_agents = read_text_file(os.path.join(script_dir, "lib", "user_agents.txt"))
header = {"user-agent": random.choice(user_agents)}
return header
def calculate_epoch_timestamp(timestamp, seconds):
try:
epoch_timestamp = ((datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S") + timedelta(seconds=seconds)) - datetime(1970, 1, 1)).total_seconds()
return epoch_timestamp
except ValueError:
return None
def calculate_days_since_broadcast(start_timestamp):
if start_timestamp is None:
return 0
vod_age = datetime.today() - datetime.strptime(start_timestamp, "%Y-%m-%d %H:%M:%S")
return max(vod_age.days, 0)
def is_video_muted(m3u8_link):
response = requests.get(m3u8_link, timeout=10).text
return bool("unmuted" in response)
def calculate_broadcast_duration_in_minutes(hours, minutes):
return (int(hours) * 60) + int(minutes)
def calculate_max_clip_offset(video_duration):
return (video_duration * 60) + 2000
def parse_streamer_from_csv_filename(csv_filename):
_, file_name = os.path.split(csv_filename)
streamer_name = file_name.strip()
return streamer_name.split()[0]
def parse_streamer_from_m3u8_link(m3u8_link):
indices = [i.start() for i in re.finditer("_", m3u8_link)]
streamer_name = m3u8_link[indices[0] + 1 : indices[-2]]
return streamer_name
def parse_video_id_from_m3u8_link(m3u8_link):
indices = [i.start() for i in re.finditer("_", m3u8_link)]
video_id = m3u8_link[
indices[0] + len(parse_streamer_from_m3u8_link(m3u8_link)) + 2 : indices[-1]
]
return video_id
def parse_streamer_and_video_id_from_m3u8_link(m3u8_link):
indices = [i.start() for i in re.finditer("_", m3u8_link)]
streamer_name = m3u8_link[indices[0] + 1 : indices[-2]]
video_id = m3u8_link[indices[0] + len(streamer_name) + 2 : indices[-1]]
return f" - {streamer_name} [{video_id}]"
def parse_streamscharts_url(streamscharts_url):
try:
streamer_name = streamscharts_url.split("/channels/", 1)[1].split("/streams/")[0]
video_id = streamscharts_url.split("/streams/", 1)[1]
return streamer_name, video_id
except IndexError:
print("\033[91m \n✖ Invalid Streamscharts URL! Please try again:\n \033[0m")
input("Press Enter to continue...")
return run_vod_recover()
def parse_twitchtracker_url(twitchtracker_url):
try:
streamer_name = twitchtracker_url.split(".com/", 1)[1].split("/streams/")[0]
video_id = twitchtracker_url.split("/streams/", 1)[1]
return streamer_name, video_id
except IndexError:
print("\033[91m \n✖ Invalid Twitchtracker URL! Please try again:\n \033[0m")
input("Press Enter to continue...")
return run_vod_recover()
def parse_sullygnome_url(sullygnome_url):
try:
streamer_name = sullygnome_url.split("/channel/", 1)[1].split("/")[0]
video_id = sullygnome_url.split("/stream/", 1)[1]
return streamer_name, video_id
except IndexError:
print("\033[91m \n✖ Invalid SullyGnome URL! Please try again:\n \033[0m")
input("Press Enter to continue...")
return run_vod_recover()
def set_default_video_format():
print("\nSelect the default video format")
for i, format_option in enumerate(SUPPORTED_FORMATS, start=1):
print(f"{i}) {format_option.lstrip('.')}")
user_option = str(input("\nChoose a video format: "))
if user_option in [str(i) for i in range(1, len(SUPPORTED_FORMATS) + 1)]:
selected_format = SUPPORTED_FORMATS[int(user_option) - 1]
script_dir = get_script_directory()
config_file_path = os.path.join(script_dir, "config", "settings.json")
try:
with open(config_file_path, "r", encoding="utf-8") as config_file:
config_data = json.load(config_file)
if not config_data:
print("Error: No config file found.")
return
config_data["DEFAULT_VIDEO_FORMAT"] = selected_format
with open(config_file_path, "w", encoding="utf-8") as config_file:
json.dump(config_data, config_file, indent=4)
print(f"\n\033[92m\u2713 Default video format set to: {selected_format.lstrip('.')}\033[0m")
except (FileNotFoundError, json.JSONDecodeError) as error:
print(f"Error: {error}")
else:
print("\n✖ Invalid option! Please try again:\n")
return
def set_default_directory():
try:
print("\nSelect the default directory")
window = tk.Tk()
window.wm_attributes("-topmost", 1)
window.withdraw()
file_path = filedialog.askdirectory(
parent=window, initialdir=dir, title="Select A Default Directory"
)
if file_path:
if not file_path.endswith("/"):
file_path += "/"
script_dir = get_script_directory()
config_file_path = os.path.join(script_dir, "config", "settings.json")
try:
with open(config_file_path, "r", encoding="utf-8") as config_file:
config_data = json.load(config_file)
config_data["DEFAULT_DIRECTORY"] = file_path
with open(config_file_path, "w", encoding="utf-8") as config_file:
json.dump(config_data, config_file, indent=4)
print(f"\n\033[92m\u2713 Default directory set to: {file_path}\033[0m")
except (FileNotFoundError, json.JSONDecodeError) as error:
print(f"Error: {error}")
else:
print("\nNo folder selected! Returning to main menu...")
window.destroy()
except tk.TclError:
file_path = input("Enter the full path to the default directory: ").strip(' "\'')
while True:
if not file_path:
print("\nNo directory entered! Returning to main menu...")
return
file_path = os.path.expanduser(file_path)
try:
os.makedirs(file_path, exist_ok=True)
except Exception as e:
file_path = input(f"Error creating directory: {e}\nEnter a valid path: ").strip(' "\'')
continue
if not file_path.endswith("/"):
file_path += "/"
script_dir = get_script_directory()
config_file_path = os.path.join(script_dir, "config", "settings.json")
try:
with open(config_file_path, "r", encoding="utf-8") as config_file:
config_data = json.load(config_file)
config_data["DEFAULT_DIRECTORY"] = file_path
with open(config_file_path, "w", encoding="utf-8") as config_file:
json.dump(config_data, config_file, indent=4)
print(f"\n\033[92m\u2713 Default directory set to: {file_path}\033[0m")
break
except (FileNotFoundError, json.JSONDecodeError) as error:
print(f"Error: {error}")
return
def set_default_downloader():
# Choose between ffmpeg and yt-dlp
print("\nSelect the default downloader")
DOWNLOADERS = ["ffmpeg", "yt-dlp"]
for i, downloader_option in enumerate(DOWNLOADERS, start=1):
print(f"{i}) {downloader_option.lstrip('.')}")
user_option = str(input("\nChoose a downloader: "))
if user_option in [str(i) for i in range(1, len(DOWNLOADERS) + 1)]:
selected_downloader = DOWNLOADERS[int(user_option) - 1]
if selected_downloader == "yt-dlp":
get_yt_dlp_path()
script_dir = get_script_directory()
config_file_path = os.path.join(script_dir, "config", "settings.json")
try:
with open(config_file_path, "r", encoding="utf-8") as config_file:
config_data = json.load(config_file)
config_data["DEFAULT_DOWNLOADER"] = selected_downloader
with open(config_file_path, "w", encoding="utf-8") as config_file:
json.dump(config_data, config_file, indent=4)
print(f"\n\033[92m\u2713 Default downloader set to: {selected_downloader}\033[0m")
except (FileNotFoundError, json.JSONDecodeError) as error:
print(f"Error: {error}")
else:
print("\n✖ Invalid option! Please try again:\n")
return
def get_m3u8_file_dialog():
try:
window = tk.Tk()
window.wm_attributes("-topmost", 1)
window.withdraw()
directory = get_default_directory()
file_path = filedialog.askopenfilename(
parent=window,
initialdir=directory,
title="Select A File",
filetypes=(("M3U8 files", "*.m3u8"), ("All files", "*")),
)
window.destroy()
return file_path
except tk.TclError:
file_path = input("Enter the full path to the M3U8 file: ").strip(' "\'')
while not file_path:
return None
while not os.path.exists(file_path):
file_path = input("File does not exist! Enter a valid path: ").strip(' "\'')
return file_path
def parse_vod_filename(m3u8_video_filename):
base = os.path.basename(m3u8_video_filename)
streamer_name, video_id = base.split(".m3u8", 1)[0].rsplit("_", 1)
return streamer_name, video_id
def parse_vod_filename_with_Brackets(m3u8_video_filename):
base = os.path.basename(m3u8_video_filename)
streamer_name, video_id = base.split(".m3u8", 1)[0].rsplit("_", 1)
return f" - {streamer_name} [{video_id}]"
def remove_chars_from_ordinal_numbers(datetime_string):
ordinal_numbers = ["th", "nd", "st", "rd"]
for exclude_string in ordinal_numbers:
if exclude_string in datetime_string:
return datetime_string.replace(datetime_string.split(" ")[1], datetime_string.split(" ")[1][:-len(exclude_string)])
def generate_website_links(streamer_name, video_id, tracker_url=None):
website_list = [
f"https://sullygnome.com/channel/{streamer_name}/stream/{video_id}",
f"https://twitchtracker.com/{streamer_name}/streams/{video_id}",
f"https://streamscharts.com/channels/{streamer_name}/streams/{video_id}",
]
if tracker_url:
website_list = [link for link in website_list if tracker_url not in link]
return website_list
def convert_url(url, target):
# converts url to the specified target website
patterns = {
"sullygnome": "https://sullygnome.com/channel/{}/stream/{}",
"twitchtracker": "https://twitchtracker.com/{}/streams/{}",
"streamscharts": "https://streamscharts.com/channels/{}/streams/{}",
}
parsed_url = urlparse(url)
streamer, video_id = None, None
if "sullygnome" in url:
streamer = parsed_url.path.split("/")[2]
video_id = parsed_url.path.split("/")[4]
elif "twitchtracker" in url:
streamer = parsed_url.path.split("/")[1]
video_id = parsed_url.path.split("/")[3]
elif "streamscharts" in url:
streamer = parsed_url.path.split("/")[2]
video_id = parsed_url.path.split("/")[4]
if streamer and video_id:
return patterns[target].format(streamer, video_id)
def extract_offset(clip_url):
clip_offset = re.search(r"(?:-offset|-index)-(\d+)", clip_url)
return clip_offset.group(1)
def get_clip_format(video_id, offsets):
default_clip_list = [f"https://clips-media-assets2.twitch.tv/{video_id}-offset-{i}.mp4" for i in range(0, offsets, 2)]
alternate_clip_list = [f"https://clips-media-assets2.twitch.tv/vod-{video_id}-offset-{i}.mp4" for i in range(0, offsets, 2)]
legacy_clip_list = [f"https://clips-media-assets2.twitch.tv/{video_id}-index-{i:010}.mp4" for i in range(offsets)]
clip_format_dict = {
"1": default_clip_list,
"2": alternate_clip_list,
"3": legacy_clip_list,
}
return clip_format_dict
def get_random_clip_information():
while True:
url = get_websites_tracker_url()
if "streamscharts" in url:
_, video_id = parse_streamscharts_url(url)
break
if "twitchtracker" in url:
_, video_id = parse_twitchtracker_url(url)
break
if "sullygnome" in url:
_, video_id = parse_sullygnome_url(url)
break
print("\n✖ Link not supported! Please try again:\n")
while True:
duration = get_time_input_HH_MM("Enter stream duration in (HH:MM) format: ")
hours, minutes = map(int, duration.split(":"))
if hours >= 0 and minutes >= 0:
break
return video_id, hours, minutes
def manual_clip_recover():
while True:
streamer_name = input("Enter the Streamer Name: ")
if streamer_name.strip():
break
else:
print("\n✖ No streamer name! Please try again:\n")
while True:
video_id = input("Enter the Video ID (from: Twitchtracker/Streamscharts/Sullygnome): ")
if video_id.strip():
break
else:
print("\n✖ No video ID! Please try again:\n")
while True:
duration = get_time_input_HH_MM("Enter stream duration in (HH:MM) format: ")
hours, minutes = map(int, duration.split(":"))
if hours >= 0 and minutes >= 0:
total_minutes = hours * 60 + minutes
break
clip_recover(streamer_name, video_id, total_minutes)
def website_clip_recover():
tracker_url = get_websites_tracker_url()
if not tracker_url.startswith("https://"):
tracker_url = "https://" + tracker_url
if "streamscharts" in tracker_url:
streamer, video_id = parse_streamscharts_url(tracker_url)
print("\nRetrieving stream duration from Streamscharts")
duration_streamscharts = parse_duration_streamscharts(tracker_url)
# print(f"Duration: {duration_streamscharts}")
clip_recover(streamer, video_id, int(duration_streamscharts))
elif "twitchtracker" in tracker_url:
streamer, video_id = parse_twitchtracker_url(tracker_url)
print("\nRetrieving stream duration from Twitchtracker")
duration_twitchtracker = parse_duration_twitchtracker(tracker_url)
# print(f"Duration: {duration_twitchtracker}")
clip_recover(streamer, video_id, int(duration_twitchtracker))
elif "sullygnome" in tracker_url:
streamer, video_id = parse_sullygnome_url(tracker_url)
print("\nRetrieving stream duration from Sullygnome")
duration_sullygnome = parse_duration_sullygnome(tracker_url)
if duration_sullygnome is None:
print("Could not retrieve duration from Sullygnome. Try a different URL.\n")
return print_main_menu()
# print(f"Duration: {duration_sullygnome}")
clip_recover(streamer, video_id, int(duration_sullygnome))
else:
print("\n✖ Link not supported! Try again...\n")
return run_vod_recover()
def manual_vod_recover():
while True:
streamer_name = input("Enter the Streamer Name: ")
if streamer_name.lower().strip():
break
print("\n✖ No streamer name! Please try again:\n")
while True:
video_id = input("Enter the Video ID (from: Twitchtracker/Streamscharts/Sullygnome): ")
if video_id.strip():
break
else:
print("\n✖ No video ID! Please try again:\n")
timestamp = get_time_input_YYYY_MM_DD_HH_MM_SS("Enter VOD Datetime YYYY-MM-DD HH:MM:SS (24-hour format, UTC): ")
m3u8_link = vod_recover(streamer_name, video_id, timestamp)
if m3u8_link is None:
sys.exit("No M3U8 link found! Exiting...")
m3u8_source = process_m3u8_configuration(m3u8_link)
handle_download_menu(m3u8_source)
def handle_vod_recover(url, url_parser, datetime_parser, website_name):
streamer, video_id = url_parser(url)
print(f"Checking {streamer} VOD ID: {video_id}")
stream_datetime, source_duration = datetime_parser(url)
m3u8_link = vod_recover(streamer, video_id, stream_datetime, url)
if m3u8_link is None:
input(f"\nNo M3U8 link found from {website_name}! Press Enter to return...")
return run_vod_recover()
m3u8_source = process_m3u8_configuration(m3u8_link)
m3u8_duration = return_m3u8_duration(m3u8_link)
if source_duration and int(source_duration) >= m3u8_duration + 10:
print(f"The duration from {website_name} exceeds the M3U8 duration. This may indicate a split stream, try checking Streamscharts for another URL.")
return m3u8_source, stream_datetime
def website_vod_recover():
url = get_twitch_or_tracker_url()
if not url.startswith("https://"):
url = "https://" + url
if "streamscharts" in url:
return handle_vod_recover(url, parse_streamscharts_url, parse_datetime_streamscharts, "Streamscharts")
if "twitchtracker" in url:
return handle_vod_recover(url, parse_twitchtracker_url, parse_datetime_twitchtracker, "Twitchtracker")
if "sullygnome" in url:
new_tracker_url = re.sub(r"/\d+/", "/", url)
return handle_vod_recover(new_tracker_url, parse_sullygnome_url, parse_datetime_sullygnome, "Sullygnome")
twitch_recover(url)
print("\n✖ Link not supported! Returning to main menu...")
return run_vod_recover()
def get_all_clip_urls(clip_format_dict, clip_format_list):
combined_clip_format_list = []
for key, value in clip_format_dict.items():
if key in clip_format_list:
combined_clip_format_list += value
return combined_clip_format_list