73 lines
2.4 KiB
Python
73 lines
2.4 KiB
Python
import src.fw_api
|
|
|
|
import os
|
|
import sys
|
|
import shutil
|
|
from urllib.parse import unquote
|
|
|
|
|
|
def get_remote_file_name(url):
|
|
'''This function return filename by content-disposition header'''
|
|
r = src.fw_api.current_instance.s.head(url)
|
|
content_dispos = r.headers.get('content-disposition')
|
|
if content_dispos.startswith('attachment; filename*=UTF-8\'\''):
|
|
return unquote(content_dispos.split('attachment; filename*=UTF-8\'\'')[-1])
|
|
|
|
|
|
def download_track(url, name=None):
|
|
if not url.startswith('http'):
|
|
copy_from_cache(url)
|
|
return
|
|
|
|
url = url.split('?')[0] # Stripe all params from 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('/', '_'), '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)
|
|
# base progress bar
|
|
sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50-done)))
|
|
sys.stdout.flush()
|
|
return name
|
|
|
|
|
|
def copy_from_cache(url_file):
|
|
uuid = url_file.split(r'/')[-1]
|
|
original_name = get_remote_file_name(f'https://{src.fw_api.current_instance.instance}/api/v1/listen/{uuid}')
|
|
shutil.copyfile(url_file, original_name)
|
|
|
|
|
|
def print_there(x, y, text):
|
|
'''Print at position x, y caption in terminal (Linux only)'''
|
|
sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
|
|
sys.stdout.flush()
|
|
|
|
|
|
def track_info_output(track):
|
|
output = []
|
|
for k, v in track.items():
|
|
if k not in ('cover', 'uploads', 'listen_url', 'mbid', 'id', 'is_playable') and v is not None and v != []:
|
|
if isinstance(v, dict):
|
|
for i in ('title', 'name', 'fid'):
|
|
if v.get(i):
|
|
val_override = v.get(i)
|
|
output.append(f'{k}: {val_override}')
|
|
else:
|
|
output.append(f'{k}: {v}')
|
|
output = '\n'.join(output)
|
|
os.system(f'less <<EOF\n{output}\nEOF')
|