From 8f36a9ab2d5da11c355da2467cb7c5ddbcc9068d Mon Sep 17 00:00:00 2001 From: Thomas Lau Date: Thu, 28 Oct 2021 09:01:40 +0000 Subject: [PATCH] fix windows invalid folder name --- zspotify/album.py | 6 ++++-- zspotify/utils.py | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/zspotify/album.py b/zspotify/album.py index 2070da24..8a38b6e5 100644 --- a/zspotify/album.py +++ b/zspotify/album.py @@ -2,7 +2,7 @@ from tqdm import tqdm from const import ITEMS, ARTISTS, NAME, ID from track import download_track -from utils import sanitize_data +from utils import sanitize_data, fix_filename from zspotify import ZSpotify ALBUM_URL = 'https://api.spotify.com/v1/albums' @@ -47,9 +47,11 @@ def get_artist_albums(artist_id): def download_album(album): """ Downloads songs from an album """ artist, album_name = get_album_name(album) + artist_fixed = fix_filename(artist) + album_name_fixed = fix_filename(album_name) tracks = get_album_tracks(album) for n, track in tqdm(enumerate(tracks, start=1), unit_scale=True, unit='Song', total=len(tracks)): - download_track(track[ID], f'{artist}/{album_name}', + download_track(track[ID], f'{artist_fixed}/{album_name_fixed}', prefix=True, prefix_value=str(n), disable_progressbar=True) diff --git a/zspotify/utils.py b/zspotify/utils.py index b8188d95..f6c95840 100644 --- a/zspotify/utils.py +++ b/zspotify/utils.py @@ -179,3 +179,22 @@ def regex_input_for_urls(search_input) -> Tuple[str, str, str, str, str, str]: artist_id_str = None return track_id_str, album_id_str, playlist_id_str, episode_id_str, show_id_str, artist_id_str + + +def fix_filename(name): + """ + Replace invalid characters on Linux/Windows/MacOS with underscores. + List from https://stackoverflow.com/a/31976060/819417 + Trailing spaces & periods are ignored on Windows. + >>> fix_filename(" COM1 ") + '_ COM1 _' + >>> fix_filename("COM10") + 'COM10' + >>> fix_filename("COM1,") + 'COM1,' + >>> fix_filename("COM1.txt") + '_.txt' + >>> all('_' == fix_filename(chr(i)) for i in list(range(32))) + True + """ + return re.sub(r'[/\\:|<>"?*\0-\x1f]|^(AUX|COM[1-9]|CON|LPT[1-9]|NUL|PRN)(?![^.])|^\s|[\s.]$', "_", name, flags=re.IGNORECASE)