[SCM] mpd-sima/master: Imported Upstream version 0.12.1

kaliko-guest at users.alioth.debian.org kaliko-guest at users.alioth.debian.org
Sun Sep 28 11:34:27 UTC 2014


The following commit has been merged in the master branch:
commit 89e471581670227bde8b73308e6874ed9fc09c3a
Author: Geoffroy Youri Berret <efrim at azylum.org>
Date:   Sat Jun 21 14:23:24 2014 +0200

    Imported Upstream version 0.12.1

diff --git a/INSTALL b/INSTALL
index 337766e..c622d77 100644
--- a/INSTALL
+++ b/INSTALL
@@ -1,3 +1,12 @@
+Design for python >= 3.3
+
+Requires: python-musicpd >= 0.4.0 [0],
+          requests >= 2.2.0 [1]
+
+	[0] http://media.kaliko.me/src/musicpd/
+	[1] http://docs.python-requests.org/
+
+
 Virtualenv installation:
 
 Run ./vinstall.sh to generate the python virtualenv and install requirements.
diff --git a/README b/README
index 00360ca..2ee0a5b 100644
--- a/README
+++ b/README
@@ -1,9 +1,9 @@
-Design for python >= 3.3
-
-Requires: python-musicpd >= 0.4.0 [0],
-          requests >= 2.2.0 [1]
-
-	[0] http://media.kaliko.me/src/musicpd/
-	[1] http://docs.python-requests.org/
+MPD_sima Automagically add titles to MPD playlist.
 
+MPD_Sima is a Python script meant to feed your MPD's queue with tracks from
+artists similar to your currently playing track, provided that these artists
+are found in MPD library. Similar artists are fetched from last.fm.  MPD_sima
+can queue track, top track or whole album for similar artists.
 
+This client allows you to never run out of music when your playlist queue is
+getting short.
diff --git a/data/man/Makefile b/data/man/Makefile
index 67fb872..32a68b7 100644
--- a/data/man/Makefile
+++ b/data/man/Makefile
@@ -29,10 +29,10 @@ mpd_sima_html:
 	xmllint --xinclude --nowarning --noent mpd_sima.1.xml | $(XP) $(HXSL) - > ./mpd_sima.1.html
 
 simadb_cli_html:
-	$(XP) $(HXSL) simadb_cli.1.xml > ./simadb_cli.1.html
+	xmllint --xinclude --nowarning --noent simadb_cli.1.xml | $(XP) $(HXSL) - > ./simadb_cli.1.html
 
 mpd_sima.cfg_html:
-	$(XP) $(HXSL) mpd_sima.cfg.5.xml > ./mpd_sima.cfg.5.html
+	xmllint --xinclude --nowarning --noent mpd_sima.cfg.5.xml | $(XP) $(HXSL) - > ./mpd_sima.cfg.5.html
 
 man: simadb_cli mpd_sima mpd_sima.cfg
 
diff --git a/data/man/info.xml b/data/man/info.xml
index d0933fa..96bffe2 100644
--- a/data/man/info.xml
+++ b/data/man/info.xml
@@ -5,7 +5,7 @@
   <!ENTITY dhemail     "kaliko at azylum.org">
   <!ENTITY dhusername  "&dhfirstname; &dhsurname;">
   <!ENTITY dhpackage "mpd-sima">
