-
Notifications
You must be signed in to change notification settings - Fork 1
/
releaser_CLI.py
1602 lines (1322 loc) · 56.1 KB
/
releaser_CLI.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
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
##
# Todo
#
#
# Debug ON/OFF
DEBUG = 0
# iMPORT ALL MODULES
import json
import sqlite3
import platform
import random
import re
import threading
import requests
import socket
import binascii
import time
import datetime
import os
import sys
import shutil
import string
from pymediainfo import MediaInfo
import pyfiglet
# iMPORT UPDATER
import updater
try:
from ftplib import FTP, error_perm, FTP_TLS
except:
print(f"Error: Missing ftplib, install it now")
os.system("pip install ftplib")
try:
import configparser
except:
print(f"Error: Missing configparser, install it now")
os.system("pip install configparser")
# END OF iMPORT
if platform.system() == 'Linux':
linux = 1
separator = "/"
elif platform.system() == 'Windows':
linux = 0
separator = "\\"
else:
print(f"Unsupported OS {platform.system()}")
sys.exit(1)
___AUTHOR___ = 'zer0.de^r00tSec'
___VERSION___ = '2.2.3'
if linux == 1:
# LiNUX COLOR CODES (SHELL)
BLACK = "\033[0;30m" # Black
RED = "\033[0;31m" # Red
GREEN = "\033[0;32m" # Green
YELLOW = "\033[0;33m" # Yellow
BLUE = "\033[0;34m" # Blue
PURPLE = "\033[0;35m" # Purple
CYAN = "\033[0;36m" # Cyan
WHITE = "\033[0;37m" # White
ENDC = "\033[0m" # Clear/return
else:
# WiNDOWS COLOR CODES (CMD)
os.system("")
BLACK = "\033[0;30m" # Black
RED = "\033[0;31m" # Red
GREEN = "\033[0;32m" # Green
YELLOW = "\033[0;33m" # Yellow
BLUE = "\033[0;34m" # Blue
PURPLE = "\033[0;35m" # Purple
CYAN = "\033[0;36m" # Cyan
WHITE = "\033[0;37m" # White
ENDC = "\033[0m" # Clear/return
# CODE START
DATABASE_FILE = 'releaser.db'
config_file = './config/config.ini'
IMDB_LINK = None
class IRC:
UTF8 = "UTF-8"
def __init__(self):
self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def send(self, chan, msg):
self.irc.sendall(bytes(f"PRIVMSG {chan} {msg}\n", IRC.UTF8))
# DEFiNES THE SOCKET
def connect(self, server, port, channel, botnick, server_pw, channel_pw):
try:
self.irc.connect((server, port)) # connects to the server
self.irc.send(bytes(f"PASS {server_pw}\r\n", IRC.UTF8))
# user authentication
self.irc.send(
bytes(f"USER {botnick} {botnick} {botnick} :This is a fun bot!\r\n", IRC.UTF8))
self.irc.send(bytes(f"NICK {botnick}\r\n", IRC.UTF8))
time.sleep(2)
# join the chan
self.irc.send(bytes(f"JOIN {channel} {channel_pw}\r\n", IRC.UTF8))
return True
except Exception as e:
print(f"Error: Failed to connect to {server}:{port}. {e}")
return False
def quit(self):
self.irc.close()
def create_database():
print(f"{CYAN} [!!] Creating Database please wait..")
conn = sqlite3.connect(DATABASE_FILE)
conn.close()
conn = sqlite3.connect(DATABASE_FILE)
c = conn.cursor()
# Create a table if it doesn't exist
c.execute('''CREATE TABLE IF NOT EXISTS data
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT,
LINK_ID TEXT)''')
conn.commit()
conn.close()
def select_data(name):
conn = sqlite3.connect(DATABASE_FILE)
c = conn.cursor()
# Select data
c.execute("SELECT LINK_ID FROM data WHERE NAME = ?", (name,))
result = c.fetchone()
conn.close()
if result:
return result[0]
else:
return ""
def insert_data(name, link_id):
print(f"{CYAN} [!!] Insert Data: {name} {link_id}")
conn = sqlite3.connect(DATABASE_FILE)
c = conn.cursor()
# Enter data (IGNORE INSERT uses INSERT OR IGNORE to ignore already existing entries)
c.execute(
"INSERT OR IGNORE INTO data (NAME, LINK_ID) VALUES (?, ?)", (name, link_id))
conn.commit()
conn.close()
def delete_data(name):
print(f"{RED} [!!] Delete Data: {name}")
conn = sqlite3.connect(DATABASE_FILE)
c = conn.cursor()
try:
c.execute("DELETE FROM data WHERE NAME=?", (name,))
conn.commit()
except sqlite3.Error as e:
print(
f"{RED} [!] Szene Releaser {___VERSION___} Error in Delete SQLi: {e}")
finally:
conn.close()
def dupe_check_srrdb(release):
readjson = requests.get(f"https://api.srrdb.com/v1/search/{release}").text
data = json.loads(readjson)
if data or json.JSONDecodeError:
if 'results' in data and len(data['results']) > 0:
num_results = len(data['results'])
print(f"{BLUE} [+] Ich habe {num_results} Ergebnisse gefunden.")
print(
f"{BLUE} [+] Möchtest du alle durchgehen, Abbrechen oder Ignorieren?")
print(
f"{BLUE} [+] Y - Alle durchgehen | I - Ignorieren | C - Abbrechen")
user_input = ask_yes_no_dupe("Deine Wahl: ")
if user_input == True:
if len(data['results']) == 1:
rls_name = data['results'][0]['release']
user_input = ask_yes_no_dupe(f"Ist {rls_name} das dupe?: ")
if user_input == True:
sys.exit(1)
elif user_input == False:
return
elif user_input == "cancle":
sys.exit(1)
elif user_input == "ignore":
return
else:
for index, result in enumerate(data['results']):
print("Multi Result ist: " + str(result))
rls_name = result['release']
user_input = ask_yes_no_dupe(
f"Ist {rls_name} das dupe?: ")
if user_input == True:
break # Beendet die Schleife und das Skript
elif user_input == "cancle":
break # Beendet die Schleife und das Skript
elif user_input == "ignore":
break # Beendet die Schleife und das Skript
elif user_input.lower() == "c":
sys.exit(1) # Beendet die Schleife und das Skript
else:
print(f"{GREEN} [+] Nichts gefunden für {release}")
def calculate_part_size(compl_path):
# GET ALL NECESERY VARs
config = configparser.ConfigParser()
config.read(config_file)
RAR_PAKET_SMALL_SIZE = config.get('RAR', 'RAR_PAKET_SMALL_SIZE')
RAR_PAKET_SMALL_COUNT = config.get('RAR', 'RAR_PAKET_SMALL_COUNT')
RAR_PAKET_MID_SIZE = config.get('RAR', 'RAR_PAKET_MID_SIZE')
RAR_PAKET_MID_COUNT = config.get('RAR', 'RAR_PAKET_MID_COUNT')
RAR_PAKET_MAX_COUNT = config.get('RAR', 'RAR_PAKET_MAX_COUNT')
stats = os.stat(compl_path)
f_size = ((stats.st_size / 1024)/1024)
file_size = round(f_size, 0)
if file_size <= RAR_PAKET_SMALL_SIZE:
package_size = RAR_PAKET_SMALL_COUNT
elif file_size <= RAR_PAKET_MID_SIZE:
package_size = RAR_PAKET_MID_COUNT
else:
package_size = RAR_PAKET_MAX_COUNT
part_size = (file_size / package_size) * 1024 * 1024
return round(part_size)
def rar_pack_size(compl_path):
stats = os.stat(compl_path)
f_size = ((stats.st_size / 1024)/1024)
f_size = round(f_size, 0)
# FiLE SiZE iN MB
if f_size <= 1450.0:
print(
f"{PURPLE} [~] File ist kleiner als/gleich 1450MB wähle 50MB Packs")
return "50000000"
elif f_size > 1450.0 and f_size < 14000.0:
print(
f"{PURPLE} [~] File ist grösser als 1450MB aber kleiner als 14GB wähle 150MB Packs")
return "150000000"
elif f_size > 14000.0 and f_size < 30000.0:
print(
f"{PURPLE} [~] File ist grösser als 15GB aber kleiner als 30GB 300MB Packs")
return "300000000"
else:
print(f"{PURPLE} [~] File ist grösser als 30GB 500MB Packs")
return "500000000"
def write_to_file(file, text, modus='a'):
if not os.path.exists(file):
try:
d = open(file, modus)
d.write(text)
d.close
except:
print(
f"{RED} [!] Szene Releaser {___VERSION___} Error: {file} to Write not found or access denied!")
else:
d = open(file, modus)
d.write(text)
d.close
def CRC32_from_file(filename):
with open(filename, 'rb') as file:
buf = file.read()
buf = (binascii.crc32(buf) & 0xFFFFFFFF)
return "%08X" % buf
def upload(ftp, local_path):
"""
Uploads a file or directory to the remote FTP server.
"""
# GET ALL NECESERY VARs
config = configparser.ConfigParser()
config.read(config_file)
FTP_PREDIR = config.get('FTP', 'FTP_PREDIR')
if not os.path.exists(local_path):
raise ValueError(f'Local path "{local_path}" does not exist')
rel_dir = os.path.basename(local_path)
if rel_dir in ('Sample', 'Proof', 'Subs'):
return
remote_dir = os.path.join(FTP_PREDIR, rel_dir)
try:
ftp.mkd(remote_dir)
except Exception as e:
if not e.args[0].startswith('550'):
raise
ftp.cwd(remote_dir)
upload_directory(ftp, local_path, remote_dir)
ftp.cwd(FTP_PREDIR)
def upload_directory(ftp, local_path):
# GET ALL NECESERY VARs
config = configparser.ConfigParser()
config.read(config_file)
FTP_PREDIR = config.get('FTP', 'FTP_PREDIR')
base_dir = os.path.basename(os.path.normpath(local_path))
if base_dir not in ["Sample", "Proof", "Subs"]:
try:
ftp.mkd(FTP_PREDIR + base_dir)
except Exception as e:
if e.args[0].startswith('550'):
pass
rel_dir = FTP_PREDIR + base_dir
if "Sample" not in local_path:
ftp.cwd(rel_dir)
# UPLOAD SFV FiLES FiRST
sorted_dir = sorted(os.listdir(local_path))
for i in range(len(sorted_dir)):
if ".sfv" in sorted_dir[i]:
sorted_dir.insert(0, sorted_dir.pop(i))
for name in sorted_dir:
localpath = os.path.join(local_path, name)
if os.path.isfile(localpath):
filelist = []
ftp.retrlines('NLST', filelist.append)
if not name in filelist:
ftp.storbinary('STOR ' + name, open(localpath, 'rb'))
elif os.path.isdir(localpath):
try:
ftp.mkd(name)
except Exception as e:
if e.args[0].startswith('550'):
pass
ftp.cwd(name)
upload_directory(ftp, localpath)
ftp.cwd(rel_dir)
def packing(ext, destination, filename, movie_complete_path):
if DEBUG == 1:
print(f"{YELLOW} [*] Packing ")
print(f"{YELLOW} [*] ext {ext}")
print(f"{YELLOW} [*] destination {destination}")
print(f"{YELLOW} [*] filename {filename}")
print(f"{YELLOW} [*] source {movie_complete_path}")
fname = os.path.basename(os.path.dirname(movie_complete_path))
# GETTiNG RAR SiZE
if movie_complete_path:
PACK_SIZE = rar_pack_size(movie_complete_path)
elif fname == "Subs" or fname == "Proof":
PACK_SIZE = "15728640"
if linux == 1:
syntax = (
f"rar a -m0 -ma4 -s -v{PACK_SIZE}b -vn -ep1 {ext} "
f'"{os.path.join(destination, filename.lower())}.rar" '
f'"{movie_complete_path}" >/dev/null 2>&1'
)
else:
syntax = (
f'addons{separator}rar.exe a -m0 -s -v{PACK_SIZE}b -vn -ep1 {ext} '
f'"{os.path.join(destination, filename.lower())}.rar" '
f'"{movie_complete_path}" >nul'
)
if DEBUG == 1:
print(f"{YELLOW} [*] RAR Syntax: {syntax}")
ret = os.system(syntax)
if ret != 0:
raise Exception("Packing failed")
print(f"{RED} [*] Packing failed!")
def load_random_sentence(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
sentence = random.choice(lines).strip()
return sentence
def generate_random_string(length=5):
# Zeichen, die für den zufälligen String verwendet werden sollen (Buchstaben und Zahlen)
characters = string.ascii_letters + string.digits
# Generiere den zufälligen String
random_string = ''.join(random.choice(characters) for _ in range(length))
return random_string
def filter_name(name):
name = re.sub('[._\\-]', ' ', name)
regex = r'^.*?(?=(19\d{2}|20\d{2}|german|S\d+E\d+|$))'
match = re.search(regex, name)
if match:
found = match.group()
# Entferne überflüssige Zeichen und Leerzeichen
found = found.rstrip('.mkv').rstrip('.')
# Finde das Jahr
year_match = re.search(r'(19\d{2}|20\d{2})', name)
if year_match:
year = year_match.group()
found = found.replace(year, '') # Entferne das Jahr aus dem Namen
found = found.strip() + "&y=" + year # Füge das Jahr ans Ende des Namens an
return found
else:
return ''
def extract_info(input_string, dupe=False):
# GET ALL NECESERY VARs
config = configparser.ConfigParser()
config.read(config_file)
RAR_USE = config.getint('RAR', 'RAR_USE')
RAR_PACK_MOVIE = config.get('RAR', 'RAR_PACK_MOVIE')
RAR_PACK_SERIES = config.get('RAR', 'RAR_PACK_SERIES')
if RAR_USE == 1:
input_string = input_string.replace(".", " ")
# SEARCH PATTERN FOR DiFFERENT DELiMiTERS
# year_pattern = r"\d{4}"
year_pattern = r".19\d{2}|20\d{2}."
season_episode_pattern = r".S\d{2}E\d{2,3}."
episode_pattern = r".E\d{2,3}."
lang_pattern = r".(GERMAN|FRENCH|DUTCH|MULTI)."
audio_pattern = r".(DD5\.1|DL|ML|AC3|MIC|LINEDUB|DTS|DUBBED|AC3D)."
codec_pattern = r".(H264|H265|X264|X265)."
hdr_pattern = r".SDR."
hdr1_pattern = r".HDR."
hdr2_pattern = r".DV."
screen_pattern = r".(WS|FS)."
# SEARCH FOR DELiMiTERS
year_match = re.search(year_pattern, input_string, re.IGNORECASE)
season_episode_match = re.search(
season_episode_pattern, input_string, re.IGNORECASE)
episode_match = re.search(episode_pattern, input_string, re.IGNORECASE)
lang_match = re.search(lang_pattern, input_string, re.IGNORECASE)
audio_match = re.search(audio_pattern, input_string, re.IGNORECASE)
codec_match = re.search(codec_pattern, input_string, re.IGNORECASE)
hdr_match = re.search(hdr_pattern, input_string, re.IGNORECASE)
hdr1_match = re.search(hdr1_pattern, input_string, re.IGNORECASE)
hdr2_match = re.search(hdr2_pattern, input_string, re.IGNORECASE)
screen_match = re.search(screen_pattern, input_string, re.IGNORECASE)
# DETERMiTE START AND END POSiTiON OF THE TRACK
start_pos = 0
end_pos = len(input_string)
if year_match:
end_pos = year_match.start()
if season_episode_match:
end_pos = min(end_pos, season_episode_match.start())
if episode_match:
end_pos = min(end_pos, episode_match.start())
if lang_match:
end_pos = min(end_pos, lang_match.start())
if audio_match:
end_pos = min(end_pos, audio_match.start())
if codec_match:
end_pos = min(end_pos, codec_match.start())
if hdr_match:
end_pos = min(end_pos, hdr_match.start())
if hdr1_match:
end_pos = min(end_pos, hdr1_match.start())
if hdr2_match:
end_pos = min(end_pos, hdr2_match.start())
if screen_match:
end_pos = min(end_pos, screen_match.start())
# EXTRACT TiTLE
title = input_string[start_pos:end_pos].strip()
# EXTRACT EPiSODE/SEASON
if episode_match:
episode = episode_match.group()
else:
episode = ""
if season_episode_match:
episode_season = season_episode_match.group()
# iF SEASON iS SET, SET SiNGLE EPiSODE TO ""
episode = ""
else:
episode_season = ""
# EXTRACT LANGUAGE
if lang_match:
language = lang_match.group(1)
else:
language = ""
# EXTRACT AUDiO FORMAT
if audio_match:
audio = audio_match.group(1)
else:
audio = ""
# EXTRACT RESOLUTiON
resolution_pattern = r"\d{3,4}p"
resolution_match = re.search(
resolution_pattern, input_string, re.IGNORECASE)
if resolution_match:
resolution = resolution_match.group()
else:
resolution = ""
# EXTRACT CODEC
if codec_match:
codec = codec_match.group(1)
else:
codec = ""
# EXTRACT YEAR
if year_match:
year = year_match.group()
else:
year = ""
# EXTRACT 4K TAGS
if hdr_match:
hdr = hdr_match.group()
else:
hdr = ""
if hdr1_match:
hdr1 = hdr1_match.group()
else:
hdr1 = ""
if hdr2_match:
hdr2 = hdr2_match.group()
else:
hdr2 = ""
# EXTRACT GROUP
group_pattern = r"-(\w+)$"
group_match = re.search(group_pattern, input_string, re.IGNORECASE)
if group_match:
group = group_match.group(1)
else:
group = ""
# EXTRACT WS/FS
if screen_match:
screen = screen_match.group(1)
else:
screen = ""
# CREATE RESULT TUPLE
# 0 1 2 3 4 5 6 7 8 9 10 11 12
result = (title, episode, episode_season, year, language,
audio, resolution, hdr, hdr1, hdr2, screen, codec, group)
if (episode or episode_season):
serie = 1
else:
serie = 0
patterns = [(" ", "."), ("..", "."), ("..", ".")]
# iF WE CHECK of DUPE
if dupe == True:
if serie == 1:
dupe_str = "{}{}{}{} {}".format(
result[0], result[1], result[2], result[4], result[6])
else:
dupe_str = "{}{}{}".format(result[0], result[4], result[6])
for pattern in patterns:
dupe_str = dupe_str.replace(pattern[0], pattern[1])
print(f"{CYAN} [!] Search in PRE-DB: " + str(dupe_str))
return dupe_str
# iF iT iS a SERiES USE THE SERiES TEMPLATE
if serie == 1:
series_str = RAR_PACK_SERIES.format(series_group=result[12], series_title=result[0], series_episode=result[1], series_episode_season=result[2],
series_resolution=result[6], series_hdr=result[7], series_hdr1=result[8], series_hdr2=result[9], series_screen=result[10])
for pattern in patterns:
series_str = series_str.replace(pattern[0], pattern[1])
if series_str.endswith('.'):
series_str = series_str.rstrip('.')
return series_str
# OTHERWiSE -> MOViE
else:
movie_str = RAR_PACK_MOVIE.format(movie_group=result[12], movie_title=result[0], movie_year=result[1],
movie_resolution=result[6], movie_hdr=result[7], movie_hdr1=result[8], movie_hdr2=result[9], movie_screen=result[10])
for pattern in patterns:
movie_str = movie_str.replace(pattern[0], pattern[1])
if movie_str.endswith('.'):
movie_str = movie_str.rstrip('.')
return movie_str
else:
return input_string
def get_hdr_info(movie_complete_path):
try:
media_info = MediaInfo.parse(movie_complete_path)
except Exception as e:
# Fehler beim Einlesen der Datei behandeln
print(f"{RED} [!!] Fehler beim Einlesen der Mediainformationen: {e}")
return None
hdr_text = ""
if DEBUG == 1:
video_track = next((track for track in media_info.tracks if track.track_type == "Video"), None)
# Zeige den gesamten Inhalt des Video-Tracks an
video_track_info = {k: v for k, v in vars(video_track).items()}
print(json.dumps(video_track_info, indent=4))
print(f"{YELLOW} [*] Video-Track Details: {video_track}")
for track in media_info.tracks:
if track.track_type == "Video":
try:
# HDR format auslesen
if hasattr(track, "hdr_format") and track.hdr_format:
hdr_text += " ".join(track.hdr_format)
except:
# Feld nicht gefunden, passen
pass
# die leerschritte entfernen und kommata adden
hdr_text = hdr_text.replace(" ", "")
hdr_text = f"{hdr_text},"
# jetzt den rest durchlaufen
try:
if hasattr(track, "other_hdr_format") and track.other_hdr_format:
hdr_text += " ".join(track.other_hdr_format)
if hasattr(track, "hdr_format_commercial") and track.hdr_format_commercial:
hdr_text += " ".join(track.hdr_format_commercial)
if hasattr(track, "hdr_format_compatibility") and track.hdr_format_compatibility:
hdr_text += " ".join(track.hdr_format_compatibility)
except:
# Felder nicht gefunden, passen
pass
if DEBUG == 1:
print(f"{YELLOW} [*] 1.hdr_matches = {hdr_text}")
# die leerschritte entfernen und kommata adden
hdr_text = hdr_text.replace(" ", "")
hdr_text = f"{hdr_text},"
# Extrahiere relevante HDR-Typen
hdr_matches = set()
try:
if re.search(r"\bDolbyVision\b", hdr_text, re.IGNORECASE):
hdr_matches.add("DoVi")
if re.search(r"\bHDR10\+\b", hdr_text, re.IGNORECASE):
hdr_matches.add("HDR10+")
if re.search(r"\bHDR10\b", hdr_text, re.IGNORECASE):
hdr_matches.add("HDR10")
except Exception as e:
print(f"{RED} [!!] Fehler beim Verarbeiten von HDR-Informationen: {e}")
if DEBUG == 1:
print(f"{YELLOW} [*] 2.hdr_matches = {hdr_matches}")
# Rückgabe des Ergebnisses
if not hdr_matches:
return None
else:
return "/".join(sorted(hdr_matches))
# Falls keine Video-Tracks gefunden wurden
return None
def find_imdb_link(imdb_search):
# GET ALL NECESERY VARs
config = configparser.ConfigParser()
config.read(config_file)
IMDB_API_KEY = config.get('IMDB', 'IMDB_API_KEY')
try:
url = f"https://imdb-api.com/de/API/SearchMovie/{IMDB_API_KEY}/{imdb_search}"
response = requests.get(url)
# Wirft eine Ausnahme, wenn der Statuscode nicht erfolgreich ist
response.raise_for_status()
data = response.json()
if data['results']:
# CHECK iF DESiRED RESULT IS FOUND iN SEARCH RESULTS
for result in data['results']:
if result['title'] == imdb_search:
imdb_id = result['id']
if DEBUG == 1:
print(
f"{YELLOW} [*] ID des Films : {imdb_id}")
return f"https://www.imdb.com/title/{imdb_id}/"
# iF DESiRED RESULT iS NOT FOUND -> RETURN FiRST RESULT
imdb_id = data['results'][0]['id']
if DEBUG == 1:
print(f"{YELLOW} [*] ID des Films : {imdb_id}")
insert_data(imdb_search, imdb_id)
return f"https://www.imdb.com/title/{imdb_id}/", imdb_id
else:
return "", ""
except requests.exceptions.HTTPError as err:
# Behandlung von HTTP-Fehlern
print(f"{RED} [!] IMDB-API sends a Error - {err}")
return "", ""
except requests.exceptions.RequestException as err:
# Behandlung von anderen Ausnahmen (z.B. Verbindungsfehler)
print(f"{RED} [!] IMDB-API sends a Error - {err}")
return "", ""
def get_imdb_link(movie_complete_path):
movie = os.path.split(movie_complete_path)[1].lower()
# FiND MOViE NAME
filename = filter_name(movie)
# iF EMPTY STRiNG SET TEMP NAME
if filename == '':
filename = movie
# GET iMDB iD
# CHECK WHETHER MOViE OR SERiES
tmp = filename
match = re.search(r"(.*?)\b(?:S\d{2}E\d{2}|E\d{2}|german)\b", tmp, flags=re.IGNORECASE)
imdb_search = match.group(1) if match else ""
imdb_search = re.sub(r"[.,_]", " ", imdb_search)
# check if movie is in DB
result = select_data(f"{imdb_search}")
if result != "":
return f"https://www.imdb.com/title/{result}", {imdb_search}
else:
IMDB_LINK, IMDB_ID = find_imdb_link(imdb_search)
return IMDB_LINK, imdb_search
def find_omdb_link(imdb_search):
# GET ALL NECESERY VARs
config = configparser.ConfigParser()
config.read(config_file)
OMDB_API_KEY = config.get('OMDB', 'OMDB_API_KEYS')
# check if key is valid or change it
"""Search for a movie using OMDB API"""
try:
url = f"http://www.omdbapi.com/?apikey={OMDB_API_KEY}&t={imdb_search}"
#print(f"DEBUG: {url}")
response = requests.get(url)
data = response.json()
if response.status_code == 200 and data['Response'] == 'True':
imdb_id = data['imdbID']
if DEBUG == 1:
print(
f"{YELLOW} [*] ID des Films : {imdb_id}")
# insert result in db
insert_data(imdb_search, imdb_id)
return f"https://www.imdb.com/title/{imdb_id}"
except requests.exceptions.HTTPError as err:
# Behandlung von HTTP-Fehlern
print(f"{RED} [!] IMDB-API sends a Error - {err}")
return "", ""
except requests.exceptions.RequestException as err:
# Behandlung von anderen Ausnahmen (z.B. Verbindungsfehler)
print(f"{RED} [!] IMDB-API sends a Error - {err}")
return "", ""
def get_omdb_link(movie_complete_path):
movie = os.path.split(movie_complete_path)[1].lower()
# FiND MOViE NAME
imdb_search = filter_name(movie)
# iF EMPTY STRiNG SET TEMP NAME
if imdb_search == '':
imdb_search = movie
# check if movie is in DB
result = select_data(f"{imdb_search}")
if result != "":
return f"https://www.imdb.com/title/{result}", {imdb_search}
else:
IMDB_LINK = find_omdb_link(imdb_search)
return IMDB_LINK
def create_dirs(source_dir, release_dir_dest):
dirs = ["Sample"]
PROOF_DIR, SUBS_DIR = 0, 0
if linux == 1:
separator = "/"
else:
separator = "\\"
if os.path.isdir(f"{source_dir}{separator}Proof"):
dirs.append("Proof")
PROOF_DIR = 1
if os.path.isdir(f"{source_dir}{separator}Subs"):
dirs.append("Subs")
SUBS_DIR = 1
for d in dirs:
dir_path = f"{release_dir_dest}{separator}{d}"
try:
os.makedirs(dir_path, exist_ok=True)
except:
# DiR EXiSTS
pass
return PROOF_DIR, SUBS_DIR
def cut_movie(movie_complete_path, release_dir_dest, filename, CUT_FROM, CUT_TO):
movie = filename
sample_file = f"{movie.lower()}_sample.mkv"
movie_sample = os.path.join(release_dir_dest, "Sample", sample_file)
if linux == 1:
sample_cut = f'mkvmerge "{movie_complete_path}" --compression -1:none --split parts:{CUT_FROM}-{CUT_TO} -o "{movie_sample}" >/dev/null 2>&1'
else:
sample_cut = f'addons{separator}mkvmerge.exe "{movie_complete_path}" --compression -1:none --split parts:{CUT_FROM}-{CUT_TO} -o "{movie_sample}" > nul'
try:
if DEBUG == 1:
print(f"{YELLOW} [*] Sample Cut: {sample_cut}")
os.system(sample_cut)
# CHECK iF FiLE WAS CREATED
sample_file = os.path.join(movie_sample)
if os.path.isfile(sample_file):
print(f"{GREEN} [+] Cutting done {movie}")
return True
else:
print(f"{RED} [-] Cutting failed for {movie}")
return False
except Exception as e:
print(RED + " [!] Szene Releaser " +
___VERSION___, " Sample Error: %s" % e)
return False
def create_nfo(movie_complete_path, destination, movie, filename, file_source, IMDB_LINK):
# CREATE NFO
# GET ALL NECESSARY VARs
config = configparser.ConfigParser()
config.read(config_file)
NFO_GROUP_NAME = config.get('NFO', 'NFO_GROUP_NAME')
NFO_GROUP_NAME_SHORT = config.get('NFO', 'NFO_GROUP_NAME_SHORT')
MORE_NOTES = config.get('NFO', 'NOTES', raw=True)
CODEC_REPLACEMENTS = dict(config.items('REPLACEMENTS'))
# Get codec
start = os.path.splitext(movie)[0].rfind(".") + 1
end = os.path.splitext(movie)[0].rfind("-", start)
codec = os.path.splitext(movie)[0][start:end]
codec_info = ""
# Get HDR info
hdr_info = get_hdr_info(movie_complete_path)
if hdr_info != None:
codec_info = f" | {hdr_info}"
file = os.path.splitext(movie)[0]
movie_nfo = f"{destination}{separator}{file}{separator}"
movie_nfo += f"{filename}.nfo".lower()
print(f"{YELLOW} [*] NFO started for {filename}")
# replace \\n with \r\n on windows
if linux == 1:
MORE_NOTES = MORE_NOTES.replace("\\n", "\n")
MORE_NOTES = MORE_NOTES.replace("\\t", "\t")
else:
MORE_NOTES = MORE_NOTES.replace("\\n", "\r\n")
MORE_NOTES = MORE_NOTES.replace("\\t", "\t")
if DEBUG == 1:
print(f"{YELLOW} [*] movie_nfo = {movie_nfo}")
now = datetime.datetime.now()
if file_source.lower() == "web":
TOUCH = f" untouched\n {MORE_NOTES}"
else:
TOUCH = f" {MORE_NOTES}"
# CHANGE iT HERE
GROUP_NAME = f"{NFO_GROUP_NAME}\n\n"
# PATH TO THE NFO TEMPLATE
NFO_TEMPLATE = f"{os.path.abspath('.')}{separator}config{separator}{NFO_GROUP_NAME_SHORT}_nfo.txt"
# APPEND ON TOP
NFO_HEADER = f"RELEASE : {os.path.basename(destination + separator + os.path.splitext(movie)[0])}\nDATE : {now.strftime('%d-%m-%Y')}\nCODEC : {codec}{codec_info}\nSOURCE : {file_source}"
# APPEND ON FOOTER
NFO_FOOTER = f"IMDB : {IMDB_LINK}\n\nNOTES :{TOUCH}"
# CHANGE END!
# WROTE THE HEADER OF NFO
write_to_file(movie_nfo, f"{GROUP_NAME}{NFO_HEADER}")
# THE BODY
if linux == 1:
syntax = f"--Inform=\"file://{NFO_TEMPLATE}\" \"{movie_complete_path}\" >> \"{movie_nfo}\""
if DEBUG == 1:
print(
f"{YELLOW} [*] movie_complete_path : {movie_complete_path}")
print(f"{YELLOW} [*] Mediainfo : {syntax}")
os.system(f"mediainfo {syntax}")
else:
syntax = f"--Inform=\"file://{NFO_TEMPLATE}\" \"{movie_complete_path}\" >> \"{movie_nfo}\""
if DEBUG == 1:
print(
f"{YELLOW} [*] movie_complete_path : {movie_complete_path}")
print(f"{YELLOW} [*] Mediainfo : {syntax}")
os.system(f"addons{separator}mediainfo.exe {syntax}")
# AT THE END
write_to_file(movie_nfo, NFO_FOOTER, "a")
# CHECK NFO CODEC
movie_nfo_tmp = f"{movie_nfo}.tmp"
shutil.copy(movie_nfo,movie_nfo_tmp)
with open(movie_nfo_tmp, 'r') as file:
original_content = file.read()
try:
for key, value in CODEC_REPLACEMENTS.items():
original_content = original_content.replace(key.upper(), value.upper())
except:
pass
# Schreibe die bearbeitete Ausgabe in eine neue Datei
with open(movie_nfo, 'w') as file:
file.writelines(original_content)
os.remove(movie_nfo_tmp)
print(f"{GREEN} [+] NFO Created for {movie[:-4]}")
def create_nfo_with_template(media_file_content, nfo_template, destination, filename, movie):
global IMDB_LINK
general_duration, general_file_size, video_res, video_bit_rate, audio_string, subs_string = extract_info_of_file(media_file_content)
file = os.path.splitext(movie)[0]
movie_nfo = f"{destination}{separator}{file}{separator}"
movie_nfo += f"{filename}.nfo".lower()
if DEBUG == 1:
print(f"{YELLOW} NFO Template: {nfo_template}")
print(f"{YELLOW} NFO: {movie_nfo}")
# Tonspuren
audios = ""
for index, audio in enumerate(audio_string):
if index > 0:
indentation = calculate_indentation("{audio_string}", nfo_template)
audio = indentation + audio
audios += audio + "\n"
# Subs
subs = ""