aboutsummaryrefslogtreecommitdiffstats
path: root/youtube_podcaster/config.py
blob: bfce9022a98edfa66a4ab30cbe3b647529cb1aee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import sys
import os
import json


class ConfigException(Exception):
    def __init__(self, msg):
        super(ConfigException, self).__init__("Config exception: %s" % (msg))


class Config:
    instance = None

    def parse_config(config_file=None):
        if not Config.instance:
            Config.instance = Config(config_file)

        return Config.instance

    def __init__(self, args):
        if args.config:
            config = args.config
        else:
            config_file = "youtube-podcaster.json"

            if sys.platform == "linux" and not hasattr(sys, "real_prefix"):
                config = "/etc/%s" % (config_file)
            else:
                config = "%s/etc/%s" % (sys.prefix, config_file)

        if not os.path.isfile(config):
            raise ConfigException("%s not found" % (config))

        try:
            config = json.load(open(config))
        except json.decoder.JSONDecodeError as e:
            raise ConfigException("%s is not valid json: %s" % (
                                  config, str(e)))

        try:
            self.server = config["server"]
            self.youtube = config["youtube"]
            self.podcasts = config["podcasts"]
        except KeyError as e:
            raise ConfigException("Missing %s-section in %s" % (
                                  str(e), config))

        for arg, value in vars(args).items():
            if not value:
                continue

            if arg == "interface":
                self.server["interface"] = value
            elif arg == "port":
                self.server["port"] = value
            elif arg == "apikey":
                self.youtube["api-key"] = value

    def get_server_address(self):
        interface = str(self.server["interface"])
        port = int(self.server["port"])
        return interface, port

#  vim: set ts=8 sw=4 tw=0 et :