コード例 #1
0
 def commands(self):
     """Add the last-import command."""
     last_import = Subcommand(
         'last-import', help=u'print the most recently imported items.')
     last_import.parser.add_all_common_options()
     last_import.func = self.last_import
     return [last_import]
コード例 #2
0
    def commands(self):
        def print_unimported(lib, opts, args):
            ignore_exts = [
                ('.' + x).encode()
                for x in self.config["ignore_extensions"].as_str_seq()
            ]
            ignore_dirs = [
                os.path.join(lib.directory, x.encode())
                for x in self.config["ignore_subdirectories"].as_str_seq()
            ]
            in_folder = {
                os.path.join(r, file)
                for r, d, f in os.walk(lib.directory) for file in f
                if not any([file.endswith(ext)
                            for ext in ignore_exts] + [r in ignore_dirs])
            }
            in_library = {x.path for x in lib.items()}
            art_files = {x.artpath for x in lib.albums()}
            for f in in_folder - in_library - art_files:
                print_(util.displayable_path(f))

        unimported = Subcommand(
            'unimported',
            help='list all files in the library folder which are not listed'
            ' in the beets library database')
        unimported.func = print_unimported
        return [unimported]
コード例 #3
0
    def commands(self):
        """Add subcommand used to run the AURA server."""
        def run_aura(lib, opts, args):
            """Run the application using Flask's built in-server.

            Args:
                lib: A beets Library object (not used).
                opts: Command line options. An optparse.Values object.
                args: The list of arguments to process (not used).
            """
            app = create_app()
            # Start the built-in server (not intended for production)
            app.run(
                host=self.config["host"].get(str),
                port=self.config["port"].get(int),
                debug=opts.debug,
                threaded=True,
            )

        run_aura_cmd = Subcommand("aura", help="run an AURA server")
        run_aura_cmd.parser.add_option(
            "-d",
            "--debug",
            action="store_true",
            default=False,
            help="use Flask debug mode",
        )
        run_aura_cmd.func = run_aura
        return [run_aura_cmd]
コード例 #4
0
ファイル: __init__.py プロジェクト: Lugoues/beets-lyrics
    def commands(self):
        lyrics_cmd = Subcommand('lyrics', help='fetch lyrics')
        lyrics_cmd.func = self.lyrics_func
        lyrics_cmd.parser.add_option('-f', '--force', action='store_true', default=None, help='overwrite tag updates')
        lyrics_cmd.parser.add_option('-p', '--processes', dest='processes', help='number of concurrent threads to run')

        return [lyrics_cmd]
コード例 #5
0
ファイル: normalizecontainers.py プロジェクト: cravxx/stuff
 def commands(self):
     normalize = Subcommand(
         'normalize',
         help='normalizes the tag containers to ID3v2.4 and ID3v1.0')
     normalize.parser.add_all_common_options()
     normalize.func = self.do_normalize
     return [normalize]
コード例 #6
0
ファイル: play.py プロジェクト: Brainversation/beets
 def commands(self):
     play_command = Subcommand("play", help="send music to a player as a playlist")
     play_command.parser.add_option(
         "-a", "--album", action="store_true", default=False, help="query and load albums rather than tracks"
     )
     play_command.func = play_music
     return [play_command]
コード例 #7
0
ファイル: play.py プロジェクト: 15502119602/beets
 def commands(self):
     play_command = Subcommand(
         'play',
         help='send music to a player as a playlist'
     )
     play_command.parser.add_album_option()
     play_command.func = self.play_music
     return [play_command]
コード例 #8
0
 def commands(self):
     play_command = Subcommand('play',
         help='send query results to music player as playlist.')
     play_command.parser.add_option('-a', '--album',
         action='store_true', default=False,
         help='query and load albums(folders) rather then tracks.')
     play_command.func = play_music
     return [play_command]
コード例 #9
0
ファイル: badfiles.py プロジェクト: adamjakab/Beets
 def commands(self):
     bad_command = Subcommand('bad',
                              help='check for corrupt or missing files')
     bad_command.parser.add_option(
         '-v', '--verbose',
         action='store_true', default=False, dest='verbose',
         help='view results for both the bad and uncorrupted files'
     )
     bad_command.func = self.command
     return [bad_command]
コード例 #10
0
ファイル: mbcollection.py プロジェクト: bheadwhite/beets
 def commands(self):
     mbupdate = Subcommand('mbupdate',
                           help=u'Update MusicBrainz collection')
     mbupdate.parser.add_option('-r', '--remove',
                                action='store_true',
                                default=None,
                                dest='remove',
                                help='Remove albums not in beets library')
     mbupdate.func = self.update_collection
     return [mbupdate]
コード例 #11
0
ファイル: badfiles.py プロジェクト: beetbox/beets
 def commands(self):
     bad_command = Subcommand('bad',
                              help=u'check for corrupt or missing files')
     bad_command.parser.add_option(
         u'-v', u'--verbose',
         action='store_true', default=False, dest='verbose',
         help=u'view results for both the bad and uncorrupted files'
     )
     bad_command.func = self.command
     return [bad_command]
コード例 #12
0
ファイル: mbcollection.py プロジェクト: adamjakab/Beets
 def commands(self):
     mbupdate = Subcommand('mbupdate', help='Update MusicBrainz collection')
     mbupdate.parser.add_option('-r',
                                '--remove',
                                action='store_true',
                                default=None,
                                dest='remove',
                                help='Remove albums not in beets library')
     mbupdate.func = self.update_collection
     return [mbupdate]
コード例 #13
0
ファイル: play.py プロジェクト: cmclaughlin/beets
 def commands(self):
     play_command = Subcommand('play',
                               help='send music to a player as a playlist')
     play_command.parser.add_option(
         '-a',
         '--album',
         action='store_true',
         default=False,
         help='query and load albums rather than tracks')
     play_command.func = play_music
     return [play_command]
