Exemplo n.º 1
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.º 2
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(
        '-k',
        '--keep_playlist_order',
        type=bool,
        default=False,
        action=argparse.BooleanOptionalAction,
        help='Whether to keep original playlist ordering or not.')
    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')
    parser.add_argument('-c',
                        '--createdir',
                        action='store_true',
                        help='Create a subdirectory')
    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))

    # TODO: make the logic less dumb
    if args.url:
        valid_item = validate_spotify_url(args.url)
        valid_yt = validate_youtube_url(args.url)

    if valid_item:
        download_spotify(sp, args)
    elif valid_yt:
        download_youtube(sp, args)
    exit(1)
Exemplo n.º 3
0
from spotify_dl.cache import check_if_in_cache, save_to_cache
from spotify_dl.models import db, Song

search_term_wrong = 'bleh'
search_term = "Red Hot Chili Peppers - Dani California [Official Music Video]"

video_id = "Sb5aq5HcS1A"
db.connect()
db.create_tables([Song])


def test_check_for_cache_miss():
    exists, song_info = check_if_in_cache(search_term=search_term_wrong)
    assert exists is False
    assert song_info is None


def test_check_for_cache_hit():
    _ = save_to_cache(search_term=search_term, video_id='Sb5aq5HcS1A')
    exists, cache_video_id = check_if_in_cache(search_term=search_term)
    assert exists is True
    assert cache_video_id == video_id
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(
        '-k',
        '--keep_playlist_order',
        default=False,
        action='store_true',
        help='Whether to keep original playlist ordering or not.')
    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)
        save_path = Path(
            PurePath.joinpath(Path(args.output), Path(directory_name)))
        save_path.mkdir(parents=True, exist_ok=True)
        log.info("Saving songs to: {}".format(directory_name))

    songs = fetch_tracks(sp, item_type, args.url)
    if args.download is True:
        file_name_f = default_filename
        if args.keep_playlist_order:
            file_name_f = playlist_num_filename

        download_songs(songs, save_path, args.format_str, args.skip_mp3,
                       args.keep_playlist_order, file_name_f)