def enqueue_audio_playlist(self, arg):
        """Add all audio streams in a YouTube playlist to the playback queue.

        :param arg: a YouTube playlist id

        """
        logging.info("arg : %s", arg)
        try:
            print_msg("[YouTube] [Audio playlist] : '{0}'. ".format(arg))
            count = len(self.queue)

            playlist = pafy.get_playlist2(arg)
            if len(playlist) > 0:
                for yt_video in playlist:
                    self._add_to_playback_queue(
                        video=yt_video,
                        info=VideoInfo(ytid=yt_video.videoid,
                                       title=yt_video.title),
                    )

            if count == len(self.queue):
                raise ValueError

            self._update_play_queue_order()

        except ValueError:
            raise ValueError(str("Playlist not found : %s" % arg))
def main():

    # URL for just2good's list of videos
    url = 'https://www.youtube.com/playlist?list=UUp_mZttcKNIcUBVdi0wTdIA'

    # Open file to retrieve previous count
    prevFile = open('previous.txt', 'r')

    # Setting the previous count
    prevCount = int(prevFile.read())
    prevFile.close()

    # Creating playlist object and current count
    playlist = pafy.get_playlist2(url)
    currCount = len(playlist)

    # If new videos have been added, download the most recent ones
    if (currCount > prevCount):
        for i in range(0, currCount - prevCount):
            print("Downloading...'" + playlist[i].title + "'")
            playlist[i].getbest().download()

    # Clearing the plalist object
    playlist = None

    # Clearing previous value and adding new previous value
    prevFile = open('previous.txt', 'w')
    prevFile.truncate()
    prevFile.write(str(currCount))

    # Closing the file
    prevFile.close()
    def getVideoPlaylist(self):
        ''' retrieving videos from the list'''

        try:
            playList = pafy.get_playlist2(self.playlistID)
            print("Playlist Title:{}".format(playList.title))
            self.playlistTitle = listtitle = playList.title
            # title of the xspf (vlc playlist) file to avoid symbol
            self.XSPFTitle = re.sub(r'[^\w]', ' ', listtitle).replace(" ", "_")
            print("Playlist author: {}".format(playList.author))
            self.playlistLength = len(playList)
            print("Videos in Playlist: {}".format(self.playlistLength))
            print('Getting videos from the playlist')
            td = []
            for id, video in enumerate(playList):
                #     thread = threading.Thread(target=self.getVideo, args=(video,))
                #     thread.start()
                #     td.append(thread)
                # for t in td:
                #     t.join(5)

                if threading.active_count() == VideoPlaylist.THREAD_LIMIT:
                    while not threading.active_count() == 5:
                        pass
                thread = threading.Thread(target=self.getVideo, args=(video,))
                thread.start()
            while not threading.active_count() == 1:
                pass

        except ValueError as r:
            print(r)
            exit(1)
Example #4
0
 def add_playlist(self, url, by_name, next):
     playlist_ = pafy.get_playlist2(url)
     for item in playlist_:
         best = item.getbest()
         media = self.instance.media_new(item)
         media.get_mrl()
         self.playlist.append(media)
Example #5
0
    def refreshplaylistfromyoutube(self, force=False):
        if self.url:
            playlistobject = pafy.get_playlist2(self.url)
            playlistlength = len(playlistobject)

            if playlistlength != len(self.ytplaylist) or force:
                print("Songlist is updating.")
                try:
                    for video in playlistobject:
                        if video.videoid not in map(lambda a: a.vidid, self.ytplaylist):
                            if video.videoid not in map(lambda a: a.vidid, G.songset):
                                newsong = Song(video.videoid, video.title, video.watchv_url, video.duration, video.author, video.getbestthumb().split("?")[0])
                                G.songset.add(newsong)
                                self.ytplaylist.add(newsong)
                                print(f"Downloading and adding {video.title}")

                            else:
                                songlist = list(G.songset)
                                correlatesong = songlist[list(map(lambda a: a.vidid, songlist)).index(video.videoid)]
                                self.ytplaylist.add(correlatesong)
                                print(f"Finding and adding {video.title}")
                except pafy.util.GdataError as e:
                    print("Couldn't update songlist:", e)

        else:
            print("Local playlist - no update.")
Example #6
0
    def handleButtonFirstStep(self):
        link = self.le_playlist_link.displayText()
        # print("Link : " + link)
        import pafy
        try:
            self.playlist = pafy.get_playlist2(link, True, False, False, None)
        except ValueError:
            QtWidgets.QMessageBox.warning(self.main, 'Lien invalide',
                                          "Le lien est invalide :\n" + link,
                                          QtWidgets.QMessageBox.Ok,
                                          QtWidgets.QMessageBox.Ok)
            return

        # print("The playlist %s contains %d vidéos.\nBy %s" % (playlist.title, len(playlist), playlist.author))
        self.label_3.setText(
            "La playlist %s de %s contient %d vidéos." %
            (self.playlist.title, self.playlist.author, len(self.playlist)))
        self.cb_debut.addItem(DEBUT)
        for x in range(1, len(self.playlist)):
            self.cb_debut.addItem(str(x + 1))

        self.cb_fin.addItem(FIN)
        for x in range(len(self.playlist), 1, -1):
            self.cb_fin.addItem(str(x - 1))
        self.stackedWidget.setCurrentIndex(1)
