]> kaliko git repositories - mpd-sima.git/blob - sima/launch.py
Cleanup PlayerError exception wrapper
[mpd-sima.git] / sima / launch.py
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2013, 2014, 2015, 2020-2022 kaliko <kaliko@azylum.org>
3 #
4 #  This file is part of sima
5 #
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.
10 #
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.
15 #
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/>.
18 #
19 #
20 """Sima
21 """
22
23 # standard library import
24 import logging
25 import sys
26
27 from importlib import __import__ as sima_import
28 from os.path import isfile
29 from os import rename
30 ##
31
32 # third parties components
33 ##
34
35 # local import
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
44 # core plugins
45 from .plugins.core.history import History
46 from .plugins.core.mpdoptions import MpdOptions
47 from .plugins.core.uniq import Uniq
48 ##
49
50
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):
57         return
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()}'
63         try:
64             mod_obj = sima_import(module, fromlist=[plugin])
65         except ImportError as err:
66             logger.error(f'Failed to load "{plugin}" plugin\'s module: ' +
67                          f'{module} ({err})')
68             sima.shutdown()
69             sys.exit(1)
70         try:
71             plugin_obj = getattr(mod_obj, plugin)
72         except AttributeError as err:
73             logger.error('Failed to load plugin %s (%s)', plugin, err)
74             sima.shutdown()
75             sys.exit(1)
76         logger.info('Loading {0} plugin: {name} ({doc})'.format(
77             source, **plugin_obj.info()))
78         sima.register_plugin(plugin_obj)
79
80
81 def start(sopt, restart=False):
82     """starts application
83     """
84     # loads configuration
85     cfg_mgmt = ConfMan(sopt.options)
86     config = cfg_mgmt.config
87     # set logger
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
92         set_logger(verbosity)
93     else:
94         set_logger(verbosity, logfile)
95     logger.debug('Command line say: %s', sopt.options)
96
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()
109
110     if sopt.options.get('command'):
111         cmd = sopt.options.get('command')
112         if cmd.startswith('bl-'):
113             BLCli(config, sopt.options)
114             sys.exit(0)
115         if cmd == "generate-config":
116             config.write(sys.stdout, space_around_delimiters=True)
117             sys.exit(0)
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
122             config_test(config)
123             sys.exit(0)
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()
128             else:
129                 logger.info('Database already there, not overwriting %s', db_file)
130             logger.info('Done, bye...')
131             sys.exit(0)
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)
136                 sys.exit(1)
137             SimaDB(db_path=db_file).purge_history(duration=0)
138             sys.exit(0)
139         if cmd == 'random':
140             config['sima']['internal'] = 'Crop, Random'
141             if sopt.options.get('nbtracks'):
142                 config['random']['track_to_add'] = str(sopt.options.get('nbtracks'))
143
144     logger.info('Starting (%s)...', info.__version__)
145     sima = core.Sima(config)
146
147     # required core plugins
148     core_plugins = [History, MpdOptions, Uniq]
149     if config.getboolean('sima', 'mopidy_compat'):
150         logger.warning('Running with mopidy compat. mode!')
151         core_plugins = [History, MpdOptions]
152         config['sima']['musicbrainzid'] = 'False'
153     for cplgn in core_plugins:
154         logger.debug('Register core %(name)s (%(doc)s)', cplgn.info())
155         sima.register_core_plugin(cplgn)
156     logger.debug('core loaded, prioriy: %s',
157                  ' > '.join(map(str, sima.core_plugins)))
158
159     #  Loading internal plugins
160     load_plugins(sima, 'internal')
161     #  Loading contrib plugins
162     load_plugins(sima, 'contrib')
163     logger.info('plugins loaded, prioriy: %s', ' > '.join(map(str, sima.plugins)))
164
165     # Run as a daemon
166     if config.getboolean('daemon', 'daemon'):
167         if restart:
168             sima.run()
169         else:
170             logger.info('Daemonize process...')
171             sima.start()
172
173     try:
174         sima.foreground()
175     except KeyboardInterrupt:
176         logger.info('Caught KeyboardInterrupt, stopping')
177         sys.exit(0)
178
179
180 def run(sopt, restart=False):
181     """
182     Handles SigHup exception
183     Catches Unhandled exception
184     """
185     # pylint: disable=broad-except
186     logger = logging.getLogger('sima')
187     try:
188         start(sopt, restart)
189     except SigHup:  # SigHup inherit from Exception
190         run(sopt, True)
191     except (MPDSimaException, PlayerError) as err:
192         logger.error(err)
193         sys.exit(2)
194     except Exception:  # Unhandled exception
195         exception_log()
196
197
198 # Script starts here
199 def main():
200     """Entry point"""
201     nfo = dict({'version': info.__version__,
202                 'prog': 'mpd-sima'})
203     # StartOpt gathers options from command line call (in StartOpt().options)
204     sopt = StartOpt(nfo)
205     run(sopt)
206
207
208 if __name__ == '__main__':
209     main()
210
211 # VIM MODLINE
212 # vim: ai ts=4 sw=4 sts=4 expandtab