]> kaliko git repositories - mpd-goodies.git/commitdiff
* rewrote mtopls
authorkaliko <kaliko@azylum.org>
Sun, 13 Jun 2010 13:31:00 +0000 (13:31 +0000)
committerkaliko <kaliko@azylum.org>
Sun, 13 Jun 2010 13:31:00 +0000 (13:31 +0000)
 * crop : switch to arguments instead of options in CLI

crop
mfade
mtopls

diff --git a/crop b/crop
index 9a08eb1e0b2c743f9e784e1850a4b3e4330db5d5..2b255f18aa3f4095bf8c4888fe2d2c7fc726804e 100755 (executable)
--- a/crop
+++ b/crop
@@ -26,16 +26,7 @@ from lib.startop import StartOpt
 
 NAME = 'crop'
 VERSION = '0.1'
-
-CROP_OPTS = list([
-    {
-        'sw': ['-n', '--nbtracks'],
-        'type': 'int',
-        'dest': 'nb_tracks',
-        'default': 6,
-        'metavar': '<n>',
-        'help': 'keep <n> tracks before currently played.'},
-    ])
+USAGE = 'USAGE:  %prog [--help] | [ <n> ]'
 
 class Crop(StartOpt, MPDClass):
     """
@@ -43,24 +34,37 @@ class Crop(StartOpt, MPDClass):
     script_info = dict({
         'version': VERSION,
         'prog_name': NAME,
-        'description': 'Keep <n> tracks before currently played, removed others.',
+        'description': 'Keep <n> tracks before currently played, removed others. Default is to keep 6 tracks.',
+        'usage': USAGE,
         })
 
     def __init__(self):
         """"""
-        StartOpt.__init__(self, self.__class__.script_info, CROP_OPTS)
+        StartOpt.__init__(self, self.__class__.script_info, [])
         MPDClass.__init__(self)
+        self.nb_tracks = 6
+        self._get_arg()
         self._run()
 
+    def _get_arg(self):
+        """"""
+        if not self.cli_args:
+            return True
+        try:
+            self.nb_tracks = int(self.cli_args[0])
+        except ValueError, err:
+            self.parser.error('invalid argument, not a natural number? (%s)' % err)
+
     def _run(self):
         """"""
         print 'Connecting %s:%i' % (self.cli_options.host, self.cli_options.port)
+        print 'Keeping %i tracks' % self.nb_tracks
         self.mpdConnect()
         current_pos = int(self.client.currentsong().get('pos'))
-        if current_pos <=  self.cli_options.nb_tracks:
+        if current_pos <=  self.nb_tracks:
             self.client.disconnect()
             sys.exit(0)
-        while current_pos > self.cli_options.nb_tracks:
+        while current_pos > self.nb_tracks:
             self.client.delete(0)
             current_pos = int(self.client.currentsong().get('pos'))
         self.client.disconnect()
diff --git a/mfade b/mfade
index 6666c8d4ca03c9f37697d49ee4295b744f9303eb..de84f141dfc21be9cfc252af9bd885b179a2a0e8 100755 (executable)
--- a/mfade
+++ b/mfade
@@ -34,10 +34,10 @@ from lib.startop import StartOpt
 
 NAME = 'mfade'
 VERSION = '0.1'
-USAGE = 'USAGE:  %prog [--help] [options] [<time> [<final volume level>]'
-DESC = """Fade in/out to <final volume level> over <time>. From 0% to 50% when
-paused or stopped and from current volume to 10th of it if playing, both over 10
-minutes."""
+USAGE = 'USAGE:  %prog [--help] | [ <time> [<final volume level>] ]'
+DESC = """Fade in/out to <final volume level> over <time>. Defaults are from 0%
+to 50% when paused or stopped and from current volume to 10th of it if playing,
+both over 10 minutes."""
 
 
 class Sleep(StartOpt, MPDClass):
@@ -62,7 +62,7 @@ class Sleep(StartOpt, MPDClass):
         """"""
         if (len(self.cli_args) < 1 or
                 len(self.cli_args) > 2):
-            self.parser.error('%s requires at least an argument and no more than two!')
+            self.parser.error('need at least an argument and no more than two!')
         try:
             self.tempo = int(self.cli_args[0])
             self.volum = int(self.cli_args[1])
diff --git a/mtopls b/mtopls
index 78476c60b72b0bc18da9a44d63612b3f97eb143a..6d0c6ee7aff2d7b2267886af0b573ed35b79daaf 100755 (executable)
--- a/mtopls
+++ b/mtopls
 #
 #  }}}
 
-"""
-DOC:
-"""
 
 import sys
 
-from os import (access, F_OK, W_OK)
-from os.path import (dirname, isfile, join, abspath)
+from os import(access, W_OK)
+from os.path import (dirname, isfile, join, basename, abspath)
 
-from lib.mpdutils import (mconnect, collapse_tags)
+from lib.mpdclass import MPDClass
+from lib.startop import StartOpt
 
-USAGE = """Usage:
+NAME = 'mtopls'
+VERSION = '0.1'
+USAGE = 'USAGE:  %prog [--help] | /path/to/the/playlist/file/'
 