Example #7
0
    def update(self):
        """Uses pafy to create episodes from all videos in a playlist."""
        # add all videos from playlist
        if self.playlist_url:
            playlist = pafy.get_playlist2(self.playlist_url)
            self.description = playlist.description

            # get_playlist2 does not automatically filter out private/deleted videos, for that you have to access at
            # least one of them
            # Afaik it filters out private/deleted videos but keeps videos that are claimed by eg UMG but this
            # is probably because of geo restrictions
            try:
                playlist[0]
            except IndexError:
                pass

            # add new episodes
            for video in playlist:
                if not self.episode_set.filter(url=video.watchv_url).exists():
                    self.episode_set.create(url=video.watchv_url)

        self.save()
            
        # how would I throw that into the queue aswell? I could create a group and block unit that's done
        for episode in self.episode_set.filter(invalid=False, updated=False):
            episode.update()

        return f"Updated podcast {self}"
Example #8
0
 def get_youtube_playlist(playlist_url):
     video_list = pafy.get_playlist2(playlist_url)
     for video in video_list:
         try:
             video.audio_url = video.getbestaudio().url
         except Exception:
             video.audio_url = None
     return video_list
Example #9
0
def video_info(num):
    """ Get video information. """
    if g.browse_mode == "ytpl":
        p = g.ytpls[int(num) - 1]

        # fetch the playlist item as it has more metadata
        if p['link'] in g.pafy_pls:
            ytpl = g.pafy_pls[p['link']][0]
        else:
            g.content = logo(col=c.g)
            g.message = "Fetching playlist info.."
            screen.update()
            util.dbg("%sFetching playlist using pafy%s", c.y, c.w)
            ytpl = pafy.get_playlist2(p['link'])
            g.pafy_pls[p['link']] = (ytpl, util.IterSlicer(ytpl))

        ytpl_desc = ytpl.description
        g.content = generate_songlist_display()
        created = util.yt_datetime_local(p['created'])
        updated = util.yt_datetime_local(p['updated'])
        out = c.ul + "Playlist Info" + c.w + "\n\n"
        out += p['title']
        out += "\n" + ytpl_desc
        out += ("\n\nAuthor     : " + p['author'])
        out += "\nSize       : " + str(p['size']) + " videos"
        out += "\nCreated    : " + created[1] + " " + created[2]
        out += "\nUpdated    : " + updated[1] + " " + updated[2]
        out += "\nID         : " + str(p['link'])
        out += ("\n\n%s[%sPress enter to go back%s]%s" % (c.y, c.w, c.y, c.w))
        g.content = out

    elif g.browse_mode == "normal":
        g.content = logo(c.b)
        screen.update()
        screen.writestatus("Fetching video metadata..")
        item = (g.model[int(num) - 1])
        streams.get(item)
        p = util.get_pafy(item)
        pub = datetime.strptime(str(p.published), "%Y-%m-%d %H:%M:%S")
        pub = util.utc2local(pub)
        screen.writestatus("Fetched")
        out = c.ul + "Video Info" + c.w + "\n\n"
        out += p.title or ""
        out += "\n" + (p.description or "") + "\n"
        out += "\nAuthor     : " + str(p.author)
        out += "\nPublished  : " + pub.strftime("%c")
        out += "\nView count : " + str(p.viewcount)
        out += "\nRating     : " + str(p.rating)[:4]
        out += "\nLikes      : " + str(p.likes)
        out += "\nDislikes   : " + str(p.dislikes)
        out += "\nCategory   : " + str(p.category)
        out += "\nLink       : " + "https://youtube.com/watch?v=%s" % p.videoid
        if config.SHOW_QRCODE.get:
            out += "\n" + qrcode_display(
                "https://youtube.com/watch?v=%s" % p.videoid)

        out += "\n\n%s[%sPress enter to go back%s]%s" % (c.y, c.w, c.y, c.w)
        g.content = out
Example #10
0
def url_getter(url):
    # get url and make needed changes on it
    global details, playlist
    details = pafy.get_playlist(url)
    playlist = pafy.get_playlist2(url)

    print(details['title'])

    print('length of the playlist: {}'.format(len(playlist)))
    music_getter(details, playlist)
Example #11
0
def info(num):
    """ Get video description. """
    if g.browse_mode == "ytpl":
        p = g.ytpls[int(num) - 1]

        # fetch the playlist item as it has more metadata
        if p['link'] in g.pafy_pls:
            ytpl = g.pafy_pls[p['link']][0]
        else:
            g.content = logo(col=c.g)
            g.message = "Fetching playlist info.."
            screen.update()
            util.dbg("%sFetching playlist using pafy%s", c.y, c.w)
            ytpl = pafy.get_playlist2(p['link'])
            g.pafy_pls[p['link']] = (ytpl, util.IterSlicer(ytpl))

        ytpl_desc = ytpl.description
        g.content = generate_songlist_display()

        created = util.yt_datetime(p['created'])[0]
        updated = util.yt_datetime(p['updated'])[0]
        out = c.ul + "Playlist Info" + c.w + "\n\n"
        out += p['title']
        out += "\n" + ytpl_desc
        out += ("\n\nAuthor     : " + p['author'])
        out += "\nSize       : " + str(p['size']) + " videos"
        out += "\nCreated    : " + time.strftime("%x %X", created)
        out += "\nUpdated    : " + time.strftime("%x %X", updated)
        out += "\nID         : " + str(p['link'])
        out += ("\n\n%s[%sPress enter to go back%s]%s" % (c.y, c.w, c.y, c.w))
        g.content = out

    elif g.browse_mode == "normal":
        g.content = logo(c.b)
        screen.update()
        screen.writestatus("Fetching video metadata..")
        item = (g.model[int(num) - 1])
        streams.get(item)
        p = util.get_pafy(item)
        pub = time.strptime(str(p.published), "%Y-%m-%d %H:%M:%S")
        screen.writestatus("Fetched")
        out = c.ul + "Video Info" + c.w + "\n\n"
        out += p.title or ""
        out += "\n" + (p.description or "")
        out += "\n\nAuthor     : " + str(p.author)
        out += "\nPublished  : " + time.strftime("%c", pub)
        out += "\nView count : " + str(p.viewcount)
        out += "\nRating     : " + str(p.rating)[:4]
        out += "\nLikes      : " + str(p.likes)
        out += "\nDislikes   : " + str(p.dislikes)
        out += "\nCategory   : " + str(p.category)
        out += "\nLink       : " + "https://youtube.com/watch?v=%s" % p.videoid
        out += "\n\n%s[%sPress enter to go back%s]%s" % (c.y, c.w, c.y, c.w)
        g.content = out
