]> kaliko git repositories - mpd-sima.git/blob - sima/plugins/internal/tags.py
Ensure metadata used in filter are available (closes #38)
[mpd-sima.git] / sima / plugins / internal / tags.py
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2020 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 """
21 Add titles based on tags
22 """
23
24 # standard library import
25 import random
26
27 # third parties components
28 from musicpd import CommandError
29
30 # local import
31 from ...lib.plugin import Plugin
32 from ...lib.track import Track
33 from ...utils.utils import PluginException
34
35
36 def forge_filter(cfg):
37     tags = set(cfg.keys()) & Tags.supported_tags
38     cfg_filter = cfg.get('filter', None)
39     mpd_filter = []
40     if cfg_filter:
41         mpd_filter.append(cfg_filter)
42     for tag in tags:
43         if not cfg[tag]:  # avoid empty tags entries in config
44             continue
45         if ',' in cfg[tag]:
46             patt = '|'.join(map(str.strip, cfg[tag].split(',')))
47             mpd_filter.append(f"({tag} =~ '({patt})')")
48         else:
49             mpd_filter.append(f"({tag} == '{cfg[tag].strip()}')")
50     mpd_filter = ' AND '.join(mpd_filter)
51     if 'AND' in mpd_filter:
52         mpd_filter = f'({mpd_filter})'
53     return mpd_filter
54
55
56 class Tags(Plugin):
57     """Add track based on tags content
58     """
59     supported_tags = {'comment', 'date', 'genre', 'label', 'originaldate'}
60
61     def __init__(self, daemon):
62         super().__init__(daemon)
63         self.daemon = daemon
64         self._control_conf()
65         self.mpd_filter = forge_filter(self.plugin_conf)
66         self._setup_tagsneeded()
67         self.log.debug('mpd filter: %s', self.mpd_filter)
68
69     def _control_conf(self):
70         sup_tags = Tags.supported_tags
71         config_tags = {k for k, v in self.plugin_conf.items()
72                        if (v and k not in ['filter', 'priority', 'track_to_add'])}
73         if not self.plugin_conf.get('filter', None) and \
74                 config_tags.isdisjoint(sup_tags):
75             self.log.error('Found no config for %s plugin! '
76                            'Need at least "filter" or a supported tag', self)
77             self.log.info('Supported Tags are : %s', ', '.join(sup_tags))
78             raise PluginException('plugin misconfiguration')
79         if config_tags.difference(sup_tags):
80             self.log.error('Found unsupported tag in config: %s',
81                            config_tags.difference(sup_tags))
82             raise PluginException('plugin misconfiguration')
83
84     def _setup_tagsneeded(self):
85         """Ensure needed tags are exposed by MPD"""
86         # At this point mpd_filter concatenetes {tags}+filter
87         config_tags = set()
88         for mpd_supp_tags in self.player.MPD_supported_tags:
89             if mpd_supp_tags.lower() in self.mpd_filter.lower():
90                 config_tags.add(mpd_supp_tags.lower())
91         self.log.debug('%s plugin needs the following metadata: %s',
92                        self, config_tags)
93         tags = config_tags & Tags.supported_tags
94         self.player.needed_tags |= tags
95
96     def _get_history(self):
97         """Constructs list of already played artists.
98         """
99         duration = self.daemon.config.getint('sima', 'history_duration')
100         tracks_from_db = self.daemon.sdb.get_history(duration=duration)
101         hist = [Track(file=tr[3], artist=tr[0]) for tr in tracks_from_db]
102         return hist
103
104     def start(self):
105         if (0, 21, 0) > tuple(map(int, self.player.mpd_version.split('.'))):
106             self.log.warning('MPD protocol version: %s < 0.21.0',
107                              self.player.mpd_version)
108             self.log.error(
109                 'Need at least MPD 0.21 to use Tags plugin (filters required)')
110             self.player.disconnect()
111             raise PluginException('MPD >= 0.21 required')
112         # Check filter is valid
113         try:
114             if self.plugin_conf['filter']:
115                 self.player.find(self.plugin_conf['filter'])
116         except CommandError:
117             raise PluginException('Badly formated filter in tags plugin configuration: "%s"'
118                                   % self.plugin_conf['filter'])
119
120     def callback_need_track(self):
121         candidates = []
122         target = self.plugin_conf.getint('track_to_add')
123         tracks = self.player.find(self.mpd_filter)
124         random.shuffle(tracks)
125         history = self._get_history()
126         while tracks:
127             trk = tracks.pop()
128             if trk in self.player.queue or \
129                trk in candidates:
130                 self.log.debug('%s already queued', trk)
131                 continue
132             if trk in history:
133                 self.log.debug('%s in history', trk)
134                 continue
135             candidates.append(trk)
136             self.log.info('Tags candidate: {}'.format(trk))
137             if len(candidates) >= target:
138                 break
139         if not candidates:
140             self.log.info('Tags plugin failed to find some tracks')
141         return candidates
142
143 # VIM MODLINE
144 # vim: ai ts=4 sw=4 sts=4 expandtab