コード例 #14
0
ファイル: play.py プロジェクト: shanemikel/beets
 def commands(self):
     play_command = Subcommand('play',
                               help='send music to a player as a playlist')
     play_command.parser.add_album_option()
     play_command.parser.add_option(
         '-A',
         '--args',
         action='store',
         help='add additional arguments to the command',
     )
     play_command.func = self.play_music
     return [play_command]
コード例 #15
0
ファイル: play.py プロジェクト: Dietr1ch/beets
 def commands(self):
     play_command = Subcommand(
         'play',
         help='send music to a player as a playlist'
     )
     play_command.parser.add_option(
         '-a', '--album',
         action='store_true', default=False,
         help='query and load albums rather than tracks'
     )
     play_command.func = play_music
     return [play_command]
コード例 #16
0
    def commands(self):
        zero_command = Subcommand('zero', help='set fields to null')

        def zero_fields(lib, opts, args):
            if not decargs(args) and not input_yn(
                    u"Remove fields for all items? (Y/n)", True):
                return
            for item in lib.items(decargs(args)):
                self.process_item(item)

        zero_command.func = zero_fields
        return [zero_command]
コード例 #17
0
ファイル: thumbnails.py プロジェクト: hiro-sumi1888/beets
    def commands(self):
        thumbnails_command = Subcommand("thumbnails",
                                        help="Create album thumbnails")
        thumbnails_command.parser.add_option(
            '-f', '--force', dest='force', action='store_true', default=False,
            help='force regeneration of thumbnails deemed fine (existing & '
                 'recent enough)')
        thumbnails_command.parser.add_option(
            '--dolphin', dest='dolphin', action='store_true', default=False,
            help="create Dolphin-compatible thumbnail information (for KDE)")
        thumbnails_command.func = self.process_query

        return [thumbnails_command]
コード例 #18
0
ファイル: wlg.py プロジェクト: samdoshi/whatlastgenre
 def commands(self):
     cmds = Subcommand('wlg', help='get genres with whatlastgenre')
     cmds.parser.add_option(
         '-v', '--verbose', dest='verbose', action='count',
         default=0, help='verbose output (-vv for debug)')
     cmds.parser.add_option(
         '-f', '--force', dest='force', action='store_true',
         default=False, help='force overwrite existing genres')
     cmds.parser.add_option(
         '-u', '--update-cache', dest='cache', action='store_true',
         default=False, help='force update cache')
     cmds.func = self.commanded
     return [cmds]
コード例 #19
0
ファイル: zero.py プロジェクト: JDLH/beets
    def commands(self):
        zero_command = Subcommand('zero', help='set fields to null')

        def zero_fields(lib, opts, args):
            if not decargs(args) and not input_yn(
                    u"Remove fields for all items? (Y/n)",
                    True):
                return
            for item in lib.items(decargs(args)):
                self.process_item(item)

        zero_command.func = zero_fields
        return [zero_command]
コード例 #20
0
ファイル: wlg.py プロジェクト: YetAnotherNerd/whatlastgenre
 def commands(self):
     cmds = Subcommand('wlg', help='get genres with whatlastgenre')
     cmds.parser.add_option(
         '-v', '--verbose', dest='verbose', action='count',
         default=0, help='verbose output (-vv for debug)')
     cmds.parser.add_option(
         '-f', '--force', dest='force', action='store_true',
         default=False, help='force overwrite existing genres')
     cmds.parser.add_option(
         '-u', '--update-cache', dest='cache', action='store_true',
         default=False, help='force update cache')
     cmds.func = self.commanded
     return [cmds]
コード例 #21
0
ファイル: play.py プロジェクト: agittins/beets
 def commands(self):
     play_command = Subcommand(
         'play',
         help=u'send music to a player as a playlist'
     )
     play_command.parser.add_album_option()
     play_command.parser.add_option(
         u'-A', u'--args',
         action='store',
         help=u'add additional arguments to the command',
     )
     play_command.func = self.play_music
     return [play_command]
コード例 #22
0
    def commands(self):
        thumbnails_command = Subcommand("thumbnails",
                                        help=u"Create album thumbnails")
        thumbnails_command.parser.add_option(
            u'-f', u'--force',
            dest='force', action='store_true', default=False,
            help=u'force regeneration of thumbnails deemed fine (existing & '
                 u'recent enough)')
        thumbnails_command.parser.add_option(
            u'--dolphin', dest='dolphin', action='store_true', default=False,
            help=u"create Dolphin-compatible thumbnail information (for KDE)")
        thumbnails_command.func = self.process_query

        return [thumbnails_command]
コード例 #23
0
    def commands(self):
        airsonicsync = Subcommand('airsonicsync', help='sync new imports to the airsonic monthly playlist')
        airsonicsync.func = self.sync

        airsonictest = Subcommand('airsonictest', help='ping the airsonic server defined in the config')
        airsonictest.func = self.test


        airsonicscan = Subcommand('airsonicscan', help='run a scan on the airsonic server')
        airsonicscan.func = self.scan
        return [airsonicsync, airsonictest, airsonicscan]
コード例 #24
0
    def __init__(self):
        super(MissingPlugin, self).__init__()

        self.config.add({
            'count': False,
            'total': False,
            'album': False,
        })

        self.album_template_fields['missing'] = _missing_count

        self._command = Subcommand('missing', help=__doc__, aliases=['miss'])
        self._command.parser.add_option(u'-c',
                                        u'--count',
                                        dest='count',
                                        action='store_true',
                                        help=u'count missing tracks per album')
        self._command.parser.add_option(u'-t',
                                        u'--total',
                                        dest='total',
                                        action='store_true',
                                        help=u'count total of missing tracks')
        self._command.parser.add_option(
            u'-a',
            u'--album',
            dest='album',
            action='store_true',
            help=u'show missing albums for artist instead of tracks')
        self._command.parser.add_format_option()