Example #12
0
async def play(ctx, url):
    music_player = music_players.get(ctx.guild.id)
    songs = []
    if not music_player:
        music_player = await join(ctx)
    if 'playlist' in url:
        playlist = pafy.get_playlist2(url)
        songs = [song for song in playlist]
    else:
        song = pafy.new(url)
        songs.append(song)
    await music_player.queue_songs(songs)
def playlistURL(URL):
    plurl = URL
    try:
        playlist = pafy.get_playlist(playlist_url=plurl)
    except:
        playlist = pafy.get_playlist2(playlist_url=plurl)

    length = int(len(playlist['items']))
    Title = []
    for i in range(0, length):
        Title.append(playlist['items'][i]['playlist_meta']['title'])
    return length, Title
Example #14
0
    def process(self, request):
        ref = db.reference()
        requests_ref = ref.child('requests/{0}'.format(request['requestId']))
        config = requests_ref.get()
        
        if config:
            playlistIds = []
            requests_ref.update({"processing_status": "Parsing playlist..."})
            playlistObject = pafy.get_playlist2(config['playlistUrl'])
            print('Playlist has ' + str(len(playlistObject)) + ' vids.')
            bar = Bar('Retrieving playlist info', max=len(playlistObject), suffix='%(index)d/%(max)d - %(percent).1f%%')
            for vidObj in playlistObject:
                    playlistIds.append(vidObj.videoid)
                    bar.next()
            bar.finish()

            requests_ref.update({"processing_status": "Processing video..."})

            vidsToDl = []
            if config['pickRandom']:
                vidsToDl = random.sample(playlistIds, config['numberVideos'])
            else:
                # TODO: take n first videos from playlistIds
                pass                

            tempVidPath = './temp_vids'
            if not os.path.exists(tempVidPath):
                os.makedirs(tempVidPath)
                
            for vid in vidsToDl:
                v = pafy.new(vid)
                s = v.getbest(preftype="mp4") # in the future make this a parameter to choose resolution
                filename = s.download(filepath="./temp_vids/" + vid + ".mp4")

            vids = []
            # TODO: for v2, let users upload a video
            # vids.append(VideoFileClip("intro.mp4"))
            for vid in vidsToDl:
                vids.append(VideoFileClip("./temp_vids/" + vid + ".mp4"))
            
            final = concatenate_videoclips(vids, method='compose')
            requests_ref.update({"processing_status": "Exporting video..."})
            final.write_videofile("{0}.mp4".format(request['requestId'].replace('-', '_')), fps=config['videosFps'])

            print "Uploading file"
            requests_ref.update({"processing_status": "Uploading video..."})
            blob = storageBucket.blob('user-videos/{0}.mp4'.format(request['requestId']))
            blob.upload_from_filename("{0}.mp4".format(request['requestId'].replace('-', '_')))
            requests_ref.update({ "final_export_url": blob.public_url, "processing_status": "Exported"})
            return blob.public_url

        return None
Example #15
0
def playlistData(ids, num):
    # array of playlist ids...get num from each
    ret = []
    for id in ids:
        url = "https://www.youtube.com/playlist?list={0}".format(id)
        playlist = pafy.get_playlist2(url)
        playData = []
        for item in playlist:
            #print(item.videoid)
            playData.append(item.videoid)
            if len(playData) == num:
                break
        ret = ret + playData
    return ret
Example #16
0
def plist(parturl):
    """ Retrieve YouTube playlist. """

    if parturl in g.pafy_pls:
        ytpl, plitems = g.pafy_pls[parturl]
    else:
        util.dbg("%sFetching playlist using pafy%s", c.y, c.w)
        ytpl = pafy.get_playlist2(parturl)
        plitems = util.IterSlicer(ytpl)
        g.pafy_pls[parturl] = (ytpl, plitems)

    def pl_seg(s, e):
        return [Video(i.videoid, i.title, i.length) for i in plitems[s:e]]

    msg = "Showing YouTube playlist %s" % (c.y + ytpl.title + c.w)
    loadmsg = "Retrieving YouTube playlist"
    paginatesongs(pl_seg, length=len(ytpl), msg=msg, loadmsg=loadmsg)
Example #17
0
def plist(parturl):
    """ Retrieve YouTube playlist. """

    if parturl in g.pafy_pls:
        ytpl, plitems = g.pafy_pls[parturl]
    else:
        util.dbg("%sFetching playlist using pafy%s", c.y, c.w)
        ytpl = pafy.get_playlist2(parturl)
        plitems = util.IterSlicer(ytpl)
        g.pafy_pls[parturl] = (ytpl, plitems)

    def pl_seg(s, e):
        return [Video(i.videoid, i.title, i.length) for i in plitems[s:e]]

    msg = "Showing YouTube playlist %s" % (c.y + ytpl.title + c.w)
    loadmsg = "Retrieving YouTube playlist"
    paginatesongs(pl_seg, length=len(ytpl), msg=msg, loadmsg=loadmsg)
