]> kaliko git repositories - mpd-sima.git/blob - launch
Simplified configuration manager (db_file's no longer a special case)
[mpd-sima.git] / launch
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 """Sima
4 """
5
6 # standart library import
7 import logging
8 import sys
9
10 from importlib import __import__
11 from os.path import isfile
12 ##
13
14 # third parties components
15 ##
16
17 # local import
18 from sima import core
19 from sima.lib.logger import set_logger
20 from sima.lib.simadb import SimaDB
21 from sima.utils.config import ConfMan
22 from sima.utils.startopt import StartOpt
23 from sima.utils.utils import exception_log
24 ##
25 # internal plugins
26 from sima.plugins.crop import Crop
27 from sima.plugins.addhist import History
28 from sima.plugins.lastfm import Lastfm
29 from sima.plugins.mpd import MpdOptions
30 from sima.plugins.randomfallback import RandomFallBack
31
32 # official plugins to start
33 PLUGINS = (Crop, History, MpdOptions,
34            Lastfm, RandomFallBack)
35
36
37 def load_contrib_plugins(sima):
38     """Handles contrib/external plugins
39     """
40     if not sima.config.has_option('sima', 'plugins'):
41         return
42     logger = logging.getLogger('sima')
43     for plugin in sima.config.get('sima','plugins').split(','):
44         plugin = plugin.strip(' \n')
45         module = 'sima.plugins.contrib.{}'.format(plugin.lower())
46         try:
47             mod_obj = __import__(module, fromlist=[plugin])
48         except ImportError as err:
49             logger.error('Failed to load plugin\'s module: {0} ({1})'.format(module, err))
50             sima.shutdown()
51         try:
52             plugin_obj = getattr(mod_obj, plugin)
53         except AttributeError as err:
54             logger.error('Failed to load plugin {0} ({1})'.format(plugin, err))
55             sima.shutdown()
56         logger.info('Loading contrib plugin: {name} ({doc})'.format(**plugin_obj.info()))
57         sima.register_plugin(plugin_obj)
58
59
60 def load_internal_plugins(sima):
61     """Handles contrib/external plugins
62     """
63     raise NotImplementedError
64
65
66 def main():
67     """Entry point, deal w/ CLI and starts application
68     """
69     info = dict({'version': core.__version__,})
70     # StartOpt gathers options from command line call (in StartOpt().options)
71     sopt = StartOpt(info)
72     # set logger
73     verbosity = sopt.options.get('verbosity', 'warning')
74     cli_loglevel = getattr(logging, verbosity.upper())
75     set_logger(level=verbosity)
76     logger = logging.getLogger('sima')
77     logger.setLevel(cli_loglevel)
78     # loads configuration
79     config = ConfMan(logger, sopt.options).config
80     logger.setLevel(getattr(logging,
81                     config.get('log', 'verbosity').upper()))  # pylint: disable=E1103
82
83     logger.debug('Command line say: {0}'.format(sopt.options))
84     # Create Database
85     db_file = config.get('sima', 'db_file')
86     if (sopt.options.get('create_db', None)
87        or not isfile(db_file)):
88         logger.info('Creating database in "{}"'.format(db_file))
89         open(db_file, 'a').close()
90         SimaDB(db_path=db_file).create_db()
91         if sopt.options.get('create_db', None):
92             logger.info('Done, bye...')
93             sys.exit(0)
94
95     logger.info('Starting...')
96     sima = core.Sima(config)
97
98     #  Loading internal plugins
99     for plugin in PLUGINS:
100         logger.info('Loading internal plugin: {name} ({doc})'.format(**plugin.info()))
101         sima.register_plugin(plugin)
102
103     #  Loading contrib plugins
104     load_contrib_plugins(sima)
105     try:
106         sima.run()
107     except KeyboardInterrupt:
108         logger.info('Caught KeyboardInterrupt, stopping')
109         sima.shutdown()
110
111
112 # Script starts here
113 if __name__ == '__main__':
114     # pylint: disable=broad-except
115     try:
116         main()
117     except Exception:
118         exception_log()
119
120
121 # VIM MODLINE
122 # vim: ai ts=4 sw=4 sts=4 expandtab