コード例 #25
0
ファイル: missing.py プロジェクト: simonluijk/beets
    def __init__(self):
        super(MissingPlugin, self).__init__()

        self.config.add({
            'format': None,
            'count': False,
            'total': False,
        })

        self.album_template_fields['missing'] = _missing_count

        self._command = Subcommand('missing',
                                   help=__doc__,
                                   aliases=['miss'])

        self._command.parser.add_option('-f', '--format', dest='format',
                                        action='store', type='string',
                                        help='print with custom FORMAT',
                                        metavar='FORMAT')

        self._command.parser.add_option('-c', '--count', dest='count',
                                        action='store_true',
                                        help='count missing tracks per album')

        self._command.parser.add_option('-t', '--total', dest='total',
                                        action='store_true',
                                        help='count total of missing tracks')
コード例 #26
0
ファイル: duplicates.py プロジェクト: toddbot2/beets
    def __init__(self):
        super(DuplicatesPlugin, self).__init__()

        self.config.add({'format': ''})
        self.config.add({'count': False})
        self.config.add({'album': False})
        self.config.add({'full': False})

        self._command = Subcommand('duplicates',
                                   help=__doc__,
                                   aliases=['dup'])

        self._command.parser.add_option('-f', '--format', dest='format',
                                        action='store', type='string',
                                        help='print with custom FORMAT',
                                        metavar='FORMAT')

        self._command.parser.add_option('-c', '--count', dest='count',
                                        action='store_true',
                                        help='count duplicate tracks or\
                                        albums')

        self._command.parser.add_option('-a', '--album', dest='album',
                                        action='store_true',
                                        help='show duplicate albums instead\
                                        of tracks')

        self._command.parser.add_option('-F', '--full', dest='full',
                                        action='store_true',
                                        help='show all versions of duplicate\
                                        tracks or albums')
コード例 #27
0
    def commands(self):
        tag_copy_command = Subcommand(
            'tagcopy',
            help='copy the contents of one tag to another',
            aliases=['tc'])

        def copy_tags(lib, opts, args):
            items = list(lib.items(decargs(args)))

            for item in items:
                item = self.process_item(item)
                item.store()
                item.write()

        tag_copy_command.func = copy_tags

        return [tag_copy_command]
コード例 #28
0
ファイル: play.py プロジェクト: arogl/beets
 def commands(self):
     play_command = Subcommand(
         'play',
         help=u'send music to a player as a playlist'
     )
     play_command.parser.add_album_option()
     play_command.parser.add_option(
         u'-A', u'--args',
         action='store',
         help=u'add additional arguments to the command',
     )
     play_command.parser.add_option(
         u'-y', u'--yes',
         action="store_true",
         help=u'skip the warning threshold',
     )
     play_command.func = self._play_command
     return [play_command]
コード例 #29
0
ファイル: duplicates.py プロジェクト: tjgritton/beets
    def __init__(self):
        super(DuplicatesPlugin, self).__init__()

        self.config.add({
            'format': '',
            'count': False,
            'album': False,
            'full': False,
            'path': False,
            'keys': ['mb_trackid', 'mb_albumid'],
            'checksum': None,
            'copy': False,
            'move': False,
            'delete': False,
            'tag': False,
        })

        self._command = Subcommand('duplicates',
                                   help=__doc__,
                                   aliases=['dup'])
        self._command.parser.add_option('-c', '--count', dest='count',
                                        action='store_true',
                                        help='show duplicate counts')

        self._command.parser.add_option('-C', '--checksum', dest='checksum',
                                        action='store', metavar='PROG',
                                        help='report duplicates based on'
                                        ' arbitrary command')

        self._command.parser.add_option('-d', '--delete', dest='delete',
                                        action='store_true',
                                        help='delete items from library and '
                                        'disk')

        self._command.parser.add_option('-F', '--full', dest='full',
                                        action='store_true',
                                        help='show all versions of duplicate'
                                        ' tracks or albums')

        self._command.parser.add_option('-k', '--keys', dest='keys',
                                        action='callback', metavar='KEY1 KEY2',
                                        callback=vararg_callback,
                                        help='report duplicates based on keys')

        self._command.parser.add_option('-m', '--move', dest='move',
                                        action='store', metavar='DEST',
                                        help='move items to dest')

        self._command.parser.add_option('-o', '--copy', dest='copy',
                                        action='store', metavar='DEST',
                                        help='copy items to dest')

        self._command.parser.add_option('-t', '--tag', dest='tag',
                                        action='store',
                                        help='tag matched items with \'k=v\''
                                        ' attribute')
        self._command.parser.add_all_common_options()
コード例 #30
0
ファイル: play.py プロジェクト: RobbeeUA/Music
 def commands(self):
     play_command = Subcommand('play',
                               help=u'send music to a player as a playlist')
     play_command.parser.add_album_option()
     play_command.parser.add_option(
         u'-A',
         u'--args',
         action='store',
         help=u'add additional arguments to the command',
     )
     play_command.parser.add_option(
         u'-y',
         u'--yes',
         action="store_true",
         help=u'skip the warning threshold',
     )
     play_command.func = self._play_command
     return [play_command]