Example #18
0
 def __init__(self, name, url):
     self.tracks = collections.OrderedDict()
     self.playing_track = None
     self.next = None
     self.title = None
     if isinstance(url, str):
         playlist = pafy.get_playlist2(url)
         self.name = name
         self.title = playlist.title
         self.author = playlist.author
         for track in playlist:
             new_track = Track(track.watchv_url, track)
             self[new_track.audiostream.url] = new_track
     else:
         self.name = name
         self.author = 'me'
         for track_url in url:
             new_track = Track(track_url)
             self[new_track.audiostream.url] = new_track
     self.size = len(self.tracks)
Example #19
0
    def __init__(self,
                 youtube_playlist_url,
                 youtube_api_key,
                 song_info_enabled=True):
        pafy.set_api_key(youtube_api_key)
        self.playlist = pafy.get_playlist2(
            youtube_playlist_url)  # Pafy playlist object
        self.song_index = 0  # Current song index
        self.song_counter = 0  # Stores how many songs have been played, resets if every song has been played.
        self.total_songs = len(
            self.playlist)  # Amount of songs in the Pafy object
        self.current_song = None  # Stores the current song
        os.environ[
            "VLC_VERBOSE"] = "-1"  # Decrease verbosity of VLC error output, necessary because errors sometimes occur that spam the screen but otherwise have no effect
        self.vlc_player = vlc.MediaPlayer()  # Stores the VLC object
        self.song_info_enabled = song_info_enabled  # The current song information is printed when the song changes if this is enabled
        self.song_history = []  # Stores indexes of songs that have been played

        # User input
        self.cmds = CommandHandler(
            self)  # Collects user input on another thread
Example #20
0
    def Download_playlist(self):
        try:
            plurl = self.lineEdit_6.text()
            playlist = pafy.get_playlist2(plurl)

            os.chdir(self.lineEdit_5.text())
            if not os.path.exists(self.Valid_Name(playlist.title)):
                os.mkdir(self.Valid_Name(playlist.title))
            os.chdir(self.Valid_Name(playlist.title))

            current_v = 0

            for videos in playlist:
                current_v += 1
                self.lcdNumber.display(current_v)
                QApplication.processEvents()
                videos.getbest(preftype='mp4').download(
                    filepath=f'{self.lineEdit_5.text()}\\{self.Valid_Name(playlist.title)}',
                    quiet=True, callback=self.progressbar)
                QApplication.processEvents()
        except Exception:
            QMessageBox.warning(self, 'Corrupted Data', 'Verify that you have entered a valid link Or valid Path')
            return
Example #21
0
    def DownloadPlaylist():
        url = "https://www.youtube.com/playlist?list=PLLcpBVEQD-CwpLaJzjFbKhBbAn2Wz4lle"  #The url of the playlist to be used

        with open(os.path.join(dependencies.globalFolder, 'config.txt'),
                  'r') as f:
            cont = f.read().split(
                '\n'
            )  #Reads the data from 'config.txt', as created in dependencies.py

        location = os.path.abspath(cont[0])  #Folder to save downloaded videos
        t = str(cont[1])  #Type of download, Audio|Video

        #Initializing variables and retrieving playlist data
        playlist = pafy.get_playlist2(url)
        #state = dependencies.proceed    #If the code runs for the 1st time, it will not download, just resolve the creation of folders and definition of destination folders, etc.
        state = True
        logging.info("\n" + "*" + "-" * 80 + "*" + "\n" + " " * 5 + "-" * 72 +
                     "\n")  #Aesthetic spacer for command outputs

        for video in playlist:
            logging.info("\n\tCurrently in music: %s" % (video.title))
            try:
                if t == '1':  #Download as video
                    Video_handler.download(video, location)

                elif t == '0':  #Download as audio
                    Audio_handler.download(video, location)

            except Exception as e:
                logging.error("Process couldn't be concluded!\n", e)

            logging.info("\n" + "-" * 80 +
                         "\n")  #Aesthetic spacer for command outputs

        logging.info("\tProcess finished successfully.\n")
        logging.info("\n" + " " * 5 + "-" * 72 + "\n" + "*" + "-" * 80 + "*" +
                     "\n")
