1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2013, 2014, 2015, 2020, 2021 kaliko <kaliko@azylum.org>
4 # This file is part of sima
6 # sima is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # sima is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with sima. If not, see <http://www.gnu.org/licenses/>.
23 # standard library import
27 from importlib import __import__ as sima_import
28 from os.path import isfile
32 # third parties components
36 from . import core, info
37 from .lib.logger import set_logger
38 from .lib.simadb import SimaDB
39 from .mpdclient import PlayerError
40 from .utils.config import ConfMan
41 from .utils.startopt import StartOpt
42 from .utils.utils import exception_log, SigHup, MPDSimaException
43 from .utils.blcli import BLCli
45 from .plugins.core.history import History
46 from .plugins.core.mpdoptions import MpdOptions
47 from .plugins.core.uniq import Uniq
51 def load_plugins(sima, source):
52 """Handles internal/external plugins
53 sima: sima.core.Sima instance
54 source: ['internal', 'contrib']
55 """# pylint: disable=logging-not-lazy,logging-format-interpolation
56 if not sima.config.get('sima', source):
58 logger = logging.getLogger('sima')
59 # TODO: Sanity check for "sima.config.get('sima', source)" ?
60 for plugin in sima.config.get('sima', source).split(','):
61 plugin = plugin.strip(' \n')
62 module = f'sima.plugins.{source}.{plugin.lower()}'
64 mod_obj = sima_import(module, fromlist=[plugin])
65 except ImportError as err:
66 logger.error(f'Failed to load "{plugin}" plugin\'s module: ' +
71 plugin_obj = getattr(mod_obj, plugin)
72 except AttributeError as err:
73 logger.error('Failed to load plugin %s (%s)', plugin, err)
76 logger.info('Loading {0} plugin: {name} ({doc})'.format(
77 source, **plugin_obj.info()))
78 sima.register_plugin(plugin_obj)
81 def start(sopt, restart=False):
85 cfg_mgmt = ConfMan(sopt.options)
86 config = cfg_mgmt.config
88 logger = logging.getLogger('sima')
89 logfile = config.get('log', 'logfile', fallback=None)
90 verbosity = config.get('log', 'verbosity')
91 if sopt.options.get('command'): # disable file logging
94 set_logger(verbosity, logfile)
95 logger.debug('Command line say: %s', sopt.options)
97 # Create database if not present
98 db_file = config.get('sima', 'db_file')
99 if not isfile(db_file):
100 logger.debug('Creating database in "%s"', db_file)
101 SimaDB(db_path=db_file).create_db()
102 # Migration from v0.17.0
103 dbinfo = SimaDB(db_path=db_file).get_info()
104 if not dbinfo: # v0.17.0 → v0.18+ migration
105 logger.warning('Backing up database!')
106 rename(db_file, db_file + '-old-version-backup')
107 logger.info('Creating an new database in "%s"', db_file)
108 SimaDB(db_path=db_file).create_db()
110 if sopt.options.get('command'):
111 cmd = sopt.options.get('command')
112 if cmd.startswith('bl-'):
113 BLCli(config, sopt.options)
115 if cmd == "generate-config":
116 config.write(sys.stdout, space_around_delimiters=True)
118 logger.info('Running "%s" and exit', cmd)
119 if cmd == "config-test":
120 logger.info('Config location: "%s"', cfg_mgmt.conf_file)
121 from .utils.configtest import config_test
124 if cmd == "create-db":
125 if not isfile(db_file):
126 logger.info('Creating database in "%s"', db_file)
127 SimaDB(db_path=db_file).create_db()
129 logger.info('Database already there, not overwriting %s', db_file)
130 logger.info('Done, bye...')
132 if cmd == "purge-history":
133 db_file = config.get('sima', 'db_file')
134 if not isfile(db_file):
135 logger.warning('No db found: %s', db_file)
137 SimaDB(db_path=db_file).purge_history(duration=0)
140 logger.info('Starting (%s)...', info.__version__)
141 sima = core.Sima(config)
143 # required core plugins
144 core_plugins = [History, MpdOptions, Uniq]
145 if config.getboolean('sima', 'mopidy_compat'):
146 logger.warning('Running with mopidy compat. mode!')
147 core_plugins = [History, MpdOptions]
148 config['sima']['musicbrainzid'] = 'False'
149 for cplgn in core_plugins:
150 logger.debug('Register core %(name)s (%(doc)s)', cplgn.info())
151 sima.register_core_plugin(cplgn)
152 logger.debug('core loaded, prioriy: %s',
153 ' > '.join(map(str, sima.core_plugins)))
155 # Loading internal plugins
156 load_plugins(sima, 'internal')
157 # Loading contrib plugins
158 load_plugins(sima, 'contrib')
159 logger.info('plugins loaded, prioriy: %s', ' > '.join(map(str, sima.plugins)))
162 if config.getboolean('daemon', 'daemon'):
166 logger.info('Daemonize process...')
171 except KeyboardInterrupt:
172 logger.info('Caught KeyboardInterrupt, stopping')
176 def run(sopt, restart=False):
178 Handles SigHup exception
179 Catches Unhandled exception
181 # pylint: disable=broad-except
182 logger = logging.getLogger('sima')
185 except SigHup: # SigHup inherit from Exception
187 except (MPDSimaException, PlayerError) as err:
190 except Exception: # Unhandled exception
197 nfo = dict({'version': info.__version__,
199 # StartOpt gathers options from command line call (in StartOpt().options)
204 if __name__ == '__main__':
208 # vim: ai ts=4 sw=4 sts=4 expandtab