コード例 #31
0
ファイル: subsonicplaylist.py プロジェクト: zyj3421/beets
    def commands(self):
        def build_playlist(lib, opts, args):
            self.config.set_args(opts)
            ids = self.config['playlist_ids'].as_str_seq()
            if self.config['playlist_names'].as_str_seq():
                playlists = ElementTree.fromstring(
                    self.send('getPlaylists').text)[0]
                if playlists.attrib.get('code', '200') != '200':
                    alt_error = 'error getting playlists,' \
                                ' but no error message found'
                    self._log.warn(
                        playlists.attrib.get('message', alt_error))
                    return
                for name in self.config['playlist_names'].as_str_seq():
                    for playlist in playlists:
                        if name == playlist.attrib['name']:
                            ids.append(playlist.attrib['id'])

            playlist_dict = self.get_playlists(ids)

            # delete old tags
            if self.config['delete']:
                existing = list(lib.items('subsonic_playlist:";"'))
                to_be_removed = filter_to_be_removed(
                    existing,
                    playlist_dict.keys())
                for item in to_be_removed:
                    item['subsonic_playlist'] = ''
                    with lib.transaction():
                        item.try_sync(write=True, move=False)

            self.update_tags(playlist_dict, lib)

        subsonicplaylist_cmds = Subcommand(
            'subsonicplaylist', help=u'import a subsonic playlist'
        )
        subsonicplaylist_cmds.parser.add_option(
            u'-d',
            u'--delete',
            action='store_true',
            help=u'delete tag from items not in any playlist anymore',
        )
        subsonicplaylist_cmds.func = build_playlist
        return [subsonicplaylist_cmds]
コード例 #32
0
ファイル: drop2beets.py プロジェクト: martinkirch/drop2beets
    def __init__(self):
        super(Drop2BeetsPlugin, self).__init__()
        self.attributes = None
        self.dropbox_path = self.config['dropbox_path'].as_filename()

        try:
            exec(self.config['on_item'].get(), globals())
            self.on_item = on_item
        except:
            self.on_item = lambda item, path: dict()

        self._command_dropbox = Subcommand('dropbox',
            help="Start watching %s for files to import automatically" %
                self.dropbox_path)
        self._command_dropbox.func = self._main

        self._command_install = Subcommand('install_dropbox',
            help="Install drop2beets as a user-lever systemd service")
        self._command_install.func = self._install
コード例 #33
0
ファイル: thumbnails.py プロジェクト: angelsanz/beets
    def commands(self):
        thumbnails_command = Subcommand("thumbnails", help=u"Create album thumbnails")
        thumbnails_command.parser.add_option(
            u"-f",
            u"--force",
            dest="force",
            action="store_true",
            default=False,
            help=u"force regeneration of thumbnails deemed fine (existing & " u"recent enough)",
        )
        thumbnails_command.parser.add_option(
            u"--dolphin",
            dest="dolphin",
            action="store_true",
            default=False,
            help=u"create Dolphin-compatible thumbnail information (for KDE)",
        )
        thumbnails_command.func = self.process_query

        return [thumbnails_command]
コード例 #34
0
    def __init__(self):
        super(Rivendell2BeetsPlugin, self).__init__()
        self.attributes = None

        self.IDENTIFIED_VIA_ACOUSTID = 0
        self.SEEN = 0
        self.IMPORTED = 0
        self.REJECTED = 0

        self._command_rivendell = Subcommand('rivendell2beets',
                                             help="Import from rivendell")
        self._command_rivendell.func = self._main
コード例 #35
0
ファイル: alias.py プロジェクト: kergoth/beets-kergoth
    def commands(self):
        """Add the alias commands."""
        if self.config['from_path'].get(bool):
            commands = dict(self.get_path_commands())
        else:
            commands = {}

        for alias in self.config['aliases'].keys():
            if alias in commands:
                raise confuse.ConfigError(
                    u'alias.aliases.{0} was specified multiple times'.format(
                        alias))

            command = self.config['aliases'][alias].get()
            if isinstance(command, six.text_type):
                commands[alias] = self.get_command(alias, command)
            elif isinstance(command, abc.Mapping):
                command_text = command.get('command')
                if not command_text:
                    raise confuse.ConfigError(
                        u'alias.aliases.{0}.command not found'.format(alias))
                help_text = command.get('help', command_text)
                commands[alias] = self.get_command(alias, command_text,
                                                   help_text)
            else:
                raise confuse.ConfigError(
                    u'alias.aliases.{0} must be a string or single-element mapping'
                    .format(alias))

        if 'alias' in commands:
            raise ui.UserError(
                u'alias `alias` is reserved for the alias plugin')

        alias = Subcommand('alias',
                           help=u'Print the available alias commands.')
        alias_commands = dict((a, c.command) for a, c in commands.items())
        alias.func = lambda lib, opts, args: self.cmd_alias(
            lib, opts, args, alias_commands)
        commands['alias'] = alias
        return commands.values()
コード例 #36
0
ファイル: __init__.py プロジェクト: sdrik/beetsonic
    def commands(self):
        def init_server(lib, opts, args):
            model = BeetsModel(lib)
            if opts.username is None:
                raise KeyError('Username is required')
            if opts.password is None:
                raise KeyError('Password is required')
            # Get all the args and opts into one variable

            configs = {
                u'host': self.config['host'].as_str(),
                u'port': self.config['port'].get(int),
                u'cors': self.config['cors'].as_str(),
                u'playlist_dir': self.config['playlist_dir'].as_filename(),
                u'debug': opts.debug,
                u'username': opts.username,
                u'password': opts.password,
                u'ignoredArticles': self.config['ignoredArticles'].as_str(),
            }
            app = SubsonicServer(model, configs, __name__)
            app.run(
                host=configs[u'host'],
                port=configs[u'port'],
                debug=configs[u'debug'],
            )

        cmd = Subcommand('sonic',
                         help='Run Subsonic server interface for beets')
        cmd.parser.add_option(u'-u', u'--username', action='store',
                              help=u'username')
        cmd.parser.add_option(u'-p', u'--password', action='store',
                              help=u'password')
        cmd.parser.add_option(u'-d', u'--debug', action='store_true',
                              default=False, help=u'debug mode')
        cmd.func = init_server
        return [cmd]