Example #22
0
    def __init__(self, playlist_url, song_info_enabled=True):
        self.playlist = pafy.get_playlist2(
            playlist_url)  # Pafy playlist object
        self.song_index = 0  # Current song index
        self.song_counter = 0  # Stores how many songs have been played, resets if every song has been played.
        self.total_songs = len(
            self.playlist)  # Amount of songs in the Pafy object
        self.current_song = None  # Stores the current song
        self.vlc_player = vlc.MediaPlayer()  # Stores the VLC object

        self.song_info_enabled = song_info_enabled  # The current song information is printed when the song changes if this is enabled
        self.song_history = []  # Stores indexes of songs that have been played

        # User input
        self.cmds = CommandHandler(self)
        self.input_thread_started = False

        # Command helpers
        self.skip_song = False  # Becomes True if the user enters the skip command
        self.exit_program = False  # Becomes True if the user enters the exit command
        self.loop_song = False  # Becomes True if the user enters the loop command
        self.shuffle_playlist = False  # Becomes True if the user enters the shuffle command
        self.back_song = False  # Becomes True if the user enters the back command
        self.back_amount = 1  # Stores how many indexes back will be popped from song_history to get songs in history
    def enqueue_audio_playlist(self, arg):
        """Add all audio streams in a YouTube playlist to the playback queue.

        :param arg: a YouTube playlist id

        """
        logging.info('arg : %s', arg)
        try:
            count = len(self.queue)

            playlist = pafy.get_playlist2(arg)
            if len(playlist) > 0:
                for yt_video in playlist:
                    self.add_to_playback_queue(video=yt_video, \
                                               info=VideoInfo(ytid=yt_video.videoid, \
                                                              title=yt_video.title))

            if count == len(self.queue):
                raise ValueError

            self.__update_play_queue_order()

        except ValueError:
            raise ValueError(str("Playlist not found : %s" % arg))
    def enqueue_audio_playlist(self, arg):
        """Add all audio streams in a YouTube playlist to the playback queue.

        :param arg: a YouTube playlist id

        """
        logging.info('arg : %s', arg)
        try:
            count = len(self.queue)

            playlist = pafy.get_playlist2(arg)
            if len(playlist) > 0:
                for yt_video in playlist:
                    self.add_to_playback_queue(video=yt_video, \
                                               info=VideoInfo(ytid=yt_video.videoid, \
                                                              title=yt_video.title))

            if count == len(self.queue):
                raise ValueError

            self.__update_play_queue_order()

        except ValueError:
            raise ValueError(str("Playlist not found : %s" % arg))
Example #25
0
async def queue(cmd, message, args):
    if message.author.voice:
        if args:
            qry = ' '.join(args)
            if '?list=' in qry:
                list_id = qry.split('list=')[1].split('&')[0]
                plist = pafy.get_playlist2(list_id)
                item_count = yt_playlist_adder(message.guild.id, cmd,
                                               message.author, plist)
                embed_title = f'ℹ Added {item_count} items from {plist.title}.'
                embed = discord.Embed(color=0x0099FF, title=embed_title)
                await message.channel.send(None, embed=embed)
                await asyncio.sleep(3)
            else:
                if qry.startswith('https://'):
                    if 'youtu' in qry:
                        song_url = qry
                        sound = pafy.new(song_url)
                        sound_type = 0
                    elif 'soundcloud' in qry:
                        song_url = qry
                        sc_cli = soundcloud.Client(
                            client_id=SoundCloudClientID)
                        sound = sc_cli.get('/resolve', url=qry).fields()
                        sound_type = 1
                    else:
                        response = discord.Embed(
                            color=0xDB0000, title='❗ Unsupported URL Provided')
                        response.set_footer(
                            text=
                            'We only support YouTube and SoundCloud for now.')
                        return
                else:
                    song_url = await search_youtube(qry)
                    sound = pafy.new(song_url)
                    sound_type = 0
                data = {
                    'url': song_url,
                    'type': sound_type,
                    'requester': message.author,
                    'sound': sound,
                    'timestamp': arrow.now().timestamp
                }
                embed = discord.Embed(color=0x66CC66)
                cmd.bot.music.add_to_queue(message.guild.id, data)
                if sound_type == 0:
                    embed.add_field(name='✅ Added To Queue', value=sound.title)
                    embed.set_thumbnail(url=sound.thumb)
                    embed.set_author(
                        name=
                        f'{message.author.name}#{message.author.discriminator}',
                        icon_url=user_avatar(message.author))
                    embed.set_footer(text=f'Duration: {sound.duration}')
                elif sound_type == 1:
                    embed.add_field(name='✅ Added To Queue',
                                    value=sound['title'])
                    embed.set_thumbnail(url=sound['artwork_url'])
                    embed.set_author(
                        name=
                        f'{message.author.name}#{message.author.discriminator}',
                        icon_url=user_avatar(message.author))
                else:
                    return
                await message.channel.send(None, embed=embed)
        else:
            q = cmd.bot.music.get_queue(message.guild.id)
            if q.empty():
                embed = discord.Embed(color=0x0099FF,
                                      title='ℹ The Queue Is Empty')
                await message.channel.send(None, embed=embed)
            else:
                q_list = list(q.queue)[:5]
                embed = discord.Embed(
                    color=0x0099FF,
                    title=
                    f'ℹ The {len(q_list)} Upcoming Songs (Total: {len(list(q.queue))})'
                )
                for item in q_list:
                    if item['type'] == 0:
                        information = f'Requested By: {item["requester"].name}\nDuration: {item["sound"].duration}'
                        embed.add_field(name=item['sound'].title,
                                        value=f'```\n{information}\n```',
                                        inline=False)
                    elif item['type'] == 1:
                        information = f'Requested By: {item["requester"].name}\nDuration: {time.strftime("%H:%M:%S", time.gmtime(item["sound"]["duration"]//1000))}'
                        embed.add_field(name=item['sound']['title'],
                                        value=f'```\n{information}\n```',
                                        inline=False)
                embed.set_footer(
                    text=f'To see the currently playing song type {Prefix}np')
                await message.channel.send(None, embed=embed)
Example #26
0
 def __init__(self, url):
     self.playlist = pafy.get_playlist2(url)