-  <!ENTITY release   "0.12.0">
+  <!ENTITY release   "0.12.1">
   <!-- TITLE should be something like "User commands" or similar (see
        http://www.tldp.org/HOWTO/Man-Page/q2.html). -->
   <!ENTITY dhtitle     "&dhpackage; &release; User Manual">
diff --git a/data/man/mpd-sima.1 b/data/man/mpd-sima.1
index 04434f7..b7c6aac 100644
--- a/data/man/mpd-sima.1
+++ b/data/man/mpd-sima.1
@@ -2,12 +2,12 @@
 .\"     Title: mpd-sima
 .\"    Author: Jack Kaliko <kaliko at azylum.org>
 .\" Generator: DocBook XSL Stylesheets v1.78.1 <http://docbook.sf.net/>
-.\"      Date: 06/12/2014
-.\"    Manual: mpd-sima 0.12.0 User Manual
+.\"      Date: 06/21/2014
+.\"    Manual: mpd-sima 0.12.1 User Manual
 .\"    Source: mpd-sima
 .\"  Language: English
 .\"
-.TH "MPD\-SIMA" "1" "06/12/2014" "mpd-sima" "mpd-sima 0.12.0 User Manual"
+.TH "MPD\-SIMA" "1" "06/21/2014" "mpd-sima" "mpd-sima 0.12.1 User Manual"
 .\" -----------------------------------------------------------------
 .\" * Define some portability stuff
 .\" -----------------------------------------------------------------
diff --git a/data/man/mpd_sima.cfg.5 b/data/man/mpd_sima.cfg.5
index 49a9408..785d356 100644
--- a/data/man/mpd_sima.cfg.5
+++ b/data/man/mpd_sima.cfg.5
@@ -2,12 +2,12 @@
 .\"     Title: mpd_sima.cfg
 .\"    Author: Jack Kaliko <kaliko at azylum.org>
 .\" Generator: DocBook XSL Stylesheets v1.78.1 <http://docbook.sf.net/>
-.\"      Date: 06/16/2014
-.\"    Manual: mpd-sima 0.12.0 User Manual
+.\"      Date: 06/21/2014
+.\"    Manual: mpd-sima 0.12.1 User Manual
 .\"    Source: mpd-sima
 .\"  Language: English
 .\"
-.TH "MPD_SIMA\&.CFG" "5" "06/16/2014" "mpd-sima" "mpd-sima 0.12.0 User Manual"
+.TH "MPD_SIMA\&.CFG" "5" "06/21/2014" "mpd-sima" "mpd-sima 0.12.1 User Manual"
 .\" -----------------------------------------------------------------
 .\" * Define some portability stuff
 .\" -----------------------------------------------------------------
diff --git a/data/man/simadb_cli.1 b/data/man/simadb_cli.1
index 3667de4..93250b1 100644
--- a/data/man/simadb_cli.1
+++ b/data/man/simadb_cli.1
@@ -2,12 +2,12 @@
 .\"     Title: simadb_cli
 .\"    Author: Jack Kaliko <kaliko at azylum.org>
 .\" Generator: DocBook XSL Stylesheets v1.78.1 <http://docbook.sf.net/>
-.\"      Date: 06/12/2014
-.\"    Manual: mpd-sima 0.12.0 User Manual
+.\"      Date: 06/21/2014
+.\"    Manual: mpd-sima 0.12.1 User Manual
 .\"    Source: mpd-sima
 .\"  Language: English
 .\"
-.TH "SIMADB_CLI" "1" "06/12/2014" "mpd-sima" "mpd-sima 0.12.0 User Manual"
+.TH "SIMADB_CLI" "1" "06/21/2014" "mpd-sima" "mpd-sima 0.12.1 User Manual"
 .\" -----------------------------------------------------------------
 .\" * Define some portability stuff
 .\" -----------------------------------------------------------------
diff --git a/doc/Changelog b/doc/Changelog
index f9d4feb..199d707 100644
--- a/doc/Changelog
+++ b/doc/Changelog
@@ -1,4 +1,13 @@
-sima v0.12.0
+MPD_sima v0.12.1
+
+ * Fixed SIGHUP error, need python-musicpd >= 0.4.1
+ * Add core plugin to detect multiple MPD_sima instance on the same MPD host
+ * Fixed startup robustness
+ * Removed timestamp in console logging
+
+-- kaliko jack <kaliko at azylum.org>  Sat, 21 Jun 2014 14:02:17 +0200
+
+MPD_sima v0.12.0
 
  * Major refactoring
  * Add a setup.py, got rid of the Makefile.
@@ -14,14 +23,14 @@ sima v0.12.0
 -- kaliko jack <kaliko at azylum.org> Mon, 16 Jun 2014 10:37:14 +0200
 
 
-sima v0.11.0
+MPD_sima v0.11.0
 
  * straight forward py3k conversion from v0.10.0
 
 -- kaliko jack <kaliko at azylum.org> UNRELEASED
 
 
-sima v0.10.0
+MPD_sima v0.10.0
 
  * Improved album detection (especially multi-artists album)
  * Controls conf file is readable at startup
@@ -30,21 +39,21 @@ sima v0.10.0
 -- kaliko jack <kaliko at azylum.org>  Wed, 26 Sep 2012 18:56:57 +0200
 
 
-sima v0.9.2
+MPD_sima v0.9.2
 
  * Fixed Makefile, thanks Artur Frysiak (fixes #2849 #2848)
 
 -- kaliko jack <kaliko at azylum.org>  Sun, 26 Feb 2012 22:06:27 +0100
 
 
-sima v0.9.1
+MPD_sima v0.9.1
 
  * Fixed an issue in idle implementation
 
 -- kaliko jack <kaliko at azylum.org>  Fri, 24 Feb 2012 12:04:39 +0100
 
 
-sima v0.9.0
+MPD_sima v0.9.0
 
  * New CLI option --create-db
  * Option main_loop_time removed, use of idle makes it useless
@@ -67,7 +76,7 @@ sima v0.9.0
 -- kaliko jack <kaliko at azylum.org>  Fri, 10 Feb 2012 11:31:57 +0100
 
 
-sima v0.8.0
+MPD_sima v0.8.0
 
  * New CLI option "--daemon" to run as a daemon
 
@@ -83,14 +92,14 @@ sima v0.8.0
 -- kaliko jack <kaliko at azylum.org>  Sun, 08 May 2011 14:06:22 +0200
 
 
-sima v0.7.2
+MPD_sima v0.7.2
 
   * Fixes a bug introduced fixing #2113, history was no longer honored!
 
 -- kaliko jack <kaliko at azylum.org>  Sun, 30 Jan 2011 10:54:53 +0100
 
 
-sima v0.7.1
+MPD_sima v0.7.1
 
  * Add Makefile from 0.8 dev branch
  * Fixes #2113
@@ -99,7 +108,7 @@ sima v0.7.1
 -- kaliko jack <kaliko at azylum.org>  Sat, 22 Jan 2011 09:17:18 +0100
 
 
-sima v0.7.0
+MPD_sima v0.7.0
 
  * Stall queueing when MPD is in "single" or "repeat" mode (closes #1607)
  * No longer need to restart MPD_sima when MPD database has been updated, it
@@ -133,7 +142,7 @@ sima v0.7.0
 -- kaliko jack <kaliko at azylum.org>  Sat, 18 Dec 2010 12:11:12 +0100
 
 
-sima v0.6.0
+MPD_sima v0.6.0
 
  * Use of SQLite (closes #838)
  * [simadb_cli] new command line interface to edit sima.db (SQLite database)
@@ -150,7 +159,7 @@ sima v0.6.0
 -- kaliko jack <kaliko at azylum.org>  Mon, 10 May 2010 19:40:10 +0200
 
 
-sima v0.5.2
+MPD_sima v0.5.2
 
  * New fuzzy string matching dedicated to artist names (closes #686)
  * uses optparse instead of getopt (closes #834)
@@ -163,7 +172,7 @@ sima v0.5.2
 -- kaliko jack <kaliko at azylum.org>  Tue, 16 Mar 2010 14:01:22 +0100
 
 
-sima v0.5.1
+MPD_sima v0.5.1
 
  * No longer uses/writes a default conf file in ~/.config/mpd_sima (or XDG
    default), MPD_HOST is used if no conf file is present.
@@ -173,7 +182,7 @@ sima v0.5.1
 -- kaliko jack <kaliko at azylum.org>  Thu, 26 Nov 2009 10:13:08 +0100
 
 
-sima v0.5.0
+MPD_sima v0.5.0
 
  * Add option to play only most popular songs from an artist (closes #739).
  * Now prefer non played over already played artist is possible (closes #774)
@@ -188,7 +197,7 @@ sima v0.5.0
 -- kaliko jack <kaliko at azylum.org>  Sun, 25 Oct 2009 12:02:02 +0100
 
 
-sima v0.4.0
+MPD_sima v0.4.0
 
  * Add option to play only most popular songs from an artist
  * Better list of similar artists thanks to %-age of similarity… hopefully
@@ -197,7 +206,7 @@ sima v0.4.0
 -- kaliko jack Unreleased / abandoned dev branch
 
 
-sima v0.3.0
+MPD_sima v0.3.0
 
  * New bash wrapper launch.sh to execute the script
  * User's database for similar artists through a new conf file user_db_cfg.
@@ -213,7 +222,7 @@ sima v0.3.0
 -- kaliko jack <kaliko at azylum.org>  Tue, 28 Jul 2009 18:10:09 +0200
 
 
-sima v0.2.0
+MPD_sima v0.2.0
 
  * WARNING: Moved to python-mpd instead of python-mpdclient2
  * Add cache for last.fm request
@@ -227,7 +236,7 @@ sima v0.2.0
 -- kaliko jack <kaliko at azylum.org>  Fri, 12 Jun 2009 18:10:47 +0200
 
 
-sima v0.1.1 (first upgrade)
+MPD_sima v0.1.1 (first upgrade)
 
   * HEAVY refactoring to improve coding style (thanks pylint).
   * intercept audioScrobbler server connexion errors (no longer stops
@@ -242,7 +251,7 @@ sima v0.1.1 (first upgrade)
 -- kaliko jack <kaliko at azylum.org>  Thu, 04 Jun 2009 20:35:25 +0200
 
 
-sima v0.1.0 (first stable release)
+MPD_sima v0.1.0 (first stable release)
 
   * First quasi stable release (my first python code…)
 
diff --git a/setup.py b/setup.py
index 5f51853..036f85e 100755
--- a/setup.py
+++ b/setup.py
@@ -28,7 +28,7 @@ classifiers = [
         "Programming Language :: Python :: 3",
         ]
 
-setup(name='sima',
+setup(name='MPD_sima',
       version=VERSION,
       download_url='http://kaliko.me/media/src/sima/releases/',
       url='http://kaliko.me/code/mpd-sima',
@@ -39,7 +39,7 @@ setup(name='sima',
       keywords='MPD',
       long_description=DESCRIPTION,
       classifiers=classifiers,
-      install_requires=['python-musicpd', 'requests'],
+      install_requires=['python-musicpd>=0.4.1', 'requests>= 2.0.2'],
       packages=find_packages(exclude=["tests"]),
       include_package_data=True,
       data_files=data_files,
diff --git a/sima/client.py b/sima/client.py
index c04b259..9eae523 100644
--- a/sima/client.py
+++ b/sima/client.py
@@ -96,7 +96,7 @@ class PlayerClient(Player):
     TODO: handle exception in command not going through _client_wrapper() (ie.
           remove…)
     """
-    database = None  # sima database (history, blaclist)
+    database = None  # sima database (history, blacklist)
 
     def __init__(self, host="localhost", port="6600", password=None):
         super().__init__()
@@ -288,9 +288,9 @@ class PlayerClient(Player):
     def monitor(self):
         curr = self.current
         try:
-            self._client.send_idle('database', 'playlist', 'player', 'options')
+            self.send_idle('database', 'playlist', 'player', 'options')
             select([self._client], [], [], 60)
-            ret = self._client.fetch_idle()
+            ret = self.fetch_idle()
             if self.__skipped_track(curr):
                 ret.append('skipped')
             if 'database' in ret:
@@ -299,8 +299,16 @@ class PlayerClient(Player):
         except (MPDError, IOError) as err:
             raise PlayerError("Couldn't init idle: %s" % err)
 
+    def clean(self):
+        """Clean blocking event (idle) and pending commands
+        """
+        if 'idle' in self._client._pending:
+            self._client.noidle()
+        elif self._client._pending:
+            self.log.warning('pending commands: {}'.format(self._client._pending))
+
     def remove(self, position=0):
-        self._client.delete(position)
+        self.delete(position)
 
     def add(self, track):
         """Overriding MPD's add method to accept add signature with a Track
@@ -313,7 +321,7 @@ class PlayerClient(Player):
 
     @property
     def state(self):
-        return str(self._client.status().get('state'))
+        return str(self.status().get('state'))
 
     @property
     def current(self):
diff --git a/sima/core.py b/sima/core.py
index 634db4b..3532c88 100644
--- a/sima/core.py
+++ b/sima/core.py
@@ -45,10 +45,6 @@ class Sima(Daemon):
         self.log = getLogger('sima')
         self.plugins = list()
         self.player = self.__get_player()  # Player client
-        try:
-            self.player.connect()
-        except (PlayerError, PlayerUnHandledError) as err:
-            self.log.warning('Player: {}'.format(err))
         self.short_history = deque(maxlen=60)
 
     def __get_player(self):
@@ -63,7 +59,7 @@ class Sima(Daemon):
         self.short_history.appendleft(self.player.current)
 
     def register_plugin(self, plugin_class):
-        """Registers plubin in Sima instance..."""
+        """Registers plugin in Sima instance..."""
         self.plugins.append(plugin_class(self))
 
     def foreach_plugin(self, method, *args, **kwds):
@@ -112,26 +108,32 @@ class Sima(Daemon):
             time.sleep(tmp)
             try:
                 self.player.connect()
-            except PlayerError:
+            except PlayerError as err:
+                self.log.debug(err)
                 continue
             except PlayerUnHandledError as err:
                 #TODO: unhandled Player exceptions
                 self.log.warning('Unhandled player exception: %s' % err)
             self.log.info('Got reconnected')
             break
+        self.foreach_plugin('start')
 
     def hup_handler(self, signum, frame):
         self.log.warning('Caught a sighup!')
-        self.player.disconnect()
+        # Cleaning pending command
+        self.player.clean()
         self.foreach_plugin('shutdown')
+        self.player.disconnect()
         raise SigHup('SIGHUP caught!')
 
     def shutdown(self):
         """General shutdown method
         """
         self.log.warning('Starting shutdown.')
-        self.player.disconnect()
+        # Cleaning pending command
+        self.player.clean()
         self.foreach_plugin('shutdown')
+        self.player.disconnect()
 
         self.log.info('The way is shut, it was made by those who are dead. '
                       'And the dead keep it…')
@@ -140,6 +142,13 @@ class Sima(Daemon):
     def run(self):
         """
         """
+        try:
+            self.log.info('Connecting MPD: {0}:{1}'.format(*self.player._mpd))
+            self.player.connect()
+        except (PlayerError, PlayerUnHandledError) as err:
+            self.log.warning('Player: {}'.format(err))
+            self.reconnect_player()
+        self.foreach_plugin('start')
         while 42:
             try:
                 self.loop()
diff --git a/sima/info.py b/sima/info.py
index 60d1139..c416735 100644
--- a/sima/info.py
+++ b/sima/info.py
@@ -1,17 +1,17 @@
 # -*- coding: utf-8 -*-
 """
-sima is a Python application meant to feed your MPD playlist with tracks
+MPD_sima is a Python application meant to feed your MPD playlist with tracks
 from artists similar to your currently playing track, provided that these
 artists are found in MPD library. Similar artists are fetched from last.fm.
 
-sima can queue track, top track or whole album for similar artists.
+MPD_sima can queue track, top track or whole album for similar artists.
 
 This client allows you to never run out of music when your playlist
 queue is getting short.
 """
 
 
-__version__ = '0.12.0'
+__version__ = '0.12.1'
 __author__ = 'kaliko jack'
 __email__ = 'kaliko at azylum.org'
 __url__ = 'git://git.kaliko.me/sima.git'
diff --git a/sima/launch.py b/sima/launch.py
index 733d237..03baa4f 100644
--- a/sima/launch.py
+++ b/sima/launch.py
@@ -41,6 +41,7 @@ from .utils.utils import exception_log, SigHup
  # core plugins
 from .plugins.core.history import History
 from .plugins.core.mpdoptions import MpdOptions
+from .plugins.core.uniq import Uniq
 ##
 
 
@@ -102,14 +103,17 @@ def start(sopt, restart=False):
     sima = core.Sima(config)
 
     # required core plugins
-    sima.register_plugin(History)
-    sima.register_plugin(MpdOptions)
+    core_plugins = [History, MpdOptions, Uniq]
+    for cplgn in core_plugins:
+        logger.debug('Register core {name} ({doc})'.format(**cplgn.info()))
+        sima.register_plugin(cplgn)
 
     #  Loading internal plugins
     load_plugins(sima, 'internal')
 
     #  Loading contrib plugins
     load_plugins(sima, 'contrib')
+
     # Run as a daemon
     if config.getboolean('daemon', 'daemon'):
         if restart:
diff --git a/sima/lib/logger.py b/sima/lib/logger.py
index 05f9c35..b27d4f0 100644
--- a/sima/lib/logger.py
+++ b/sima/lib/logger.py
@@ -28,8 +28,8 @@ import sys
 
 
 LOG_FORMATS = {
-        logging.DEBUG: '{asctime} {filename: >11}:{lineno: <3} {levelname: <7}: {message}',
-        logging.INFO:  '{asctime} {levelname: <7}: {message}',
+        logging.DEBUG: '[{process}]{filename: >11}:{lineno: <3} {levelname: <7}: {message}',
+        logging.INFO:  '{levelname: <7}: {message}',
         #logging.DEBUG: '{asctime} {filename}:{lineno}({funcName}) '
                                  #'{levelname}: {message}',
         }
@@ -78,6 +78,9 @@ def set_logger(level='info', logfile=None):
     if logfile:
         if filehdl:
             logg.handlers = []
+        # Add timestamp for file handler
+        log_format = '{0} {1}'.format('{asctime}', log_format)
+        formatter = logging.Formatter(log_format, DATE_FMT, '{')
         # create file handler
         fileh = logging.FileHandler(logfile)
         #fileh.setLevel(user_log_level)
diff --git a/sima/lib/player.py b/sima/lib/player.py
index 6b6d2cb..37b3c72 100644
--- a/sima/lib/player.py
+++ b/sima/lib/player.py
@@ -57,6 +57,10 @@ class Player(object):
         """
         raise NotImplementedError
 
+    def clean(self):
+        """Any cleanup necessary"""
+        pass
+
     def remove(self, position=0):
         """Removes the oldest element of the playlist (index 0)
         """
diff --git a/sima/lib/plugin.py b/sima/lib/plugin.py
index 5f70942..0523a75 100644
--- a/sima/lib/plugin.py
+++ b/sima/lib/plugin.py
@@ -26,8 +26,8 @@ class Plugin:
     First non-empty line of the docstring is used as description
     Rest of the docstring at your convenience.
 
-    The plugin Name MUST be the same as the module (file name), case
-    insensitive: for instance plugin.py → Plugin
+    The lowercased plugin Name MUST be the same as the module (file name),
+    for instance Plugin → plugin.py
     It eases plugins discovery and simplifies the code to handle them,
     IMHO, it's a fair trade-off.
     """
@@ -64,6 +64,13 @@ class Plugin:
         #    self.log.debug('Got config for {0}: {1}'.format(self,
         #                                                    self.plugin_conf))
 
+    def start(self):
+        """
+        Called when the daemon().run() is called and
+        right after the player has connected successfully.
+        """
+        pass
+
     def callback_player(self):
         """
         Called on player changes, stopped, paused, skipped
diff --git a/sima/lib/webserv.py b/sima/lib/webserv.py
index fd15815..5e78785 100644
--- a/sima/lib/webserv.py
+++ b/sima/lib/webserv.py
@@ -195,6 +195,8 @@ class WebService(Plugin):
         history = deque(self.history)
         history.popleft()
         depth = 0
+        if not self.player.playlist:
+            return ret_extra
         last_trk = self.player.playlist[-1]
         extra_arts = list()
         while depth < self.plugin_conf.getint('depth'):
@@ -222,6 +224,8 @@ class WebService(Plugin):
     def get_local_similar_artists(self):
         """Check against local player for similar artists
         """
+        if not self.player.playlist:
+            return []
         tolookfor = self.player.playlist[-1].get_artist()
         self.log.info('Looking for artist similar '
                       'to "{0.artist}"'.format(self.player.playlist[-1]))
diff --git a/sima/plugins/core/uniq.py b/sima/plugins/core/uniq.py
new file mode 100644
index 0000000..b61afa6
--- /dev/null
+++ b/sima/plugins/core/uniq.py
@@ -0,0 +1,79 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) 2014 Jack Kaliko <kaliko at azylum.org>
+#
+#  This file is part of sima
+#
+#  sima is free software: you can redistribute it and/or modify
+#  it under the terms of the GNU General Public License as published by
+#  the Free Software Foundation, either version 3 of the License, or
+#  (at your option) any later version.
+#
+#  sima is distributed in the hope that it will be useful,
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#  GNU General Public License for more details.
+#
+#  You should have received a copy of the GNU General Public License
+#  along with sima.  If not, see <http://www.gnu.org/licenses/>.
+#
+#
+"""
+    Publish presence on the MPD host message bus
+
+    Notifies when concurrent instance run on the same host.
+"""
+
+# standard library import
+from os import  getpid
+from socket import getfqdn
+
+# third parties components
+
+# local import
+from ...lib.plugin import Plugin
+
+
+class Uniq(Plugin):
+    """
+    Publish presence on the MPD host message bus
+    """
+
+    def __init__(self, daemon):
+        Plugin.__init__(self, daemon)
+        self.chan = 'mpd_sima:{0}.{1}'.format(getfqdn(), getpid())
+        self.channels = []
+        self.uniq = True
+
+    def start(self):
+        if not self.is_capable():
+            self.log.warning('MPD does not provide client to client')
+            return
+        self.is_uniq()
+        self.sub_chan()
+
+    def is_capable(self):
+        if 'channels' in self.player.commands():
+            return True
+
+    def get_channels(self):
+        return [chan for chan in self.player.channels() if
+                chan.startswith('mpd_sima') and chan != self.chan]
+
+    def is_uniq(self):
+        channels = self.get_channels()
+        if channels:
+            self.log.warning('Another instance is queueing on this MPD host')
+            self.log.warning(' '.join(channels))
+            self.uniq = False
+
+    def sub_chan(self):
+        self.log.debug('Registering as {}'.format(self.chan))
+        self.player.subscribe(self.chan)
+
+    def callback_need_track(self):
+        if self.is_capable():
+            self.is_uniq()
+
+
+# VIM MODLINE
+# vim: ai ts=4 sw=4 sts=4 expandtab

-- 
mpd-sima packaging



More information about the pkg-multimedia-commits mailing list