import requests


def imslp_file_url_to_download_url(file_url):
    """Take a MediaWiki File: page (e.g. File:PMLP129863-HandAbO.zip)
    and use the mediawiki api to get the actual URL of the file"""

    params = {"action": "query",
              "prop": "imageinfo",
              "titles": file_url,
              "format": "json",
              "iiprop": "url"}
    url = 'https://imslp.org/api.php'

    r = requests.get(url, params=params)
    r.raise_for_status()
    try:
        j = r.json()
    except ValueError:
        return []

    pages = j['query']['pages']
    for k, v in pages.items():
        info = v.get('imageinfo')
        if info:
            if file_url in info[0]["descriptionurl"]:
                return "https:" + info[0]["url"]