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

rgaudin's avatar
rgaudin committed
4
import os
5
6
import tempfile

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

9
10
from backend.download import download_file

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

19
20
21
22
23
24
25
26
27
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:
rgaudin's avatar
rgaudin committed
28
29
30
            tmpfile = tempfile.NamedTemporaryFile(suffix=".yml", delete=False)
            dlf = download_file(catalog.get("url"), tmpfile.name, logger)
            tmpfile.seek(0)  # reset as we'll read it right away
31
            if dlf.successful:
rgaudin's avatar
rgaudin committed
32
33
34
                catalogs.append(yaml.load(tmpfile.read()))
                tmpfile.close()
                os.unlink(tmpfile.name)
35
36
37
38
39
40
41
42
43
44
45
46
47
48
            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