コード例 #37
0
    def commands(self):
        gupload = Subcommand('gmusic-upload',
                             help=u'upload your tracks to Google Play Music')
        gupload.func = self.upload

        search = Subcommand('gmusic-songs',
                            help=u'list of songs in Google Play Music library')
        search.parser.add_option('-t', '--track', dest='track',
                                 action='store_true',
                                 help='Search by track name')
        search.parser.add_option('-a', '--artist', dest='artist',
                                 action='store_true',
                                 help='Search by artist')
        search.func = self.search
        return [gupload, search]
コード例 #38
0
ファイル: advisory.py プロジェクト: kergoth/beets-kergoth
 def commands(self):
     """Add the commands."""
     write_advisory = Subcommand('write-advisory',
                                 help=u'write the advisory state to tags')
     write_advisory.parser.add_option(
         u'-p', u'--pretend', action='store_true',
         help=u"show all changes but do nothing"
     )
     write_advisory.func = self.write_advisory
     read_advisory = Subcommand('read-advisory',
                                help=u'read the advisory state from tags')
     read_advisory.parser.add_option(
         u'-p', u'--pretend', action='store_true',
         help=u"show all changes but do nothing"
     )
     read_advisory.func = self.read_advisory
     return [read_advisory, write_advisory]
コード例 #39
0
ファイル: mbcollection.py プロジェクト: jbaginski/beets
            if re.match(UUID_REGEX, aid):
                album_ids.append(aid)
            else:
                log.info(u'skipping invalid MBID: {0}', aid)

    # Submit to MusicBrainz.
    print('Updating MusicBrainz collection {0}...'.format(collection_id))
    submit_albums(collection_id, album_ids)
    print('...MusicBrainz collection updated.')


def update_collection(lib, opts, args):
    update_album_list(lib.albums())


update_mb_collection_cmd = Subcommand('mbupdate',
                                      help='Update MusicBrainz collection')
update_mb_collection_cmd.func = update_collection


class MusicBrainzCollectionPlugin(BeetsPlugin):
    def __init__(self):
        super(MusicBrainzCollectionPlugin, self).__init__()
        musicbrainzngs.auth(
            config['musicbrainz']['user'].get(unicode),
            config['musicbrainz']['pass'].get(unicode),
        )
        self.config.add({'auto': False})
        if self.config['auto']:
            self.import_stages = [self.imported]

    def commands(self):
コード例 #40
0
ファイル: pastan.py プロジェクト: pukkamustard/pastan
 def commands(self):
     pastan = Subcommand('pastan', help='Hello, my name is pastan.')
     pastan.func = self.pastan
     return [pastan]
コード例 #41
0
ファイル: freedesktop.py プロジェクト: scztt/beets
 def commands(self):
     freedesktop_command = Subcommand("freedesktop",
                                      help="Create .directory files")
     freedesktop_command.func = self.process_query
     return [freedesktop_command]
コード例 #42
0
ファイル: gmusic-sync.py プロジェクト: brannon/gmusic-sync
def make_command(name, func, **kwargs):
    c = Subcommand(name, **kwargs)
    c.func = func
    return c
コード例 #43
0
    def __init__(self):
        super(DuplicatesPlugin, self).__init__()

        self.config.add({
            'album': False,
            'checksum': '',
            'copy': '',
            'count': False,
            'delete': False,
            'format': '',
            'full': False,
            'keys': [],
            'merge': False,
            'move': '',
            'path': False,
            'tiebreak': {},
            'strict': False,
            'tag': '',
        })

        self._command = Subcommand('duplicates', help=__doc__, aliases=['dup'])
        self._command.parser.add_option(
            u'-c',
            u'--count',
            dest='count',
            action='store_true',
            help=u'show duplicate counts',
        )
        self._command.parser.add_option(
            u'-C',
            u'--checksum',
            dest='checksum',
            action='store',
            metavar='PROG',
            help=u'report duplicates based on arbitrary command',
        )
        self._command.parser.add_option(
            u'-d',
            u'--delete',
            dest='delete',
            action='store_true',
            help=u'delete items from library and disk',
        )
        self._command.parser.add_option(
            u'-F',
            u'--full',
            dest='full',
            action='store_true',
            help=u'show all versions of duplicate tracks or albums',
        )
        self._command.parser.add_option(
            u'-s',
            u'--strict',
            dest='strict',
            action='store_true',
            help=u'report duplicates only if all attributes are set',
        )
        self._command.parser.add_option(
            u'-k',
            u'--key',
            action='append',
            metavar='KEY',
            help=u'report duplicates based on keys (use multiple times)',
        )
        self._command.parser.add_option(
            u'-M',
            u'--merge',
            dest='merge',
            action='store_true',
            help=u'merge duplicate items',
        )
        self._command.parser.add_option(
            u'-m',
            u'--move',
            dest='move',
            action='store',
            metavar='DEST',
            help=u'move items to dest',
        )
        self._command.parser.add_option(
            u'-o',
            u'--copy',
            dest='copy',
            action='store',
            metavar='DEST',
            help=u'copy items to dest',
        )
        self._command.parser.add_option(
            u'-t',
            u'--tag',
            dest='tag',
            action='store',
            help=u'tag matched items with \'k=v\' attribute',
        )
        self._command.parser.add_all_common_options()
コード例 #44
0
 def commands(self):
     mbupdate = Subcommand('mbupdate', help='Update MusicBrainz collection')
     mbupdate.func = self.update_collection
     return [mbupdate]
コード例 #45
0
ファイル: random.py プロジェクト: madjar/beets
            selected_artists[random.choice(artists)] += 1

        objs = []
        for artist, count in selected_artists.items():
            objs_from_artist = objs_by_artists[artist]
            number = min(count, len(objs_from_artist))
            objs.extend(random.sample(objs_from_artist, number))

    else:
        number = min(len(objs), opts.number)
        objs = random.sample(objs, number)

    for item in objs:
        print_obj(item, lib, template)

