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 | def search_and_download( # pylint: disable=R0911
self, song: Song
) -> Tuple[Song, Optional[Path]]:
"""
Search for the song and download it.
### Arguments
- song: The song to download.
### Returns
- tuple with the song and the path to the downloaded file if successful.
### Notes
- This function is synchronous.
"""
# Check if song has name/artist and url/song_id
if not (song.name and (song.artists or song.artist)) and not (
song.url or song.song_id
):
logger.error("Song is missing required fields: %s", song.display_name)
self.errors.append(f"Song is missing required fields: {song.display_name}")
return song, None
reinitialized = False
try:
# Create the output file path
output_file = create_file_name(
song=song,
template=self.settings["output"],
file_extension=self.settings["format"],
restrict=self.settings["restrict"],
file_name_length=self.settings["max_filename_length"],
)
except Exception:
song = reinit_song(song)
output_file = create_file_name(
song=song,
template=self.settings["output"],
file_extension=self.settings["format"],
restrict=self.settings["restrict"],
file_name_length=self.settings["max_filename_length"],
)
reinitialized = True
if song.explicit is True and self.settings["skip_explicit"] is True:
logger.info("Skipping explicit song: %s", song.display_name)
return song, None
# Initialize the progress tracker
display_progress_tracker = self.progress_handler.get_new_tracker(song)
try:
# Create the temp folder path
temp_folder = get_temp_path()
# Check if there is an already existing song file, with the same spotify URL in its
# metadata, but saved under a different name. If so, save its path.
dup_song_paths: List[Path] = self.known_songs.get(song.url, [])
# Remove files from the list that have the same path as the output file
dup_song_paths = [
dup_song_path
for dup_song_path in dup_song_paths
if (dup_song_path.absolute() != output_file.absolute())
and dup_song_path.exists()
]
# Checking if file already exists in all subfolders of output directory
file_exists = file_exists = output_file.exists() or dup_song_paths
if not self.settings["scan_for_songs"]:
for file_extension in self.scan_formats:
ext_path = output_file.with_suffix(f".{file_extension}")
if ext_path.exists():
dup_song_paths.append(ext_path)
if dup_song_paths:
logger.debug(
"Found duplicate songs for %s at %s",
song.display_name,
", ".join(
[f"'{str(dup_song_path)}'" for dup_song_path in dup_song_paths]
),
)
# If the file already exists and we don't want to overwrite it,
# we can skip the download
if ( # pylint: disable=R1705
Path(str(output_file.absolute()) + ".skip").exists()
and self.settings["respect_skip_file"]
):
logger.info(
"Skipping %s (skip file found) %s",
song.display_name,
"",
)
return song, output_file if output_file.exists() else None
elif file_exists and self.settings["overwrite"] == "skip":
logger.info(
"Skipping %s (file already exists) %s",
song.display_name,
"(duplicate)" if dup_song_paths else "",
)
display_progress_tracker.notify_download_skip()
return song, output_file
# Check if we have all the metadata
# and that the song object is not a placeholder
# If it's None extract the current metadata
# And reinitialize the song object
# Force song reinitialization if we are fetching albums
# they have most metadata but not all
if (
(song.name is None and song.url)
or (self.settings["fetch_albums"] and reinitialized is False)
or None
in [
song.genres,
song.disc_count,
song.tracks_count,
song.track_number,
song.album_id,
song.album_artist,
]
):
song = reinit_song(song)
reinitialized = True
# Don't skip if the file exists and overwrite is set to force
if file_exists and self.settings["overwrite"] == "force":
logger.info(
"Overwriting %s %s",
song.display_name,
" (duplicate)" if dup_song_paths else "",
)
# If the duplicate song path is not None, we can delete the old file
for dup_song_path in dup_song_paths:
try:
logger.info("Removing duplicate file: %s", dup_song_path)
dup_song_path.unlink()
except (PermissionError, OSError, Exception) as exc:
logger.debug(
"Could not remove duplicate file: %s, error: %s",
dup_song_path,
exc,
)
# Find song lyrics and add them to the song object
try:
lyrics = self.search_lyrics(song)
if lyrics is None:
logger.debug(
"No lyrics found for %s, lyrics providers: %s",
song.display_name,
", ".join(
[lprovider.name for lprovider in self.lyrics_providers]
),
)
else:
song.lyrics = lyrics
except Exception as exc:
logger.debug("Could not search for lyrics: %s", exc)
# If the file already exists and we want to overwrite the metadata,
# we can skip the download
if file_exists and self.settings["overwrite"] == "metadata":
most_recent_duplicate: Optional[Path] = None
if dup_song_paths:
# Get the most recent duplicate song path and remove the rest
most_recent_duplicate = max(
dup_song_paths,
key=lambda dup_song_path: dup_song_path.stat().st_mtime
and dup_song_path.suffix == output_file.suffix,
)
# Remove the rest of the duplicate song paths
for old_song_path in dup_song_paths:
if most_recent_duplicate == old_song_path:
continue
try:
logger.info("Removing duplicate file: %s", old_song_path)
old_song_path.unlink()
except (PermissionError, OSError) as exc:
logger.debug(
"Could not remove duplicate file: %s, error: %s",
old_song_path,
exc,
)
# Move the old file to the new location
if (
most_recent_duplicate
and most_recent_duplicate.suffix == output_file.suffix
):
most_recent_duplicate.replace(
output_file.with_suffix(f".{self.settings['format']}")
)
if (
most_recent_duplicate
and most_recent_duplicate.suffix != output_file.suffix
):
logger.info(
"Could not move duplicate file: %s, different file extension",
most_recent_duplicate,
)
display_progress_tracker.notify_complete()
return song, None
# Update the metadata
embed_metadata(
output_file=output_file,
song=song,
skip_album_art=self.settings["skip_album_art"],
)
logger.info(
f"Updated metadata for {song.display_name}"
f", moved to new location: {output_file}"
if most_recent_duplicate
else ""
)
display_progress_tracker.notify_complete()
return song, output_file
# Create the output directory if it doesn't exist
output_file.parent.mkdir(parents=True, exist_ok=True)
if song.download_url is None:
download_url = self.search(song)
else:
download_url = song.download_url
# Initialize audio downloader
audio_downloader: Union[AudioProvider, Piped]
if self.settings["audio_providers"][0] == "piped":
audio_downloader = Piped(
output_format=self.settings["format"],
cookie_file=self.settings["cookie_file"],
search_query=self.settings["search_query"],
filter_results=self.settings["filter_results"],
yt_dlp_args=self.settings["yt_dlp_args"],
)
else:
audio_downloader = AudioProvider(
output_format=self.settings["format"],
cookie_file=self.settings["cookie_file"],
search_query=self.settings["search_query"],
filter_results=self.settings["filter_results"],
yt_dlp_args=self.settings["yt_dlp_args"],
)
logger.debug("Downloading %s using %s", song.display_name, download_url)
# Add progress hook to the audio provider
audio_downloader.audio_handler.add_progress_hook(
display_progress_tracker.yt_dlp_progress_hook
)
download_info = audio_downloader.get_download_metadata(
download_url, download=True
)
temp_file = Path(
temp_folder / f"{download_info['id']}.{download_info['ext']}"
)
if download_info is None:
logger.debug(
"No download info found for %s, url: %s",
song.display_name,
download_url,
)
raise DownloaderError(
f"yt-dlp failed to get metadata for: {song.name} - {song.artist}"
)
display_progress_tracker.notify_download_complete()
# Copy the downloaded file to the output file
# if the temp file and output file have the same extension
# and the bitrate is set to auto or disable
# Don't copy if the audio provider is piped
# unless the bitrate is set to disable
if (
self.settings["bitrate"] in ["auto", "disable", None]
and temp_file.suffix == output_file.suffix
) and not (
self.settings["audio_providers"][0] == "piped"
and self.settings["bitrate"] != "disable"
):
shutil.move(str(temp_file), output_file)
success = True
result = None
else:
if self.settings["bitrate"] in ["auto", None]:
# Use the bitrate from the download info if it exists
# otherwise use `copy`
bitrate = (
f"{int(download_info['abr'])}k"
if download_info.get("abr")
else "copy"
)
elif self.settings["bitrate"] == "disable":
bitrate = None
else:
bitrate = str(self.settings["bitrate"])
# Convert the downloaded file to the output format
success, result = convert(
input_file=temp_file,
output_file=output_file,
ffmpeg=self.ffmpeg,
output_format=self.settings["format"],
bitrate=bitrate,
ffmpeg_args=self.settings["ffmpeg_args"],
progress_handler=display_progress_tracker.ffmpeg_progress_hook,
)
if self.settings["create_skip_file"]:
with open(
str(output_file) + ".skip", mode="w", encoding="utf-8"
) as _:
pass
# Remove the temp file
if temp_file.exists():
try:
temp_file.unlink()
except (PermissionError, OSError) as exc:
logger.debug(
"Could not remove temp file: %s, error: %s", temp_file, exc
)
raise DownloaderError(
f"Could not remove temp file: {temp_file}, possible duplicate song"
) from exc
if not success and result:
# If the conversion failed and there is an error message
# create a file with the error message
# and save it in the errors directory
# raise an exception with file path
file_name = (
get_errors_path()
/ f"ffmpeg_error_{datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}.txt"
)
error_message = ""
for key, value in result.items():
error_message += f"### {key}:\n{str(value).strip()}\n\n"
with open(file_name, "w", encoding="utf-8") as error_path:
error_path.write(error_message)
# Remove the file that failed to convert
if output_file.exists():
output_file.unlink()
raise FFmpegError(
f"Failed to convert {song.display_name}, "
f"you can find error here: {str(file_name.absolute())}"
)
download_info["filepath"] = str(output_file)
# Set the song's download url
if song.download_url is None:
song.download_url = download_url
display_progress_tracker.notify_conversion_complete()
# SponsorBlock post processor
if self.settings["sponsor_block"]:
# Initialize the sponsorblock post processor
post_processor = SponsorBlockPP(
audio_downloader.audio_handler, SPONSOR_BLOCK_CATEGORIES
)
# Run the post processor to get the sponsor segments
_, download_info = post_processor.run(download_info)
chapters = download_info["sponsorblock_chapters"]
# If there are sponsor segments, remove them
if len(chapters) > 0:
logger.info(
"Removing %s sponsor segments for %s",
len(chapters),
song.display_name,
)
# Initialize the modify chapters post processor
modify_chapters = ModifyChaptersPP(
downloader=audio_downloader.audio_handler,
remove_sponsor_segments=SPONSOR_BLOCK_CATEGORIES,
)
# Run the post processor to remove the sponsor segments
# this returns a list of files to delete
files_to_delete, download_info = modify_chapters.run(download_info)
# Delete the files that were created by the post processor
for file_to_delete in files_to_delete:
Path(file_to_delete).unlink()
try:
embed_metadata(
output_file,
song,
id3_separator=self.settings["id3_separator"],
skip_album_art=self.settings["skip_album_art"],
)
except Exception as exception:
raise MetadataError(
"Failed to embed metadata to the song"
) from exception
if self.settings["generate_lrc"]:
generate_lrc(song, output_file)
display_progress_tracker.notify_complete()
# Add the song to the known songs
self.known_songs.get(song.url, []).append(output_file)
logger.info('Downloaded "%s": %s', song.display_name, song.download_url)
return song, output_file
except (Exception, UnicodeEncodeError) as exception:
if isinstance(exception, UnicodeEncodeError):
exception_cause = exception
exception = DownloaderError(
"You may need to add PYTHONIOENCODING=utf-8 to your environment"
)
exception.__cause__ = exception_cause
display_progress_tracker.notify_error(
traceback.format_exc(), exception, True
)
self.errors.append(
f"{song.url} - {exception.__class__.__name__}: {exception}"
)
return song, None
|