This repository has been archived by the owner on Aug 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ABtorrents.py
1671 lines (1421 loc) · 59.7 KB
/
ABtorrents.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 time
from torf import Torrent
import PySimpleGUI as sg
import mutagen
from mutagen import File
from mutagen.id3 import ID3
import fnmatch
import shutil
import os
import glob
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pyautogui
from mutagen.mp4 import MP4
import re
import configparser
from pathlib import Path
import codecs
import sys
import logging
script_version = 'Beta v.0.3 - ABtorrents uploader Helper'
script_version_short = 'Beta v.0.3'
# set up logging to file -------------------------------------------------------------------
logging.basicConfig(level=logging.INFO,
format='%(levelname)-8s%(asctime)s %(name)-12s %(message)s',
datefmt='%d-%m-%y (%H:%M)',
filename='log.log',
filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(levelname)-8s%(asctime)s %(name)-8s %(message)s', "%H:%M:%S")
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
logger_config = logging.getLogger('config')
logger_path = logging.getLogger('paths')
logger_torrent = logging.getLogger('torrent')
logger_nfo = logging.getLogger('nfo')
logger_audio = logging.getLogger('audiofile')
logger_meta = logging.getLogger('Mp3 meta')
logger_meta2 = logging.getLogger('Mb4 meta')
logger_cover = logging.getLogger('cover')
logger_internet = logging.getLogger('site')
# END set up logging to file ----------------------------------------------------------------
# Set variables
nfo_author = ''
nfo_narr = ''
nfo_album = ''
nfo_series = ''
num_serie = ''
nfo_audio = ''
nfo_bitrate = ''
nfo_sub = ''
nfo_genre = ''
nfo_year = ''
nfo_asin = ''
nfo_publisher = ''
nfo_copy = ''
nfo_link = ''
nfo_desc = ''
nfo_encoder = ''
nfo_full = ''
nfo_comm = ''
nfo_duration = ''
nfo_unabridged = ''
nfo_release = ''
nfo_size = ''
nfo_url = ''
nfo_notes = ''
# If error pauses script---------------------------------------------------
def show_exception_and_exit(exc_type, exc_value, tb):
import traceback
traceback.print_exception(exc_type, exc_value, tb)
input("An error as appeared, press any key and enter to exit.")
sys.exit(-1)
sys.excepthook = show_exception_and_exit
# END If error pauses script-----------------------------------------------
# Log Version--------------------------------------------------------------
logging.info('Script Version: %s', script_version)
# END Log Version----------------------------------------------------------
# Config-------------------------------------------------------------------
# update the config file
config = configparser.ConfigParser()
# Config ini File
if not os.path.exists('config.ini'): # if it is not present
config.add_section('FOLDERS')
config.add_section('LOGIN')
config['FOLDERS']['torrent_folder'] = "0"
config['FOLDERS']['folder_path'] = "0"
config['FOLDERS']['torrent_file'] = "0"
config['LOGIN']['firefox_profile'] = "0"
config['LOGIN']['username'] = "0"
config['LOGIN']['password'] = "0"
logger_config.info('Ini Config file was created: config.ini')
config.write(open('config.ini', 'w'))
torrent_file_path = config['FOLDERS']['torrent_folder'] # to make folders
torrent_file = config['FOLDERS']['torrent_file'] # make files
login_session = config['LOGIN']['firefox_profile'] # profile firefox link
login_username = config['LOGIN']['username']
login_password = config['LOGIN']['password']
else:
# if config file present:
logger_config.info('The config.ini file is present.')
config.read(r'config.ini')
torrent_file_path = config['FOLDERS']['torrent_folder']
torrent_file = config['FOLDERS']['torrent_file']
login_session = config['LOGIN']['firefox_profile']
login_username = config['LOGIN']['username']
login_password = config['LOGIN']['password']
# END Config-----------------------------------------------------------------
# Paths to file/folder-------------------------------------------------------
folder_path = None
file_path = None
logger_path.info('Please enter your folder or file...')
# Choose torrent folder
sg.theme('Dark Blue 3') # please make your windows colorful
layout = [[sg.Text('Here you can choose folder or file to make a torrent.')],
[sg.Text('Later you can choose a path for the .torrent if not in config.')],
[sg.Text('Folder:', size=(10, 1)), sg.InputText(), sg.FolderBrowse()],
[sg.Text('File:', size=(10, 1)), sg.InputText(), sg.FileBrowse()],
[sg.Submit(), sg.Cancel()]]
window = sg.Window(script_version_short, layout, icon=r"favicon.ico", finalize=True)
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
logger_path.warning('You have canceled or closed the window the script will now close...')
window.read(timeout=3000)
raise SystemExit(0)
window.close()
if values[0] == '' and values[1] == '':
sg.popup_error('You did not enter anything, so exit is in order!')
logger_path.warning('All the paths were empty, the script will now close...')
raise SystemExit(0)
else:
# values[0] is the variable for the folder path
folder_path = values[0] # get the data from the values dictionary
if folder_path == '':
pass
else:
logger_path.info('Folder path was set: %s', folder_path)
# values[1] is the variable for the file path
file_path = values[1] # get the data from the values dictionary
if file_path == '':
pass
else:
logger_path.info('File path is: %s', file_path)
# if the file path as nothing create the the torrent from folder torrent
if file_path == '':
logger_torrent.info('Creating Torrent from folder...please wait')
# Make torrent from folder
t = Torrent(path=folder_path,
trackers=['https://abtorrents.me:2910/announce'],
comment='In using this torrent you are bound by the ABTorrents Confidentiality Agreement '
'By Law')
# Exclude nfo files
t.exclude_globs.append('*.nfo')
t.private = True
# animation = ["■□□□□□□□□□", "■■□□□□□□□□", "■■■□□□□□□□", "■■■■□□□□□□",
# "■■■■■□□□□□", "■■■■■■□□□□", "■■■■■■■□□□", "■■■■■■■■□□",
# "■■■■■■■■■□", "■■■■■■■■■■"]
animation = ["10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"]
for i in range(len(animation)):
time.sleep(0.2)
# sys.stdout.write("\r" + animation[i % len(animation)] + "\n")
# sys.stdout.flush()
stt = animation[i % len(animation)]
logger_torrent.info('Creating torrent: %s', stt)
t.generate()
# define the name of the directory
# get the folder name to make the torrent name
torrent_folder = Path(folder_path).stem # get only the file with extension
# if the config file as no folder path to save the .torrent create one
if torrent_file_path == '0':
# Choose .torrent folder
sg.theme('Dark Blue 3') # please make your windows colorful
layout = [[sg.Text('Here you can choose folder to save the .torrent file.')],
[sg.Text('Folder', size=(10, 1)), sg.InputText(), sg.FolderBrowse()],
[sg.Submit(), sg.Cancel()]]
window = sg.Window(script_version_short, layout, icon=r"favicon.ico")
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
sys.exit()
window.close()
# if the box text as nothing quit
if values[0] == '':
sg.popup_error('You did not enter anything, so exit is in order.')
sys.exit()
else:
path_to_torrent = values[0]
# update the config file
config = configparser.ConfigParser()
my_config = Path('config.ini') # Path of your .ini file
config.read(my_config)
config.set('FOLDERS', 'torrent_folder', path_to_torrent) # Updating existing entry
# config.set('FOLDERS', 'day', 'sunday') # Writing new entry
config.write(my_config.open("w"))
else:
path_to_torrent = torrent_file_path
file = path_to_torrent + '/' + torrent_folder + '.torrent'
if os.path.exists(file):
os.remove(file)
logger_torrent.info('Deleting old .torrent file present.')
else:
pass
t.write(path_to_torrent + '/' + torrent_folder + '.torrent')
logger_torrent.info('The .torrent file is created.')
newadded = torrent_folder
else:
logger_torrent.info('Creating Torrent...please wait.')
# make .torrent single file
t = Torrent(path=file_path,
trackers=['https://abtorrents.me:2910/announce'],
comment='In using this torrent you are bound by the ABTorrents Confidentiality Agreement '
'By Law')
t.private = True
# animation = ["■□□□□□□□□□", "■■□□□□□□□□", "■■■□□□□□□□", "■■■■□□□□□□",
# "■■■■■□□□□□", "■■■■■■□□□□", "■■■■■■■□□□", "■■■■■■■■□□",
# "■■■■■■■■■□", "■■■■■■■■■■"]
animation = ["10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"]
for i in range(len(animation)):
time.sleep(0.2)
sys.stdout.write("\r" + animation[i % len(animation)] + "\n")
sys.stdout.flush()
t.generate()
# get the file name to make the torrent name
if torrent_file == '0':
# Choose .torrent folder
sg.theme('Dark Blue 3') # please make your windows colorful
layout = [[sg.Text('Here you can choose folder to save the .torrent file.')],
[sg.Text('Folder:', size=(10, 1)), sg.InputText(), sg.FolderBrowse()],
[sg.Submit(), sg.Cancel()]]
window = sg.Window(script_version_short, layout, icon=r"favicon.ico")
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
logger_torrent.warning('The script will now close...')
time.sleep(3)
sys.exit()
window.close()
if values[0] == '':
sg.popup_error('You did not enter anything, so exit is in order.')
sys.exit()
else:
path_to_torrent_file = values[0]
logger_torrent.info('Path to torrent file: %s', path_to_torrent_file)
# update the config file
config = configparser.ConfigParser()
my_config = Path('config.ini') # Path of your .ini file
config.read(my_config)
config.set('FOLDERS', 'torrent_file', path_to_torrent_file) # Updating existing entry
# config.set('FOLDERS', 'day', 'sunday') # Writing new entry
config.write(my_config.open("w"))
# torrent_file = Path(path_to_torrent_file).stem # only the file name
else:
path_to_torrent_file = torrent_file
logger_torrent.info('File path: %s', path_to_torrent_file)
file_path2 = Path(file_path).stem # only the file name
t.write(path_to_torrent_file + '/' + file_path2 + '.torrent')
logger_torrent.info('The file was created.')
newadded = file_path2
# END Paths to file/folder-----------------------------------------------------
# para terminar o script
# raise SystemExit(0)
# Find NFO Nfo------------------------------------------------------------------
logger_nfo.info('Starting looking for NFO file(s)....')
nfofile = None
# nfo files Path
def find_files(directory, pattern):
for root, dirs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
# nfo_filename = os.path.join(basename)
nfofile = os.path.join(root, basename) # Para full path
yield nfofile
if file_path == '':
for nfofile in find_files(folder_path, '*.nfo'):
logger_nfo.info('Found NFO metadata source: %s', nfofile)
for nfofile in find_files(folder_path, '*.txt'):
logger_nfo.info('Found TXT metadata source: %s', nfofile)
if nfofile is None:
logger_nfo.warning('NFO file is not present...')
nfofile = "No NFO present"
else:
# Book Title
_title = ["Title:", "Title.."]
logger_nfo.info('Searching Title book...')
with open(nfofile, "r+") as file1:
fileline1 = file1.readlines()
for x in _title: # <--- Loop through the list to check
for line in fileline1: # <--- Loop through each line
line = line.casefold() # <--- Set line to lowercase
if x.casefold() in line:
logger_nfo.info('Line found with word: %s', x)
nfo_album = line
# remove (Unabridged)
nfo_album = re.sub(r' \(unabridged\)', r'', nfo_album)
# remove everything before :
nfo_album = re.sub(r'^[^:]*:', r'', nfo_album).lstrip().title()
# splitting if title as series
nfo_album2 = nfo_album.split(' - ')
try:
nfo_album = nfo_album2[1]
nfo_series = nfo_album2[0]
logger_nfo.info('Found Book Title: %s', nfo_album.rstrip("\n"))
except:
logger_nfo.info('Found Book Title: %s', nfo_album.rstrip("\n"))
if nfo_album == '':
logger_nfo.warning('Book Title not found.')
# Book Author
_author = ["Author:", "Author.."]
logger_nfo.info('Searching Author book...')
with open(nfofile, "r+") as file1:
fileline1 = file1.readlines()
for x in _author: # <--- Loop through the list to check
for line in fileline1: # <--- Loop through each line
line = line.casefold() # <--- Set line to lowercase
if x.casefold() in line:
logger_nfo.info('Line found with word: %s', x)
nfo_author = line
# remove everything before :
nfo_author2 = re.sub(r'^[^:]*:', r'', nfo_author).lstrip().title()
logger_nfo.info('Author Found: %s', nfo_author2.rstrip("\n"))
if nfo_author == '':
logger_nfo.warning('Author not found.')
# Book Narrator
_narrator = ["Read by:", "Narrator:", "Read by.."]
logger_nfo.info('Searching Narrator...')
with open(nfofile, "r+") as file1:
fileline1 = file1.readlines()
for x in _narrator: # <--- Loop through the list to check
for line in fileline1: # <--- Loop through each line
line = line.casefold() # <--- Set line to lowercase
if x.casefold() in line:
logger_nfo.info('Line found with word: %s', x)
nfo_narr = line
# remove everything before :
nfo_narr = re.sub(r'^[^:]*:', r'', nfo_narr).lstrip().title()
logger_nfo.info('Narrator Found: %s', nfo_narr.rstrip("\n"))
# if two narrators
try:
nfo_split_narr = nfo_narr.split(", ")
nfo_split_narr1 = nfo_split_narr[0]
nfo_split_narr2 = nfo_split_narr[1]
nfo_split_narr3 = nfo_split_narr[2]
nfo_split_narr4 = nfo_split_narr[3]
print(nfo_split_narr[0])
except:
pass
if nfo_narr == '':
logger_nfo.warning('Narrator not found.')
# Book Series
_series = ["Series:", "Series Name:"]
logger_nfo.info('Searching Series...')
with open(nfofile, "r+") as file1:
fileline1 = file1.readlines()
for x in _series: # <--- Loop through the list to check
for line in fileline1: # <--- Loop through each line
line = line.casefold() # <--- Set line to lowercase
if x.casefold() in line:
logger_nfo.info('Line found with word: %s', x)
if nfo_series == '':
nfo_series = line
# remove everything before :
nfo_series = re.sub(r'^[^:]*:', r'', nfo_series).lstrip().title()
logger_nfo.info('Series Found: %s', nfo_series.rstrip("\n"))
else:
pass
if nfo_series == '':
logger_nfo.warning('Series not found.')
else:
try:
num_serie2 = nfo_series.split(' Book ')
num_serie = num_serie2[1]
logger_nfo.info('Series number found: %s', num_serie.rstrip("\n"))
except:
logger_nfo.warning('Series number not Found!')
nfo_series = re.sub(r' Book 1', r'', nfo_series)
nfo_series = re.sub(r' Book 2', r'', nfo_series)
nfo_series = re.sub(r' Book 3', r'', nfo_series)
nfo_series = re.sub(r' Book 4', r'', nfo_series)
nfo_series = re.sub(r' Book 5', r'', nfo_series)
nfo_series = re.sub(r' Book 6', r'', nfo_series)
nfo_series = re.sub(r' Book 7', r'', nfo_series)
nfo_series = re.sub(r' Book 8', r'', nfo_series)
logger_nfo.info('Series Found: %s', nfo_series)
if num_serie == '':
# Book series number
_number = ["Position in", "sfdsfdsfsd"]
logger_nfo.info('Searching Series number...')
with open(nfofile, "r+") as file1:
fileline1 = file1.readlines()
for x in _number: # <--- Loop through the list to check
for line in fileline1: # <--- Loop through each line
line = line.casefold() # <--- Set line to lowercase
if x.casefold() in line:
logger_nfo.info('Line found with word: %s', x)
num_serie = line
# remove everything before :
num_serie = re.sub(r'^[^:]*:', r'', num_serie).lstrip().title()
logger_nfo.info('Series number Found: %s', num_serie.rstrip("\n"))
if num_serie == '':
logger_nfo.warning('Series number not found.')
else:
pass
# Book Genre
_genre = ["Genre:", "GENRE.."]
logger_nfo.info('Searching Genre...')
with open(nfofile, "r+") as file1:
fileline1 = file1.readlines()
for x in _genre: # <--- Loop through the list to check
for line in fileline1: # <--- Loop through each line
line = line.casefold() # <--- Set line to lowercase
if x.casefold() in line:
logger_nfo.info('Line found with word: %s', x)
nfo_genre = line
# remove everything before :
nfo_genre = re.sub(r'^[^:]*:', r'', nfo_genre).lstrip().title()
logger_nfo.info('Genre Found: %s', nfo_genre.rstrip("\n"))
if nfo_genre == '':
logger_nfo.warning('Genre not found.')
# Book Copyright
_copy = ["Copyright:", "Copyright.."]
logger_nfo.info('Searching Copyright...')
with open(nfofile, "r+") as file1:
fileline1 = file1.readlines()
for x in _copy: # <--- Loop through the list to check
for line in fileline1: # <--- Loop through each line
line = line.casefold() # <--- Set line to lowercase
if x.casefold() in line:
logger_nfo.info('Line found with word: %s', x)
nfo_copy = line
# remove everything before :
nfo_copy = re.sub(r'^[^:]*:', r'', nfo_copy).lstrip().title()
logger_nfo.info('Copyright Found: %s', nfo_copy.rstrip("\n"))
if nfo_copy == '':
logger_nfo.warning('Copyright not found.')
# Book Duration
_dura = ["Duration:", "Time:", 'TiME..', "Duration.."]
logger_nfo.info('Searching Duration...')
with open(nfofile, "r+") as file1:
fileline1 = file1.readlines()
for x in _dura: # <--- Loop through the list to check
for line in fileline1: # <--- Loop through each line
line = line.casefold() # <--- Set line to lowercase
if x.casefold() in line:
logger_nfo.info('Line found with word: %s', x)
nfo_duration = line
# remove everything before :
nfo_duration = re.sub(r'^[^:]*:', r'', nfo_duration).lstrip().title()
logger_nfo.info('Duration Found: %s', nfo_duration.rstrip("\n"))
if nfo_duration == '':
logger_nfo.warning('Duration not found.')
# Book Publisher
_publisher = ["Publisher:", "PUBLiSHER.."]
logger_nfo.info('Searching Publisher...')
with open(nfofile, "r+") as file1:
fileline1 = file1.readlines()
for x in _publisher: # <--- Loop through the list to check
for line in fileline1: # <--- Loop through each line
line = line.casefold() # <--- Set line to lowercase
if x.casefold() in line:
logger_nfo.info('Line found with word: %s', x)
nfo_publisher = line
# remove everything before :
nfo_publisher = re.sub(r'^[^:]*:', r'', nfo_publisher).lstrip().title()
logger_nfo.info('Publisher Found: %s', nfo_publisher.rstrip("\n"))
if nfo_publisher == '':
logger_nfo.warning('Publisher not found.')
# Book unbridged
_uno = ["Unabridged:", "Unabridged.."]
logger_nfo.info('Searching Unbridged...')
with open(nfofile, "r+") as file1:
fileline1 = file1.readlines()
for x in _uno: # <--- Loop through the list to check
for line in fileline1: # <--- Loop through each line
line = line.casefold() # <--- Set line to lowercase
if x.casefold() in line:
logger_nfo.info('Line found with word: %s', x)
nfo_unabridged = line
# remove everything before :
nfo_unabridged = re.sub(r'^[^:]*:', r'', nfo_unabridged).lstrip().title()
logger_nfo.info('Unbridged Found: %s', nfo_unabridged.rstrip("\n"))
if nfo_unabridged == '':
logger_nfo.warning('Unbridged not found.')
# Book Release
_release = ["Release:", "STOREDATE..", "Release.."]
logger_nfo.info('Searching Release...')
with open(nfofile, "r+") as file1:
fileline1 = file1.readlines()
for x in _release: # <--- Loop through the list to check
for line in fileline1: # <--- Loop through each line
line = line.casefold() # <--- Set line to lowercase
if x.casefold() in line:
logger_nfo.info('Line found with word: %s', x)
nfo_release = line
# remove everything before :
nfo_release = re.sub(r'^[^:]*:', r'', nfo_release).lstrip().title()
if not nfo_release:
pass
else:
logger_nfo.info('Release Found: %s', nfo_release.rstrip("\n"))
if nfo_release == '':
logger_nfo.warning('Release not found.')
# Book size
_size = ["Size:", "SiZE.."]
logger_nfo.info('Searching Size...')
with open(nfofile, "r+") as file1:
fileline1 = file1.readlines()
for x in _size: # <--- Loop through the list to check
for line in fileline1: # <--- Loop through each line
line = line.casefold() # <--- Set line to lowercase
if x.casefold() in line:
logger_nfo.info('Line found with word: %s', x)
nfo_size = line
# remove everything before :
nfo_size = re.sub(r'^[^:]*:', r'', nfo_size).lstrip().title()
logger_nfo.info('Size Found: %s', nfo_size.rstrip("\n"))
if nfo_size == '':
logger_nfo.warning('Size not found.')
# Book url
_url = ["URL:", "URL.."]
logger_nfo.info('Searching Url...')
with open(nfofile, "r+") as file1:
fileline1 = file1.readlines()
for x in _url: # <--- Loop through the list to check
for line in fileline1: # <--- Loop through each line
line = line.casefold() # <--- Set line to lowercase
if x.casefold() in line:
logger_nfo.info('Line found with word: %s', x)
nfo_url = line
# remove everything before :
nfo_url = re.sub(r'^[^:]*:', r'', nfo_url).lstrip().title()
logger_nfo.info('Url Found: %s', nfo_url.rstrip("\n"))
if nfo_url == '':
logger_nfo.warning('Url Not Found.')
# Book notes
_notes = ["Note(s):", "Note(s)..", "Note:"]
logger_nfo.info('Searching Notes...')
with open(nfofile, "r+") as file1:
fileline1 = file1.readlines()
for x in _notes: # <--- Loop through the list to check
for line in fileline1: # <--- Loop through each line
line = line.casefold() # <--- Set line to lowercase
if x.casefold() in line:
logger_nfo.info('Line found with word: %s', x)
nfo_notes = line
# remove everything before :
nfo_notes = re.sub(r'^[^:]*:', r'', nfo_notes).lstrip().title()
logger_nfo.info('Note Found: %s', nfo_notes.rstrip("\n"))
if nfo_notes == '':
logger_nfo.warning('Note Not Found.')
# Description
copy = False
with open(nfofile, "r") as saveoutput:
for line in saveoutput:
if 'Description' in line:
copy = True
# if line.startswith('-'):
# copy = False
if copy:
items = (format(line.strip()) for line in saveoutput)
join = '\n'.join(items)
join = re.sub(r'Description:', r'', join)
join = re.sub(r' ==', r'', join)
nfo_desc = join
# logger_nfo.info('Description: %s', join)
logger_nfo.info('Description Found: %s', nfo_desc.rstrip("\n"))
# else:
# print('No description found.')
else:
logger_nfo.info('Metadata will be made from audio file metadata.')
pass
# END Find NFO------------------------------------------------------------------
# Find audio files--------------------------------------------------------------
logger_audio.info('Starting looking for audio file(s)....')
audio_filename = None
# audio files Path
def find_files(directory, pattern):
for root, dirs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
# nfo_filename = os.path.join(basename)
audio_filename = os.path.join(root, basename) # Para full path
yield audio_filename
if file_path == '':
for audio_filename in find_files(folder_path, '*.mp3'):
logger_audio.info('Found MP3 audio source: %s', audio_filename)
for audio_filename in find_files(folder_path, '*.m4b'):
logger_audio.info('Found M4B audio source: %s', audio_filename)
for audio_filename in find_files(folder_path, '*.mp4'):
logger_audio.info('Found MP4 audio source: %s', audio_filename)
else:
audio_filename = file_path
if not audio_filename:
logger_audio.error('Audio files not present...')
else:
f = mutagen.File(audio_filename)
# samplerate = f.info.sample_rate
# print(samplerate)
# if it is not MP3 move to MP4
try:
audio = ID3(audio_filename) # path: path to file
# Here is the info from de audio file MP3
logger_audio.info('Audio files MP3 found....')
# album/title
try:
nfo_album = audio['TALB'].text[0]
# if it as a : in the album name
logger_meta.info('Album title: %s', nfo_album)
nfo_album = nfo_album.split(':')[0]
if nfo_album == nfo_album:
logger_meta.info('No (:) char found.')
else:
logger_meta.info('Removing Everything after (:) %s', nfo_album)
logger_meta.info('Album title: %s', nfo_album)
# Subtitle
try:
nfo_sub = nfo_album.split(':')[1]
logger_meta.info('Album Subtitle: %s', nfo_sub)
except:
logger_meta.info('No Subtitle found.')
# remove the initial numbers from album name
nfo_album = re.sub('^[\d-]*\s*', '', nfo_album)
logger_meta.info('Final album tag: %s', nfo_album)
except:
logger_meta.warning('Album title not found.')
if nfo_sub == '':
try:
nfo_sub = audio['TIT3'].text[0]
logger_meta.info('Album Subtitle: %s', nfo_sub)
except:
pass
else:
pass
try:
# Artist/author
nfo_author = audio['TPE1'].text[0]
# correct format of author(ex: A. B. Mark)
nfo_author = re.sub(r'(?<=[A-Z])\.?\s?(?![a-z])', r'. ', nfo_author)
logger_meta.info('Author: %s', nfo_author)
except:
logger_meta.warning('This Audiobook as No Author, probably no tags are present.')
# Narrator/composer
try:
nfo_narr = audio['TCOM'].text[0]
# correct format of narrator(ex: A. B. Mark)
nfo_narr = re.sub(r'(?<=[A-Z])\.?\s?(?![a-z])', r'. ', nfo_narr)
logger_meta.info('Narrator: %s', nfo_narr)
try:
nfo_split_narr = nfo_narr.split(", ")
nfo_split_narr1 = nfo_split_narr[0]
nfo_split_narr2 = nfo_split_narr[1]
nfo_split_narr3 = nfo_split_narr[2]
nfo_split_narr4 = nfo_split_narr[3]
print(nfo_split_narr[0])
except:
pass
except:
logger_meta.info('Narrator not found.')
# if author iqual to narrator get data from nfo.
if nfo_author == nfo_narr:
nfo_author = nfo_author2
else:
pass
# Genre
if nfo_genre == 'Audiobook' or nfo_genre == '':
try:
nfo_genre = audio['TCON'].text[0]
logger_meta.info('Genre: %s', nfo_genre)
except:
pass
else:
logger_meta.info('No GENRE found.')
# Year
try:
nfo_year = audio['TDRC'].text[0]
logger_meta.info('Year: %s', nfo_year)
except:
logger_meta.info('No Year Found.')
# Series
try:
nfo_series = audio['TXXX:SERIES'].text[0]
logger_meta.info('Series: %s', nfo_series)
except:
logger_meta.info('No series found.')
# Series number
try:
num_serie = audio['TXXX:series-part'].text[0]
logger_meta.info('Series part: %s', num_serie)
except:
logger_meta.info('No series number found.')
# Asin
try:
nfo_asin = audio['TXXX:Asin'].text[0]
logger_meta.info('Asin: %s', nfo_asin)
except:
logger_meta.info('No Asin number found.')
# Publisher
try:
nfo_publisher = audio['TPUB'].text[0]
logger_meta.info('Publisher: %s', nfo_publisher)
except:
logger_meta.warning('Publisher not found.')
# copyright
try:
nfo_copy = audio['TCOP'].text[0]
logger_meta.info('Copyright: %s', nfo_copy)
except:
logger_meta.warning('copyright not found.')
# Link
try:
nfo_link = audio['WOAF'].text[0]
logger_meta.info('Link: %s', nfo_link)
except:
logger_meta.warning('Link not found.')
# Description
try:
nfo_desc = audio['COMM::eng'].text[0]
logger_meta.info('Description: %s', nfo_desc)
except:
logger_meta.warning('Description not found.')
# File Type
nfo_audio = f.mime[0]
logger_meta.info('File type: %s', nfo_audio)
# bitrate
nfo_bitrate = int(f.info.bitrate / 1000)
logger_meta.info('Bitrate: %s kbps', nfo_bitrate)
# Encoder
try:
nfo_encoder = audio['TENC'].text[0]
logger_meta.info('Encoder: %s', nfo_encoder)
except:
logger_meta.warning('Encoder not found.')
nfo_full = f.info.pprint()
logger_meta.info('Full audio stream information:: %s', nfo_full)
except:
# MP4
mp4_audio = MP4(audio_filename) # path: path to file
# no tag in MB4
# Here is the info from de audio file MP4(mb4)
try:
nfo_album = mp4_audio['\xa9alb']
logger_meta2.info('Album: %s', nfo_album[0])
nfo_album = nfo_album[0]
# if it as a : in the album name
try:
nfo_album = nfo_album.split(':')[0]
logger_meta2.info('(:) char found.')
except:
pass
try:
nfo_sub = nfo_album.split(':')[1]
logger_meta2.info('Album Subtitle: %s', nfo_sub)
except:
logger_meta2.info('Album Subtitle not found.')
# see if it has number at start
num_serie2 = re.search('([0-9]+)', nfo_album)
try:
num_serie3 = num_serie2.group()
except:
num_serie3 = ''
nfo_album = re.sub('^[\d-]*\s*', '', nfo_album)
except:
logger_meta2.warning('Book name not found.')
if nfo_sub == '':
try:
nfo_sub = audio['TIT3'].text[0]
logger_meta2.info('Book Subtitle: %s', nfo_sub)
except:
pass
else:
pass
# Artist/author
nfo_author = mp4_audio['\xa9ART']
logger_meta2.info('Author: %s', nfo_author[0])
nfo_author = nfo_author[0]
# correct format of author(ex: A. B. Mark)
nfo_author = re.sub(r'(?<=[A-Z])\.?\s?(?![a-z])', r'. ', nfo_author)
# Narrator
try:
nfo_narr = mp4_audio['\xa9wrt']
logger_meta2.info('Narrator: %s', nfo_narr[0])
nfo_narr = nfo_narr[0]
# correct format of narrator(ex: A. B. Mark)
nfo_narr = re.sub(r'(?<=[A-Z])\.?\s?(?![a-z])', r'. ', nfo_narr)
try:
nfo_split_narr = nfo_narr.split(", ")
nfo_split_narr1 = nfo_split_narr[0]
nfo_split_narr2 = nfo_split_narr[1]
nfo_split_narr3 = nfo_split_narr[2]
nfo_split_narr4 = nfo_split_narr[3]
print(nfo_split_narr[0])
except:
pass
except:
logger_meta2.warning('Narrator not found.')
# if author iqual to narrator get data from nfo.
if nfo_author == nfo_narr:
nfo_author = nfo_author2
logger_meta2.warning('Author the same as narrator, getting data from nfo file.')
else:
pass
# Genre
if nfo_genre == 'Audiobook' or nfo_genre == '':
try:
nfo_genre = mp4_audio['\xa9gen']
logger_meta2.info('Genre: %s', nfo_genre[0])
nfo_genre = nfo_genre[0]
except:
pass
else:
logger_meta2.warning('Genre not found.')
# Year
try:
nfo_year = mp4_audio['\xa9day']
logger_meta2.info('Year: %s', nfo_year[0])
nfo_year = nfo_year[0]
except:
logger_meta2.warning('Year not found.')
# Asin
try:
nfo_asin = mp4_audio['----:com.apple.iTunes:Asin']
nfo_asin = nfo_asin[0].decode('utf8')
logger_meta2.info('Asin: %s', nfo_asin)
except:
logger_meta2.warning('Asin not found.')
# Publisher
try:
nfo_publisher = mp4_audio['----:com.apple.iTunes:Publisher']
nfo_publisher = nfo_publisher[0].decode('utf8')
logger_meta2.info('Publisher: %s', nfo_publisher)
except:
logger_meta2.warning('Publisher not found.')
# Publisher2
if nfo_publisher == '':
try:
nfo_publisher = mp4_audio['\xa9pub']
nfo_publisher = nfo_publisher[0].decode('utf8')
logger_meta2.info('Publisher(2): %s', nfo_publisher)
except:
logger_meta2.warning('Publisher(2) not found.')
else:
pass
# Copyright
try:
nfo_copy = mp4_audio['cprt']
nfo_copy = nfo_copy[0]
logger_meta2.info('Copyright: %s', nfo_copy)
except: