catalog.py 1.28 KB
Newer Older
1
2
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
3

4
5
import tempfile

thiolliere's avatar
thiolliere committed
6
import yaml
thiolliere's avatar
thiolliere committed
7

8
9
from backend.download import download_file

rgaudin's avatar
rgaudin committed
10
CATALOGS = [
11
12
13
14
    {
        "name": "Kiwix",
        "description": "Kiwix ZIM Content",
        "url": "http://download.kiwix.org/library/ideascube.yml",
15
    }
16
17
]

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
YAML_CATALOGS = None


def fetch_catalogs(logger):
    """ build a dict of loaded (yaml) catalogs from CATALOGS """
    catalogs = []
    logger.std("downloading catalogs...")
    try:
        for catalog in CATALOGS:
            fpath = tempfile.NamedTemporaryFile(suffix=".yml")
            dlf = download_file(catalog.get("url"), fpath.name, logger)
            fpath.seek(0)  # reset as we'll read it right away
            if dlf.successful:
                catalogs.append(yaml.load(fpath.read()))
                fpath.close()
            else:
                raise ValueError("Unable to download {}".format(catalog.get("url")))
    except Exception as exp:
        logger.err("Exception while downloading/parsing catalogs: {}".format(exp))
        return None
    return catalogs if len(catalogs) else None


def get_catalogs(logger):
    """ cached-shortcut to YAML_CATALOGS """
    global YAML_CATALOGS
    if YAML_CATALOGS is None:
        YAML_CATALOGS = fetch_catalogs(logger)
    return YAML_CATALOGS