import os
import re
import tempfile

import requests


def get_vk_audio(url):
    if 'm3u8' in url:
        url = re.sub(r'/[0-9a-f]+(/audios)?/([0-9a-f]+)/index.m3u8', r'\1/\2.mp3', url)
    return get_file(url)


def get_vk_photo(attachment):
    for size in (2560, 1280, 807, 604, 130, 75):
        if f'photo_{size}' in attachment:
            return attachment[f'photo_{size}']
    return None


def get_file(url):
    fname = '?'.join(url.split('?')[:-1])
    extension = os.path.basename(fname).split('.')[-1]
    f = tempfile.NamedTemporaryFile(suffix=f'.{extension}' if extension else None)
    r = requests.get(url, stream=True)
    for chunk in r.iter_content(1024 * 1024):
        if chunk:
            f.write(chunk)
    f.seek(0)
    return f