Example #27
0
async def queue(cmd, message, args):
    if message.author.voice:
        if args:
            qry = ' '.join(args)
            if qry.startswith('<'):
                qry = qry[1:]
            if qry.endswith('>'):
                qry = qry[:-1]
            if '?list=' in qry:
                list_id = qry.split('list=')[1].split('&')[0]
                plist = pafy.get_playlist2(list_id)
                item_count = await yt_playlist_adder(message.guild.id, cmd,
                                                     message.author, plist)
                embed_title = f'ℹ Added {item_count} items from {plist.title}.'
                embed = discord.Embed(color=0x0099FF, title=embed_title)
                await message.channel.send(None, embed=embed)
                await asyncio.sleep(3)
            else:
                if qry.startswith('https://'):
                    if 'youtu' in qry:
                        song_url = qry
                        sound = pafy.new(song_url)
                        sound_type = 0
                    elif 'bandcamp.com' in qry:
                        await queuebandcamp(cmd, message, args)
                        return
                    else:
                        response = discord.Embed(
                            color=0xDB0000, title='❗ Unsupported URL Provided')
                        response.set_footer(
                            text=
                            'We only support YouTube and SoundCloud for now.')
                        await message.channel.send(None, embed=response)
                        return
                else:
                    song_url = await search_youtube(qry)
                    sound = pafy.new(song_url)
                    sound_type = 0
                data = {
                    'url': song_url,
                    'type': sound_type,
                    'requester': message.author,
                    'sound': sound,
                    'timestamp': arrow.now().timestamp
                }
                embed = discord.Embed(color=0x66CC66)
                await cmd.bot.music.add_to_queue(message.guild.id, data)
                if sound_type == 0:
                    embed.add_field(name='✅ Added To Queue', value=sound.title)
                    embed.set_thumbnail(url=sound.thumb)
                    embed.set_author(
                        name=
                        f'{message.author.name}#{message.author.discriminator}',
                        icon_url=user_avatar(message.author))
                    embed.set_footer(text=f'Duration: {sound.duration}')
                elif sound_type == 1:
                    embed.add_field(name='✅ Added To Queue',
                                    value=sound['title'])
                    embed.set_thumbnail(url=sound['artwork_url'])
                    embed.set_author(
                        name=
                        f'{message.author.name}#{message.author.discriminator}',
                        icon_url=user_avatar(message.author))
                else:
                    return
                await message.channel.send(None, embed=embed)
        else:
            q = cmd.bot.music.get_queue(message.guild.id)
            q_bup = asyncio.Queue()
            if q.empty():
                embed = discord.Embed(color=0x0099FF,
                                      title='ℹ The Queue Is Empty')
                await message.channel.send(None, embed=embed)
            else:
                q_list = []
                while not q.empty():
                    q_item = await q.get()
                    q_list.append(q_item)
                    await q_bup.put(q_item)
                q_list_mini = q_list[:5]
                cmd.bot.music.queues.update({message.guild.id: q_bup})
                embed = discord.Embed(
                    color=0x0099FF,
                    title=
                    f'ℹ The {len(q_list_mini)} Upcoming Songs (Total: {len(q_list)})'
                )
                for item in q_list_mini:
                    if item['type'] == 0:
                        information = f'Requested By: {item["requester"].name}\nDuration: {item["sound"].duration}'
                        embed.add_field(name=item['sound'].title,
                                        value=f'```\n{information}\n```',
                                        inline=False)
                    elif item['type'] == 1:
                        information = f'Requested By: {item["requester"].name}\nDuration: {time.strftime("%H:%M:%S", time.gmtime(item["sound"]["duration"]//1000))}'
                        embed.add_field(name=item['sound']['title'],
                                        value=f'```\n{information}\n```',
                                        inline=False)
                    elif item['type'] == 2:
                        information = f'Requested By: {item["requester"].name}\nDuration: {time.strftime("%H:%M:%S", time.gmtime(int(item["sound"]["duration"])))}'
                        embed.add_field(
                            name=
                            f"{item['sound']['artist']} - {item['sound']['title']}",
                            value=f'```\n{information}\n```',
                            inline=False)
                if message.guild.id in cmd.bot.music.repeaters:
                    embed.set_footer(
                        text='The current queue is set to repeat.')
                else:
                    embed.set_footer(
                        text=
                        f'To see the currently playing song type {cmd.bot.get_prefix(message)}np'
                    )
                await message.channel.send(None, embed=embed)
def add_playlist_data(playlist_url):
    playlist = pafy.get_playlist2(playlist_url)
    return playlist
