Exemplo n.º 1
0
def test_fetch_youtube_url(capsys):
    song_link = fetch_youtube_url(
        "Red Hot Chili Peppers - Dani California [Official Music Video]",
        "12354")
    assert song_link is None
    captured = capsys.readouterr()
    assert "keyInvalid" in captured.out
    song_link = fetch_youtube_url(
        "Red Hot Chili Peppers - Dani California [Official Music Video]",
        get_youtube_dev_key())
    assert song_link == 'https://www.youtube.com/watch?v=Sb5aq5HcS1A'
Exemplo n.º 2
0
def spotify_dl():
    """Main entry point of the script."""
    parser = argparse.ArgumentParser(prog='spotify_dl')
    parser.add_argument('-d',
                        '--download',
                        action='store_true',
                        help='Download using youtube-dl',
                        default=True)
    parser.add_argument('-p',
                        '--playlist',
                        action='store',
                        help='Download from playlist id instead of'
                        ' saved tracks')
    parser.add_argument('-V',
                        '--verbose',
                        action='store_true',
                        help='Show more information on what'
                        's happening.')
    parser.add_argument('-v',
                        '--version',
                        action='store_true',
                        help='Shows current version of the program')
    parser.add_argument('-o',
                        '--output',
                        type=str,
                        action='store',
                        help='Specify download directory.')
    parser.add_argument('-u',
                        '--user_id',
                        action='store',
                        help='Specify the playlist owner\'s userid when it'
                        ' is different than your spotify userid')
    parser.add_argument('-i',
                        '--uri',
                        type=str,
                        action='store',
                        nargs='*',
                        help='Given a URI, download it.')
    parser.add_argument('-f',
                        '--format_str',
                        type=str,
                        action='store',
                        help='Specify youtube-dl format string.',
                        default='bestaudio/best')
    parser.add_argument('-m',
                        '--skip_mp3',
                        action='store_true',
                        help='Don\'t convert downloaded songs to mp3')
    parser.add_argument('-l',
                        '--url',
                        action="store",
                        help="Spotify Playlist link URL")
    parser.add_argument('-s',
                        '--scrape',
                        action="store",
                        help="Use HTML Scraper for YouTube Search",
                        default=True)

    args = parser.parse_args()

    playlist_url_pattern = re.compile(r'^https://open.spotify.com/(.+)$')

    if args.version:
        print("spotify_dl v{}".format(VERSION))
        exit(0)

    db.connect()
    db.create_tables([Song])
    if os.path.isfile(os.path.expanduser('~/.spotify_dl_settings')):
        with open(os.path.expanduser('~/.spotify_dl_settings')) as file:
            config = json.loads(file.read())

        for key, value in config.items():
            if value and (value.lower() == 'true' or value.lower() == 't'):
                setattr(args, key, True)
            else:
                setattr(args, key, value)

    if args.verbose:
        log.setLevel(DEBUG)

    log.info('Starting spotify_dl')
    log.debug('Setting debug mode on spotify_dl')

    if not check_for_tokens():
        exit(1)

    token = authenticate()
    sp = spotipy.Spotify(auth=token)
    log.debug('Arguments: {}'.format(args))

    if args.url:
        url_match = playlist_url_pattern.match(args.url)
        if url_match and len(url_match.groups()) > 0:
            uri = "spotify:" + url_match.groups()[0].replace('/', ':')
            args.uri = [uri]
        else:
            raise Exception('Invalid playlist URL ')
    if args.uri:
        current_user_id, playlist_id = extract_user_and_playlist_from_uri(
            args.uri[0], sp)
    else:
        if args.user_id is None:
            current_user_id = sp.current_user()['id']
        else:
            current_user_id = args.user_id

    if args.output:
        if args.uri:
            uri = args.uri[0]
            playlist = playlist_name(uri, sp)
        else:
            playlist = get_playlist_name_from_id(args.playlist,
                                                 current_user_id, sp)

        log.info("Saving songs to: {}".format(playlist))
        download_directory = args.output + '/' + playlist
        if len(download_directory) >= 0 and download_directory[-1] != '/':
            download_directory += '/'

        if not os.path.exists(download_directory):
            os.makedirs(download_directory)
    else:
        download_directory = ''

    if args.uri:
        songs = fetch_tracks(sp, playlist_id, current_user_id)
    else:
        songs = fetch_tracks(sp, args.playlist, current_user_id)
    url = []
    for song, artist in songs.items():
        link = fetch_youtube_url(song + ' - ' + artist, get_youtube_dev_key())
        if link:
            url.append((link, song, artist))

    save_songs_to_file(url, download_directory)
    if args.download is True:
        download_songs(url, download_directory, args.format_str, args.skip_mp3)
Exemplo n.º 3
0
def test_fetch_youtube_url(capsys):
    song_link = fetch_youtube_url(
        "Red Hot Chili Peppers - Dani California [Official Music Video]",
        get_youtube_dev_key())
    assert song_link == 'https://www.youtube.com/watch?v=Sb5aq5HcS1A'
Exemplo n.º 4
0
def spotify_dl():
    """Main entry point of the script."""
    parser = argparse.ArgumentParser(prog='spotify_dl')
    parser.add_argument('-l', '--url', action="store",
                        help="Spotify Playlist link URL", type=str, required=True)
    parser.add_argument('-o', '--output', type=str, action='store',
                        help='Specify download directory.', required=True)
    parser.add_argument('-d', '--download', action='store_true',
                        help='Download using youtube-dl', default=True)
    parser.add_argument('-f', '--format_str', type=str, action='store',
                        help='Specify youtube-dl format string.',
                        default='bestaudio/best')
    parser.add_argument('-m', '--skip_mp3', action='store_true',
                        help='Don\'t convert downloaded songs to mp3')
    parser.add_argument('-s', '--scrape', action="store",
                        help="Use HTML Scraper for YouTube Search", default=True)
    parser.add_argument('-V', '--verbose', action='store_true',
                        help='Show more information on what''s happening.')
    parser.add_argument('-v', '--version', action='store_true',
                        help='Shows current version of the program')
    args = parser.parse_args()

    if args.version:
        print("spotify_dl v{}".format(VERSION))
        exit(0)

    db.connect()
    db.create_tables([Song])
    if os.path.isfile(os.path.expanduser('~/.spotify_dl_settings')):
        with open(os.path.expanduser('~/.spotify_dl_settings')) as file:
            config = json.loads(file.read())

        for key, value in config.items():
            if value and (value.lower() == 'true' or value.lower() == 't'):
                setattr(args, key, True)
            else:
                setattr(args, key, value)

    if args.verbose:
        log.setLevel(DEBUG)

    log.info('Starting spotify_dl')
    log.debug('Setting debug mode on spotify_dl')

    if not check_for_tokens():
        exit(1)

    sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials())
    log.debug('Arguments: {}'.format(args))

    if args.url:
        valid_item = validate_spotify_url(args.url)

    if not valid_item:
        sys.exit(1)

    if args.output:
        item_type, item_id = parse_spotify_url(args.url)
        directory_name = get_item_name(sp, item_type, item_id)
        path = Path(PurePath.joinpath(Path(args.output), Path(directory_name)))
        path.mkdir(parents=True, exist_ok=True)
        log.info("Saving songs to: {}".format(directory_name))

    songs = fetch_tracks(sp, item_type, args.url)
    url = []
    for song, artist in songs.items():
        link = fetch_youtube_url(song + ' - ' + artist, get_youtube_dev_key())
        if link:
            url.append((link, song, artist))

    if args.download is True:
        download_songs(url, str(path), args.format_str, args.skip_mp3)