random_cmd = Subcommand('random',
                        help='chose a random track or album')
random_cmd.parser.add_option('-a', '--album', action='store_true',
        help='choose an album instead of track')
random_cmd.parser.add_option('-p', '--path', action='store_true',
        help='print the path of the matched item')
random_cmd.parser.add_option('-f', '--format', action='store',
        help='print with custom format', default=None)
random_cmd.parser.add_option('-n', '--number', action='store', type="int",
        help='number of objects to choose', default=1)
random_cmd.parser.add_option('-e', '--equal-chance', action='store_true',
        help='each artist has the same chance')
random_cmd.func = random_item

class Random(BeetsPlugin):
    def commands(self):
        return [random_cmd]
コード例 #46
0
ファイル: play.py プロジェクト: christophernhill/beets
 def commands(self):
     play_command = Subcommand("play", help="send music to a player as a playlist")
     play_command.parser.add_album_option()
     play_command.parser.add_option("-A", "--args", action="store", help="add additional arguments to the command")
     play_command.func = self.play_music
     return [play_command]
コード例 #47
0
ファイル: cmus.py プロジェクト: coolkehon/beets
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

"""Beets command line interface to cmus-remote
an instance of cmus must already be running"""

from beets.plugins import BeetsPlugin
from beets import mediafile
from beets import ui
from beets.ui import Subcommand
from beets.util import syspath, normpath
import subprocess 

cmus_cmd = Subcommand('cmus', help='Interface to a remote cmus instance.')
cmus_cmd.parser.add_option('--socket', action='store_true', dest='socket', help='Connect using socket SOCKET instead of ~/.cmus/socket.')
cmus_cmd.parser.add_option('-p', '--play', action='store_true', help='Start playing.')
cmus_cmd.parser.add_option('-u', '--pause', action='store_true', help='Toggle pause.')
cmus_cmd.parser.add_option('-s', '--stop', action='store_true', help='Stop playing.')
cmus_cmd.parser.add_option('-n', '--next', action='store_true', help='Skip forward in playlist.')
cmus_cmd.parser.add_option('-r', '--prev', action='store_true', help='Skip backward in playlist.')
cmus_cmd.parser.add_option('-R', '--repeat', action='store_true', help='Toggle repeat.')
cmus_cmd.parser.add_option('-S', '--shuffle', action='store_true', help='Toggle shuffle.')
cmus_cmd.parser.add_option('-Q', '--status', action='store_true', help='Get player status information.')
cmus_cmd.parser.add_option('-l', '--library', action='store_true', help='Modify library instead of playlist.')
cmus_cmd.parser.add_option('-P', '--playlist', action='store_true', help='Modify playlist (default).')
cmus_cmd.parser.add_option('-q', '--queue', action='store_true', help='Modify play queue instead of playlist.')
cmus_cmd.parser.add_option('-c', '--clear', action='store_true', help='clear playlist, library (-l) or play queue (-q) before adding songs.')
cmus_cmd.parser.add_option('-a', '--add', action='store_true', help='Add songs to cmus. Similar to beet ls (see beet help ls).')
コード例 #48
0
ファイル: badfiles.py プロジェクト: drm00/beets
 def commands(self):
     bad_command = Subcommand('bad',
                              help='check for corrupt or missing files')
     bad_command.func = self.check_bad
     return [bad_command]
コード例 #49
0
ファイル: blackbird.py プロジェクト: digideskio/blackbird
    def commands(self):
        """
        Commands for generating and importing features
        """

        def get_mfcc(song):
            # Deferred import (librosa was messing up general beet output)
            import librosa
            y, sr = librosa.load(song.encode(sys.getfilesystemencoding()))
            mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=20)
            return block_reduce(mfcc, (1, 100), np.mean)

        # Generate sequential features
        features_cmd = Subcommand(
            "features",
            help="Generate sequential acoustic features [blackbird]")

        def features_func(lib, opts, args):
            filtered_items = lib.items(decargs(args))

            if len(filtered_items) == 0:
                print("Query didn't match any item")
                return

            seq_features_file = config["blackbird"]["features"].get("unicode")
            seq_features = cPickle.load(open(seq_features_file, "rb"))

            print("Finding features...")
            bar = pyprind.ProgBar(len(filtered_items))
            for item in filtered_items:
                if item.id not in features:
                    try:
                        data = get_mfcc(item.path)
                        seq_features[item.id] = data
                    except Exception as e:
                        print(e)
                bar.update()

            print("Saving data...")
            cPickle.dump(seq_features,
                         open(seq_features_file, "wb"),
                         protocol=cPickle.HIGHEST_PROTOCOL)

        # Import features as coordinates
        coords_cmd = Subcommand(
            "coords",
            help=
            "Generate coordinates based on calculated features [blackbird]")
        coords_cmd.parser.add_option(
            "-t",
            "--type",
            help="Type of vectorization [mean (default), lstm]")

        def coords_func(lib, opts, args):
            if opts.type:
                seq_features_file = config["blackbird"]["features"].get(
                    "unicode")
                seq_features = cPickle.load(open(seq_features_file, "rb"))

                keys = seq_features.keys()

                if opts.type == "mean":
                    features = np.empty((len(seq_features), 20))

                    for idx, key in enumerate(seq_features):
                        length = seq_features[key].shape[1]
                        features[idx, :] = seq_features[key][:, int(
                            0.1 * length):int(0.9 * length)].mean(axis=1)
                elif opts.type == "lstm":
                    print("Loading network...")
                    model = LSTMSeq2Seq(
                        config["blackbird"]["model"]["arch"].get("unicode"),
                        config["blackbird"]["model"]["weights"].get("unicode"),
                        config["blackbird"]["model"]["output"].get())
                    # Pad sequences
                    maxlen = 150
                    padded_seq_features = np.empty((len(seq_features), maxlen,
                                                    20))
                    for idx, key in enumerate(seq_features):
                        padded_seq_features[
                            idx, :, :] = sequence.pad_sequences(
                                seq_features[key],
                                maxlen=maxlen,
                                dtype="float32").T

                    print("Getting vectors...")
                    features = model.predict([padded_seq_features, 0])
                else:
                    print("Provide a valid --type [mean, lstm]")
                    sys.exit(1)

                print("Reducing dimensions...")
                features_2d = TSNE(n_components=2).fit_transform(features)

                print("Writing to db...")
                conn = sqlite3.connect(config["blackbird"]["db"].get(
                    "unicode"))
                cur = conn.cursor()
                cur.execute("DELETE FROM coords")

                to_insert = []
                for idx in xrange(features_2d.shape[0]):
                    to_insert.append((keys[idx], features_2d[idx, 0],
                                      features_2d[idx, 1]))
                cur.executemany("INSERT INTO coords VALUES (?, ?, ?)",
                                to_insert)
                conn.commit()
                conn.close()

                # Fill leftovers
                ids_to_fill = []
                for item in lib.items():
                    if item.id not in keys:
                        ids_to_fill.append(item.id)

                self.fill(ids_to_fill,
                          features_2d.min(axis=0),
                          features_2d.max(axis=0))
            else:
                print("Provide a valid --type [mean, lstm]")

        coords_cmd.func = coords_func
        features_cmd.func = features_func

        return [features_cmd, coords_cmd]
コード例 #50
0
            # found duplicates
            if opts["output_count"]:
                print_obj(match_list[0], lib, fmt=fmt.format(num))
            else:
                for match in match_list:
                    print_obj(match, lib, fmt=fmt.format(num))
            print ""


#######################
# Command Declaration #
#######################

find_command = Subcommand(
    'find_duplicates', 
    help = 'Lists all duplicates for given query', 
    aliases = ["fdup"]
)
find_command.func = dupl_finder

gen_parser(find_command)


#####################
# Plugin Definition #
#####################

class ExtendedDuplicateFinder(BeetsPlugin):
    def commands(self):
        return [find_command]
コード例 #51
0
import beets
import urllib
import urllib2

def sendAlbums(username, password, albumIds):
    url = 'http://musicbrainz.org/ws/1/collection/' #Where to send them
    data = urllib.urlencode({ 'add': ",".join(albumIds) })
    #Post it
    pm = urllib2.HTTPPasswordMgrWithDefaultRealm()
    pm.add_password(None, url, username, password)
    urllib2.install_opener(urllib2.build_opener(
            urllib2.HTTPDigestAuthHandler(pm)))
    resp = urllib2.urlopen(url, data).read()
    return resp

update_mb_collection = Subcommand('mbupdate',
        help='Update MusicBrainz collection')
def updateCollection(lib, config, opts, args):
    username = beets.ui.config_val(config, 'musicbrainz', 'user', '')
    password = beets.ui.config_val(config, 'musicbrainz', 'pass', '')
    #Get a list of all the albums
    albums =  map(lambda a: a.mb_albumid, lib.albums())
    print 'Updating MusicBrainz collection...'
    sendAlbums(username, password, albums)
    print '...MusicBrainz collection updated'

update_mb_collection.func = updateCollection

class MusicbrainzCollection(BeetsPlugin):
    def commands(self):
            return [update_mb_collection]
コード例 #52
0
"""
This plugin creates a separate log of files that are ignored when on import and a separate log is created
for them
"""


from beets.plugins import BeetsPlugin
import os
import socket
from beets import config
from beets.ui import Subcommand

missedLogFile = '/home/travis/Apps/BeetsPlugin/beetsplug/missed.txt'

importMissedAlbums = Subcommand('importmissed', help='Import the album listed in the "missed" file')
def reImportMissed(lib, opts, args):
	print "Reimported files/albums we missed the first time"
	with open(missedLogFile) as f:
		albums = f.readlines()	
	

importMissedAlbums.func = reImportMissedAlbums


class MissedOnImport(BeetsPlugin):
	def __init__(self):
		print 'Init of new plugin!!'


コード例 #53
0
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

"""Beets command line interface to cmus-remote
an instance of cmus must already be running"""

from beets.plugins import BeetsPlugin
from beets import mediafile
from beets import ui
from beets.ui import Subcommand
from beets.util import syspath, normpath
import subprocess

cmus_cmd = Subcommand('cmus', help='Interface to a remote cmus instance.')
cmus_cmd.parser.add_option('--socket', action='store_true', dest='socket', help='Connect using socket SOCKET instead of ~/.cmus/socket.')
cmus_cmd.parser.add_option('-p', '--play', action='store_true', help='Start playing.')
cmus_cmd.parser.add_option('-u', '--pause', action='store_true', help='Toggle pause.')
cmus_cmd.parser.add_option('-s', '--stop', action='store_true', help='Stop playing.')
cmus_cmd.parser.add_option('-n', '--next', action='store_true', help='Skip forward in playlist.')
cmus_cmd.parser.add_option('-r', '--prev', action='store_true', help='Skip backward in playlist.')
cmus_cmd.parser.add_option('-R', '--repeat', action='store_true', help='Toggle repeat.')
cmus_cmd.parser.add_option('-S', '--shuffle', action='store_true', help='Toggle shuffle.')
cmus_cmd.parser.add_option('-Q', '--status', action='store_true', help='Get player status information.')
cmus_cmd.parser.add_option('-l', '--library', action='store_true', help='Modify library instead of playlist.')
cmus_cmd.parser.add_option('-P', '--playlist', action='store_true', help='Modify playlist (default).')
cmus_cmd.parser.add_option('-q', '--queue', action='store_true', help='Modify play queue instead of playlist.')
cmus_cmd.parser.add_option('-c', '--clear', action='store_true', help='clear playlist, library (-l) or play queue (-q) before adding songs.')
cmus_cmd.parser.add_option('-a', '--add', action='store_true', help='Add songs to cmus. Similar to beet ls (see beet help ls).')
コード例 #54
0
ファイル: beetFs.py プロジェクト: jbaiter/beetfs
from mutagen.flac import (
    FLAC,
    Padding,
    MetadataBlock,
    VCFLACDict,
    CueSheet,
    SeekTable,
    FLACNoHeaderError,
    FLACVorbisError,
)
from mutagen.id3 import ID3, BitPaddedInt, MakeID3v1
from mutagen._util import insert_bytes

