From b835454f116f3b0f1280222ecdd4a5f749747f7c Mon Sep 17 00:00:00 2001 From: localhost_frssoft Date: Sat, 17 Dec 2022 03:13:09 +0300 Subject: [PATCH] Add progress bar for download track --- src/fw_radios.py | 2 -- src/mpv_control.py | 2 -- src/utils.py | 21 ++++++++++++++++++--- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/fw_radios.py b/src/fw_radios.py index a6246ab..86c03d1 100644 --- a/src/fw_radios.py +++ b/src/fw_radios.py @@ -126,9 +126,7 @@ def radio_load(id_radio=None, type_radio='custom', name=None, related_object=Non else: player.pause = True elif select == 'Download': - print('Downloading...') name_downloaded = download_track(player.stream_open_filename) - print(f'Downloaded: {name_downloaded}') elif select == 'Info': track = player_fw_storage.storage.get(track_url_to_uuid()) for i in ('title', 'fid', 'license', 'album', 'artist'): diff --git a/src/mpv_control.py b/src/mpv_control.py index 0fe0026..f9ef576 100644 --- a/src/mpv_control.py +++ b/src/mpv_control.py @@ -78,9 +78,7 @@ def player_menu(header='', storage={}): else: player.pause = True elif select == 'Download': - print('Downloading...') name_downloaded = download_track(player.stream_open_filename) - print(f'Downloaded: {name_downloaded}') elif select == 'Info': track = player_fw_storage.storage.get(track_url_to_uuid()) for i in track.keys(): diff --git a/src/utils.py b/src/utils.py index e1a883b..c489864 100644 --- a/src/utils.py +++ b/src/utils.py @@ -1,4 +1,6 @@ import src.fw_api + +import sys from urllib.parse import unquote @@ -12,12 +14,25 @@ def get_remote_file_name(url): def download_track(url, name=None): url = url.split('?')[0] # Stripe all params from url - r = src.fw_api.current_instance.s.get(url) + r = src.fw_api.current_instance.s.get(url, stream=True) if not name: name = get_remote_file_name(url) if not name: name = url.split(r'/')[-1] - with open(name.replace(r'/', '_'), 'wb') as f: - f.write(r.content) + with open(name.replace('/', '_'), 'wb') as f: + print(f"Downloading {name}") + total_length = r.headers.get('content-length') + + if total_length is None: # no content length header + f.write(r.content) + else: + dl = 0 + total_length = int(total_length) + for data in r.iter_content(chunk_size=4096): + dl += len(data) + f.write(data) + done = int(50 * dl / total_length) + sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50-done)) ) # base progress bar + sys.stdout.flush() return name