Downloads a track

def download_track(track, playlist_name=None, playlist_file=None):
    """
    Downloads a track
    """
    global arguments

    title = track['title']
    title = title.encode('utf-8', 'ignore').decode('utf8')
    logger.info('Downloading {0}'.format(title))

    # Not streamable
    if not track['streamable']:
        logger.error('{0} is not streamable...'.format(title))
        return

    r = None
    # Downloadable track
    if track['downloadable'] and not arguments['--onlymp3']:
        logger.info('Downloading the original file.')
        original_url = track['download_url']
        r = requests.get(
            original_url, params={'client_id': CLIENT_ID}, stream=True
        )
        if r.status_code == 401:
            logger.info('The original file has no download left.')
            filename = get_filename(track)
        else:
            d = r.headers.get('content-disposition')
            filename = re.findall("filename=(.+)", d)[0][1:-1]
            filename = get_filename(track, filename)

    else:
        filename = get_filename(track)
    logger.debug("filename : {0}".format(filename))

    # Skip if file ID or filename already exists
    if already_downloaded(track, title, filename):
        return

    # Add the track to the generated m3u playlist file
    if playlist_file:
        duration = math.floor(track['duration'] / 1000)
        playlist_file.write(
            '#EXTINF:{0},{1}{3}{2}{3}'.format(
                duration, title, filename, os.linesep
            )
        )

    if arguments['--remove']:
        fileToKeep.append(filename)

    # Streamable track download
    if r is None or r.status_code == 401:
        url = track['stream_url']
        r = requests.get(url, params={'client_id': CLIENT_ID}, stream=True)
        logger.debug(r.url)
        if r.status_code == 401 or r.status_code == 429:
            r = requests.get(
                url, params={'client_id': ALT_CLIENT_ID}, stream=True
            )
            logger.debug(r.url)
            r.raise_for_status()
    temp = tempfile.NamedTemporaryFile(delete=False)

    total_length = int(r.headers.get('content-length'))

    min_size = arguments.get('--min-size')
    max_size = arguments.get('--max-size')

    if min_size is not None and total_length < min_size:
        logging.info('{0} not large enough, skipping'.format(title))
        return

    if max_size is not None and total_length > max_size:
        logging.info('{0} too large, skipping'.format(title))
        return

    received=0
    with temp as f:
        for chunk in progress.bar(
            r.iter_content(chunk_size=1024),
            expected_size=(total_length/1024) + 1,
            hide=True if arguments["--hide-progress"] else False
        ):
            if chunk:
                received+=len(chunk)
                f.write(chunk)
                f.flush()

    if received != total_length:
        logger.error('connection closed prematurely, download incomplete')
        sys.exit()

    shutil.move(temp.name, os.path.join(os.getcwd(), filename))
    if arguments['--flac'] and can_convert(filename):
        logger.info('Converting to .flac...')
        newfilename = filename[:-4] + ".flac"
        new = shlex.quote(newfilename)
        old = shlex.quote(filename)
        logger.debug("ffmpeg -i {0} {1} -loglevel fatal".format(old, new))
        os.system("ffmpeg -i {0} {1} -loglevel fatal".format(old, new))
        os.remove(filename)
        filename = newfilename

    if filename.endswith('.mp3') or filename.endswith('.flac'):
        try:
            set_metadata(track, filename, playlist_name)
        except Exception as e:
            logger.error('Error trying to set the tags...')
            logger.debug(e)
    else:
        logger.error("This type of audio doesn't support tagging...")

    # Try to change the real creation date
    created_at = track['created_at']
    timestamp = datetime.strptime(created_at, '%Y/%m/%d %H:%M:%S %z')
    filetime = int(time.mktime(timestamp.timetuple()))
    try_utime(filename, filetime)

    logger.info('{0} Downloaded.\n'.format(filename))
    record_download_archive(track)