PATH_FORMAT = "$artist/$album ($year) [$format_upper]/" "$track - $artist - $title.$format"

beetFs_command = Subcommand("mount", help="Mount a beets filesystem")
log = logging.getLogger("beets")


# FUSE version at the time of writing. Be compatible with this version.
fuse.fuse_python_api = (0, 2)

""" This is duplicated from Library. Ideally should be exposed from there."""
METADATA_RW_FIELDS = [
    ("title", "text"),
    ("artist", "text"),
    ("album", "text"),
    ("genre", "text"),
    ("composer", "text"),
    ("grouping", "text"),
    ("year", "int"),
コード例 #55
0
ファイル: usertag.py プロジェクト: igordertigor/beets-usertag
    for item in items:
        usertags = item.get('usertags', None)
        if usertags is None:
            usertags = []
        else:
            usertags = usertags.split('|')
        # usertags.append(' '.join(newtags))
        usertags.extend(newtags)
        usertags = list(set(usertags))
        if '' in usertags:
            usertags.pop(usertags.index(''))
        item.update({'usertags': '|'.join(usertags)})
        item.store()
        print('Added tags\n   {}'.format(item))
add_tag_command = Subcommand(
    'addtag',
    help='Add user defined tags.',
    aliases=('adt',))
add_tag_command.func = add_usertag
add_tag_command.parser.add_option(
    '--tag', '-t',
    action='append', dest='tags',
    help='Tag to add. '
    'Combine multiple tags by specifiing this option repeatedly.')
add_tag_command.parser.usage += '\n'\
    'Example: beet addtag artist:beatles -t favourites'


def remove_usertag(lib, opts, args):
    """Remove a usertag"""
    items = lib.items(args)
    deltags = opts.tags
コード例 #56
0
ファイル: fuzzy.py プロジェクト: flz/beets
    if opts.album:
        objs = lib.albums()
    else:
        objs = lib.items()

    items = filter(lambda i: is_match(queryMatcher, i, album=opts.album,
                                      threshold=threshold), objs)

    for item in items:
        print_obj(item, lib, template)
        if opts.verbose:
            print(is_match(queryMatcher, item,
                           album=opts.album, verbose=True)[1])


fuzzy_cmd = Subcommand('fuzzy',
                        help='list items using fuzzy matching')
fuzzy_cmd.parser.add_option('-a', '--album', action='store_true',
        help='choose an album instead of track')
fuzzy_cmd.parser.add_option('-p', '--path', action='store_true',
        help='print the path of the matched item')
fuzzy_cmd.parser.add_option('-f', '--format', action='store',
        help='print with custom format', default=None)
fuzzy_cmd.parser.add_option('-v', '--verbose', action='store_true',
        help='output scores for matches')
fuzzy_cmd.parser.add_option('-t', '--threshold', action='store',
        help='return result with a fuzzy score above threshold. \
              (default is 0.7)', default=None)
fuzzy_cmd.func = fuzzy_list


class Fuzzy(BeetsPlugin):
コード例 #57
0
ファイル: mbcollection.py プロジェクト: steinitzu/beets
def update_collection(lib, opts, args):
    # Get the collection to modify.
    collections = mb_request('collection', 'GET', True, True)
    if not collections['collection-list']:
        raise ui.UserError('no collections exist for user')
    collection_id = collections['collection-list'][0]['id']

    # Get a list of all the albums.
    albums = [a.mb_albumid for a in lib.albums() if a.mb_albumid]

    # Submit to MusicBrainz.
    print('Updating MusicBrainz collection {0}...'.format(collection_id))
    submit_albums(collection_id, albums)
    print('...MusicBrainz collection updated.')

update_mb_collection_cmd = Subcommand('mbupdate',
        help='Update MusicBrainz collection')
update_mb_collection_cmd.func = update_collection

class MusicBrainzCollectionPlugin(BeetsPlugin):
    def __init__(self):
        super(MusicBrainzCollectionPlugin, self).__init__()
        musicbrainzngs.auth(
            config['musicbrainz']['user'].get(unicode),
            config['musicbrainz']['pass'].get(unicode),
        )

    def commands(self):
        return [update_mb_collection_cmd]
コード例 #58
0
ファイル: genrelist.py プロジェクト: michl/beets
genres = {}

def reverse_dict(orig):
	reverse = {}
	for (genre, artists) in orig.items():
		for artist in artists:
			reverse[artist]=genre
	return reverse

def get_genre(artist, genre_dict):
	try:
		return genre_dict[artist]
	except KeyError:
		return None
		
update_cmd = Subcommand('update-genres', help='Update the genres of all media in library acording to the current genre list file')
def update_genres(lib, config, opts, args):
	global genres
	global fallback_str
	for item in lib.items(ui.decargs(args)):
		if item.album_id is not None:
			continue
		genre = get_genre(item.artist, genres)
		log.warn("title: %s, artist: %s, genre: %s" % (item.title, item.artist, genre))
		if not genre and fallback_str != None:
			genre = fallback_str
			log.warn(u'no genre for %s in list: fallback to %s' % (item.artist, genre))
		if genre is not None:
			log.warn(u'adding genre for %s from list: %s' % (item.artist, genre))
		item.genre = genre
		lib.store(item)