]> kaliko git repositories - mpd-sima.git/blob - launch
typo and less verbose logging
[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                  'prog': 'sima'})
71     # StartOpt gathers options from command line call (in StartOpt().options)
72     sopt = StartOpt(info)
73     # set logger
74     verbosity = sopt.options.get('verbosity', 'warning')
75     logfile = sopt.options.get('logfile', None)
76     cli_loglevel = getattr(logging, verbosity.upper())
77     set_logger(level=verbosity, logfile=logfile)
78     logger = logging.getLogger('sima')
79     logger.setLevel(cli_loglevel)
80     # loads configuration
81     config = ConfMan(logger, sopt.options).config
82     logger.setLevel(getattr(logging,
83                     config.get('log', 'verbosity').upper()))  # pylint: disable=E1103
84
85     logger.debug('Command line say: {0}'.format(sopt.options))
86     # Create Database
87     db_file = config.get('sima', 'db_file')
88     if (sopt.options.get('create_db', None)
89        or not isfile(db_file)):
90         logger.info('Creating database in "{}"'.format(db_file))
91         open(db_file, 'a').close()
92         SimaDB(db_path=db_file).create_db()
93         if sopt.options.get('create_db', None):
94             logger.info('Done, bye...')
95             sys.exit(0)
96
97     logger.info('Starting...')
98     sima = core.Sima(config)
99
100     #  Loading internal plugins
101     for plugin in PLUGINS:
102         logger.info('Loading internal plugin: {name} ({doc})'.format(**plugin.info()))
103         sima.register_plugin(plugin)
104
105     #  Loading contrib plugins
106     load_contrib_plugins(sima)
107
108     # Run as a daemon
109     if config.getboolean('daemon', 'daemon'):
110         sima.start()
111
112     try:
113         sima.foreground()
114     except KeyboardInterrupt:
115         logger.info('Caught KeyboardInterrupt, stopping')
116         #sima.shutdown()
117
118
119 def run():
120     """Catching broad exception
121     """
122     # pylint: disable=broad-except
123     try:
124         main()
125     except Exception:
126         exception_log()
127
128 # Script starts here
129 if __name__ == '__main__':
130     run()
131
132 # VIM MODLINE
133 # vim: ai ts=4 sw=4 sts=4 expandtab