Example #29
0
def run_youtube_playlist_search(arg):
    return pafy.get_playlist2(arg)
    chunk_size in ms

    iterate over chunks until you find the first one with sound
    '''
    trim_ms = 0 # ms

    assert chunk_size > 0 # to avoid infinite loop
    while sound[trim_ms:trim_ms+chunk_size].dBFS < silence_threshold and trim_ms < len(sound):
        trim_ms += chunk_size

    return trim_ms

os.makedirs(webm_dir, exist_ok=True)
os.makedirs(mp3_dir, exist_ok=True)

playlist = pafy.get_playlist2(playlist_url)

print('[*] Playlist "%s" has %d songs!' % (playlist.title, len(playlist)))

for i, song in enumerate(tqdm(playlist)):
    title = song.title
    title = ''.join(c for c in title if c.isalnum() or c in keepcharacters).rstrip()

    webm_path = os.path.join(webm_dir, title + '.webm')
    mp3_path = os.path.join(mp3_dir, title + '.mp3')

    if verbose:
        print('[.] Downloading %d: %s' % (i + 1, title))

    try:
        yt_audio = song.getbestaudio(preftype='webm')
Example #31
0
# Python script to download all videos from a YouTube playlist as .m4a audio
# files and save them in a folder. "pafy" library is a dependency (can be
# installed using pip)
import pafy     # Has to be installed
import ftfy     # Has to be installed
import re
import os

# Enter playlist's URL
url = raw_input("Please enter a valid YouTube playlist URL: ")
playlist = pafy.get_playlist2(url)

print("\n"+playlist.title+" successfully opened")
# Create a folder for saving all the songs there
if not os.path.exists(playlist.title):
    os.makedirs(playlist.title)
# Cycle over all videos in the playlist, skip any that has problems
counter = 0
errors = 0
for video in playlist:
    counter += 1
    print("- Retrieving audio "+str(counter)+" of "+str(len(playlist))+"...")
    if not re.findall("Deleted video", video.title):
        audiostreams = video.audiostreams
        audio_options = []
        # Cycle over all the audio streams available in the video
        for audio in audiostreams:
            # Get only m4a format streams
            if re.findall('m4a',audio.extension):
                audio_options.append(audio)
        # Get the highest quality m4a audio (typically, the latest in the list)
Example #32
0
def playlist_download():
    if os.name == "nt":
        os.sytem("cls")
    else:
        os.system("clear")
    os.system("toilet -f future -F metal Playlist Download -t")
    print("-"*50)
    purl = input(colors.Blue+"Enter Playlist URL:"+colors.BGreen)
    try:
        playlist = pafy.get_playlist2(purl, basic=True)
        print("-"*50)
        print(playlist)
    except ValueError:
        print(colors.BRed+"enter a valid Playlist URL..")
        time.sleep(1)
        playlist_download()
    print("-"*50)
    print(colors.BGreen+"\n1)Download Best Video Quality")
    print(colors.BYellow+"2)Download Audio only (with best Quality)")
    print(colors.BBlue+"3)Make A file with all downloadable links")
    print(colors.BPurple+"4)Exit")
    choice = input(colors.Cyan+"\nenter choice:"+colors.BGreen)
    ret = check(choice, mode=2)
    userpath = input(colors.BPurple+"enter path to save the playlist:")
    correct_path = valid_path(userpath)
    os.chdir(correct_path)
    count = 0
    os.system("toilet -f mini -F gay DOWNLOADING!!")
    if ret != 3:
        for item in range(len(playlist)):
            count = count + 1
            if ret == 1:
                print(f"downloading VIDEO:{count}")
                url = playlist[item].getbest()
            if ret == 2:
                print(f"downloading audio in VIDEO:{count}")
                url = playlist[item].getbestaudio()
            url.download(userpath)
            # time.sleep(3)  # just to not make immediate download call
    else:
        file = open("links.txt", "w")
        for item in range(len(playlist)):
            count = count + 1
            print(f"adding links of VIDEO:{count}")
            link = playlist[item].getbest().url
            file.write("***********************************************************\n")
            file.write("link of Video:"+str(count))
            file.write("\n")
            file.write("***********************************************************\n")
            file.write("video Details:\n")
            file.write(str(playlist[item]))
            file.write("############################################################\n")
            file.write("\n")
            file.write(link)
            file.write("\n")
            file.write("\n############################################################")
        file.close()

    print("Downloads completed!!!!!")
    print(colors.BGreen+"Thank You for using the script :)")
    input(colors.Blue+"press any key to exit!"+colors.nocolor)
    exit()
Example #33
0
async def get_all_uploads(refetch_latest=5):
    def get_playlist_id_for_channel_id(channel_id: str) -> str:
        # in YouTube, taking a channel ID and changing the second letter from "C" to "U" gives you a playlist with all that channel's uploads
        return (f"{channel_id[:1]}U{channel_id[2:]}"
                if channel_id[1] == "C" else channel_id)

    def video_to_ordered_pairs(videos):
        return reversed([(video.videoid, video) for video in videos])

    def process_start_from(dict: OrderedDict, start_from: str):
        # dict is reversed
        if not start_from:
            index = 0
            logging.info(
                f"YouTube 'start from' setting not set. Checking the entire YouTube playlist."
            )
        elif start_from in dict:
            index = tuple(dict).index(start_from)
            logging.info(
                f"YouTube 'start from' is set to '{start_from}' and was found at index {index} (index 0 is the earliest video)."
            )
        else:
            raise Exception(f"Start from video '{start_from}' was not found!")

        items = list(dict.items())
        skipped, selected = items[:index], items[index:]
        logging.debug(f"Skip index set to '{index}'.")
        logging.debug(
            f"Skipping the following videos: {[id for id, _ in skipped]}.")
        logging.debug(
            f"Selecting the following videos: {[id for id, _ in selected]}.")
        for _, video in selected:
            yield video

    from app.config.youtube import (
        channel_id,
        start_from,
        youtube_num_iterations_until_refetch,
    )
    from app.config.pickle import playlist_history_pickle_path

    channel_id, pickle_path, num_iterations_until_refetch, start_from = await asyncio.gather(
        channel_id(),
        playlist_history_pickle_path(),
        youtube_num_iterations_until_refetch(),
        start_from(),
    )
    playlist_id = get_playlist_id_for_channel_id(channel_id)

    # get_playlist2 lazy loads the basic video information first and then gets pafy objects for each on iteration
    # this means that we can load the list and only add the set of videos we need to prevent spamming YouTube
    new_playlist = pafy.get_playlist2(playlist_id)
    logging.debug(
        f"Getting all YouTube videos for the playlist '{new_playlist.title}'.")

    # periodically refetch the entire playlist
    global upload_check_iteration
    iteration_count = upload_check_iteration.get(playlist_id, 0)
    logging.debug(
        f"Iteration count for playlist '{new_playlist.title}' is {iteration_count}"
    )
    if iteration_count % num_iterations_until_refetch == 0:
        logging.info(
            f"Refetching the YouTube playlist '{new_playlist.title}' due to iteration count."
        )
        upload_check_iteration[playlist_id] = iteration_count + 1
        for video in process_start_from(
                await
                save_pickle(pickle_path,
                            OrderedDict(video_to_ordered_pairs(new_playlist))),
                start_from,
        ):
            yield video

        return

    # videos are saved into the pickle file as an ordered dictionary in ascending chronological order (i.e. videos[0] will be the first video uploaded)
    old_playlist: OrderedDict = await load_pickle(
        pickle_path,
        lambda new_playlist=new_playlist: OrderedDict(
            video_to_ordered_pairs(new_playlist)),
    )
    saved_playlist = old_playlist

    new_count = len(new_playlist)
    old_count = len(old_playlist)
    logging.debug(
        f"Playlist '{new_playlist.title}' currently has {new_count} videos. Previously, it had {old_count} videos."
    )

    # if a video is removed, then the playlist's old_count will be more than the new_count
    if old_count > new_count:
        logging.debug(
            f"old_count > new_count ===> Deleted YouTube video detected for playlist '{new_playlist.title}'. Refetching the entire playlist."
        )

        # a video was deleted, so we completely refetch the playlist
        saved_playlist = OrderedDict(video_to_ordered_pairs(new_playlist))
    elif old_count == new_count:
        logging.debug(f"old_count == new_count")
        # if the counts are equal, we expect the latest 5 videos to be exactly the same
        old_videos = list(old_playlist.items())
        for i in range(0, min(refetch_latest, old_count, new_count)):
            old_id, old = old_videos[
                -(i + 1)]  # new_playlist has index -1 == latest video
            new = new_playlist[i]  # new_playlist has index 0 == latest video

            if old_id != new.videoid:
                logging.info(
                    f"Deleted video detected. The video at position '{i}' (where position 0 is the latest video) in the playlist was expected to be video '{old.title}' but was '{new.title}'. Refetching the entire playlist."
                )
                saved_playlist = OrderedDict(
                    video_to_ordered_pairs(new_playlist))
                break
    else:
        logging.debug(
            f"old_count < new_count ===> No deleted videos detected for the current iteration of the playlist '{new_playlist.title}'."
        )
        # we didn't detect a deleted video, so we get the latest videos only
        saved_playlist = OrderedDict(
            chain(
                old_playlist.items(),
                video_to_ordered_pairs(
                    islice(new_playlist, 0,
                           new_count - old_count + refetch_latest)),
            ))

    upload_check_iteration[playlist_id] = iteration_count + 1
    for video in process_start_from(
            await save_pickle(pickle_path, saved_playlist), start_from):
        yield video
Example #34
0
def download_playlist(url, download_path):
    playlist = []

    try:
        playlist1 = pafy.get_playlist2(url)
    except:
        print(
            "An exception occured while downloading the playlist. Error: Unable to fetch data from the error or the link is not valid."
        )
        exit()

    path = os.path.join(download_path, playlist1.title)
    # create dir
    try:
        os.mkdir(path)
    except:
        pass
    download_path = path

    for links in playlist1:
        y_url = links.watchv_url
        playlist.append(y_url)

    vquality = {
        'audio': '140',
        '144': '160',
        '240': '133',
        '360': '134',
        '480': '135',
        '720': '136',
        '1080': '137',
        '4k': '313'
    }
    playlist = sorted(set(playlist), key=playlist.index)
    tuple_format = vquality[qual]

    for cur_data in playlist:
        cur_url = cur_data
        fmt_name, fmt = qual, tuple_format
        try:
            download(
                cur_url,
                dict(format=fmt + '+140',
                     outtmpl=os.path.join(download_path,
                                          f'%(title)s-{fmt_name}.%(ext)s'),
                     cookiefile="cookies.txt",
                     nooverwrites=True,
                     source_address='0.0.0.0',
                     ignoreerrors=True,
                     retries=0
                     # quiet=True
                     ))
        except youtube_dl.utils.DownloadError:
            print(f'download error: {cur_url} | {fmt_name}')
            try:
                download(
                    cur_url,
                    dict(
                        format=
                        'bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio',
                        outtmpl=os.path.join(download_path,
                                             f'%(title)s-best.mp4'),
                        cookiefile="cookies.txt",
                        nooverwrites=True,
                        source_address='0.0.0.0',
                        ignoreerrors=True,
                        retries=0
                        # quiet=True
                    ))
            except:
                pass
Example #35
0
    oled_reset = digitalio.DigitalInOut(board.D4)
    PPbutton = Button(4)
    FFbutton = Button(14)
    Stopbutton = Button(15)
    # Change these
    # to the right size for your display!
    WIDTH = 128
    HEIGHT = 64

    # Use for I2C.
    i2c = board.I2C()
    oled = adafruit_ssd1306.SSD1306_I2C(WIDTH, HEIGHT, i2c, addr=0x3c, reset=oled_reset)
    oled.fill(0)
    oled.show()
    pafy.set_api_key(YOUTUBE_API)
    playlist = pafy.get_playlist2(PLAYLIST_URL)
    url_list=[]
    for i in playlist:
        pl_list=str(i).split()
        url_list.append(pl_list[2])
    print('Retrieved ' + str(len(url_list)) + ' songs from playlist')

    image = Image.new('1', (oled.width, oled.height))

    # Get drawing object to draw on image.
    draw = ImageDraw.Draw(image)

    # Load default font.
    font_l = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", FONT_SIZE_LARGE)
    font_s = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", FONT_SIZE_SMALL)
    font_m = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", FONT_SIZE_MEDIUM)