class PlaylistDownloader():
    """
    Base class for downloading playlists using Playlst class of pytube.
    """
    def __init__(self, playlist_url, type, filepath) -> None:
        """
        playlist_url = URL to the playlist on Youtube.

        type = Download type, whether audio or video.

        filepath = The file location where all the videos of the playlist will be saved. In the filepath, a new directory with the playlost name would be created.
        """
        self.playlist_url = playlist_url
        self.type = type

        # * validating the url
        valid = validators.url(self.playlist_url)
        if valid != True:
            print("Invalid playlist url!")
            quit()

        # * initialising playlist object
        self.plt = Playlist(playlist_url)

        # * altering the playlist title for filepath since [.?*/,|\:;] are not allowed in a filename
        playlist_name = self.plt.title
        removals = re.compile(r'''[.?*/,|\:;]''')
        self.playlist_name = re.sub(removals, "", playlist_name)

        # * checking the filepath
        if filepath != None:
            if exists(filepath):
                self.filepath = join_path(filepath, playlist_name)
            else:
                print(
                    "No such directory in the system, hence the video would be downloaded in the current working directory: {}."
                    .format(getcwd()))
                self.filepath = join_path(getcwd(), playlist_name)
        else:
            self.filepath = join_path(getcwd(), playlist_name)

        while True:
            try:
                mkdir(join_path(filepath, self.playlist_name))
                break
            except FileExistsError:
                new_folder_name = join_path(
                    filepath,
                    self.playlist_name) + "" + random_choice(alphabets)
                print(
                    f"Path '{join_path(filepath, self.playlist_name)}' already exists, hence making new folder with name {new_folder_name}."
                )
                mkdir(new_folder_name)
                break

    def download_all_videos(self, resolution: str = "720p"):
        for vid in self.plt.video_urls:
            yt = YouTubeDownloader(vid, "video", self.filepath)
            yt.download_video(resolution)

    def download_all_audio(self):
        for vid in self.plt.video_urls():
            yt = YouTubeDownloader(vid, "audio", self.filepath)
            yt.download_audio()
Exemple #2
0
def download_yt_podcast(url):
    pl = Playlist(url)
    print(pl.video_urls())