-mtopls [<path-to-playlist>] [--help | -h | help]
-
-    Add the current track to playlist.
-
-    The default playlist, if none specified, is named after the current track's
-    genre within /var/lib/mpd/playlists/ (creating it if not existing).
-
-    Obviously the script is meant to be executed on hosts where
-    /var/lib/mpd/playlists/ makes sense or where file entries in the playlist
-    make sense for you (cf. "man 5 mpd.conf" especially
-    save_absolute_paths_in_playlists option).
-
-"""
-
-class MtoPls(object):
+class MtoPls(StartOpt, MPDClass):
     """
     """
+    script_info = dict({
+        'version': VERSION,
+        'prog_name': NAME,
+        'description': 'Save currently played track into your playlists',
+        'usage': USAGE,
+        })
 
     def __init__(self):
         """"""
-        self.pls_path = None
-        self.cli = mconnect()
-        self.current = self.cli.currentsong()
-        self.cli.disconnect()
-        self._consume_sopt()
-        self._controls_perm()
-        self._create_playlist()
+        StartOpt.__init__(self, self.__class__.script_info, [])
+        MPDClass.__init__(self)
+        self.playlist = None
         self._run()
 
-    def _consume_sopt(self):
+    def _get_opt(self):
         """"""
-        if len(sys.argv) >= 2 and \
-                sys.argv[1] in ['-h', '--help', 'help']:
-            sys.stdout.write(USAGE)
-            sys.exit(1)
-        if len(sys.argv) == 2:
-            self.pls_path = sys.argv[1]
-            if not dirname(self.pls_path):
-                self.pls_path = abspath(sys.argv[1])
-            print >> sys.stdout, ('Playlist set to "%s"' % self.pls_path)
-            return
-        if len(sys.argv) == 1:
-            self._set_playlist()
+        if len(self.cli_args) != 1:
+            self.parser.error('need at least a playlist file name!')
+        self.playlist = self.cli_args[0]
+        if (isfile(self.playlist) and
+                access(self.playlist, W_OK)):
             return
-        sys.stdout.write(USAGE)
-        sys.exit(1)
-
-    def _set_playlist(self):
-        """Set playlist is none is given"""
+        if not access(dirname(self.playlist), W_OK):
+            self.parser.error('not writable: %s' % dirname(self.playlist))
 
-        mpd_playlists = '/var/lib/mpd/playlists/'
-        if not access(mpd_playlists, F_OK):
-            sys.stderr.write('Error: No access to "%s"' % self.pls_path)
-            sys.exit(1)
-        genre = collapse_tags(self.current.get('genre', None))
-        if not genre:
-            sys.stderr.write('Error: No genre set in %s\n' %
-                    self.current.get('file'))
-            print >> sys.stdout, ('Please provide a playlist.')
-            sys.exit(1)
-        genre += '.m3u'
-        self.pls_path = join('/var/lib/mpd/playlists/', genre)
+    def _check_dupes(self):
+        """Controls the file is not already in the playlist"""
+        fd = open(self.playlist)
+        lines = fd.readlines()
+        fd.close()
+        if self.current_song.get('file') + '\n' in lines:
+            print 'File already in the playlist.'
+            sys.exit(0)
 
-    def _create_playlist(self):
-        if not isfile(self.pls_path):
+    def _write(self):
+        """"""
+        if not isfile(self.playlist):
             # TODO: add M3U header
-            print >> sys.stdout, ('Create new playlist: %s' % self.pls_path)
-            open(self.pls_path, 'a').close()
-
-    def _controls_perm(self):
-        if not access(dirname(self.pls_path), F_OK):
-            sys.stderr.write('Error: Not existing path: "%s"' % self.pls_path)
-            sys.exit(1)
-        if not access(self.pls_path, W_OK):
-            sys.stderr.write('Error: No write access to path: "%s"' % self.pls_path)
-            sys.exit(1)
-        if not isfile(self.pls_path):
-            sys.stderr.write('Error: Not a regular file: "%s"' % self.pls_path)
-            sys.exit(1)
-        return True
+            print >> sys.stdout, ('Create new playlist: %s' % self.playlist)
+            open(self.playlist, 'a').close()
+        else:
+            self._check_dupes()
+        fd = open(self.playlist, 'a')
+        fd.write(self.current_song.get('file') + '\n')
+        fd.close()
 
     def _run(self):
         """"""
-        # TODO: controls either file is already in playlist or not
-        print >> sys.stdout, ('Writing to %s' % self.pls_path)
-        fd = open(self.pls_path, 'a')
-        fd.write(self.current.get('file') + '\n')
-        fd.close()
-        pass
+        print 'Connecting %s:%i' % (self.cli_options.host, self.cli_options.port)
+        self.mpdConnect()
+        self.current_song = self.client.currentsong()
+        self.client.disconnect()
+        self._get_opt()
+        print 'Will try to add "%s" to "%s"' % (
+                basename(self.current_song.get('file')),
+                self.playlist)
+        self._write()
+        print 'Done...'
+        sys.exit(0)
+
 
 # Script starts here
 if __name__ == '__main__':
-    MtoPls()
+    try:
+        MtoPls()
+    except KeyboardInterrupt:
+        sys.stdout.write('exit')
 
 # VIM MODLINE
 # vim: ai ts=4 sw=4 sts=4 expandtab