desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Decorator that registers a path template function. The function will be invoked as ``%name{}`` from path format strings.'
@classmethod def template_func(cls, name):
def helper(func): if (cls.template_funcs is None): cls.template_funcs = {} cls.template_funcs[name] = func return func return helper
'Decorator that registers a path template field computation. The value will be referenced as ``$name`` from path format strings. The function must accept a single parameter, the Item being formatted.'
@classmethod def template_field(cls, name):
def helper(func): if (cls.template_fields is None): cls.template_fields = {} cls.template_fields[name] = func return func return helper
'Create a path query. `pattern` must be a path, either to a file or a directory. `case_sensitive` can be a bool or `None`, indicating that the behavior should depend on the filesystem.'
def __init__(self, field, pattern, fast=True, case_sensitive=None):
super(PathQuery, self).__init__(field, pattern, fast) if (case_sensitive is None): path = util.bytestring_path(util.normpath(pattern)) case_sensitive = beets.util.case_sensitive(path) self.case_sensitive = case_sensitive if (not case_sensitive): pattern = pattern.lower() self...
'Try to guess whether a unicode query part is a path query. Condition: separator precedes colon and the file exists.'
@classmethod def is_path_query(cls, query_part):
colon = query_part.find(':') if (colon != (-1)): query_part = query_part[:colon] return (((os.sep in query_part) or (os.altsep and (os.altsep in query_part))) and os.path.exists(syspath(normpath(query_part))))
'Create an exception describing an operation on the file at `path` with the underlying (chained) exception `reason`.'
def __init__(self, path, reason):
super(FileOperationError, self).__init__(path, reason) self.path = path self.reason = reason
'Get a string representing the error. Describes both the underlying reason and the file path in question.'
def text(self):
return u'{0}: {1}'.format(util.displayable_path(self.path), six.text_type(self.reason))
'Get the value for a key, either from the album or the item. Raise a KeyError for invalid keys.'
def _get(self, key):
if (self.for_path and (key in self.album_keys)): return self._get_formatted(self.album, key) elif (key in self.model_keys): return self._get_formatted(self.model, key) elif (key in self.album_keys): return self._get_formatted(self.album, key) else: raise KeyError(key)
'Get the value for a key. Certain unset values are remapped.'
def __getitem__(self, key):
value = self._get(key) if ((key == 'artist') and (not value)): return self._get('albumartist') elif ((key == 'albumartist') and (not value)): return self._get('artist') else: return value
'Creates a new item from the media file at the specified path.'
@classmethod def from_path(cls, path):
i = cls(album_id=None) i.read(path) i.mtime = i.current_mtime() return i
'Set the item\'s value for a standard field or a flexattr.'
def __setitem__(self, key, value):
if (key == 'path'): if isinstance(value, six.text_type): value = bytestring_path(value) elif isinstance(value, BLOB_TYPE): value = bytes(value) if (key in MediaFile.fields()): self.mtime = 0 super(Item, self).__setitem__(key, value)
'Set all key/value pairs in the mapping. If mtime is specified, it is not reset (as it might otherwise be).'
def update(self, values):
super(Item, self).update(values) if ((self.mtime == 0) and ('mtime' in values)): self.mtime = values['mtime']
'Get the Album object that this item belongs to, if any, or None if the item is a singleton or is not associated with a library.'
def get_album(self):
if (not self._db): return None return self._db.get_album(self)
'Read the metadata from the associated file. If `read_path` is specified, read metadata from that file instead. Updates all the properties in `_media_fields` from the media file. Raises a `ReadError` if the file could not be read.'
def read(self, read_path=None):
if (read_path is None): read_path = self.path else: read_path = normpath(read_path) try: mediafile = MediaFile(syspath(read_path)) except UnreadableFileError as exc: raise ReadError(read_path, exc) for key in self._media_fields: value = getattr(mediafile, key)...
'Write the item\'s metadata to a media file. All fields in `_media_fields` are written to disk according to the values on this object. `path` is the path of the mediafile to write the data to. It defaults to the item\'s path. `tags` is a dictionary of additional metadata the should be written to the file. (These tags n...
def write(self, path=None, tags=None):
if (path is None): path = self.path else: path = normpath(path) item_tags = dict(self) item_tags = {k: v for (k, v) in item_tags.items() if (k in self._media_fields)} if (tags is not None): item_tags.update(tags) plugins.send('write', item=self, path=path, tags=item_tags)...
'Calls `write()` but catches and logs `FileOperationError` exceptions. Returns `False` an exception was caught and `True` otherwise.'
def try_write(self, path=None, tags=None):
try: self.write(path, tags) return True except FileOperationError as exc: log.error(u'{0}', exc) return False
'Synchronize the item with the database and, possibly, updates its tags on disk and its path (by moving the file). `write` indicates whether to write new tags into the file. Similarly, `move` controls whether the path should be updated. In the latter case, files are *only* moved when they are inside their library\'s di...
def try_sync(self, write, move, with_album=True):
if write: self.try_write() if move: if (self._db and (self._db.directory in util.ancestry(self.path))): log.debug(u'moving {0} to synchronize path', util.displayable_path(self.path)) self.move(with_album=with_album) self.store()
'Moves or copies the item\'s file, updating the path value if the move succeeds. If a file exists at ``dest``, then it is slightly modified to be unique.'
def move_file(self, dest, copy=False, link=False, hardlink=False):
if (not util.samefile(self.path, dest)): dest = util.unique_path(dest) if copy: util.copy(self.path, dest) plugins.send('item_copied', item=self, source=self.path, destination=dest) elif link: util.link(self.path, dest) plugins.send('item_linked', item=self, source=se...
'Returns the current mtime of the file, rounded to the nearest integer.'
def current_mtime(self):
return int(os.path.getmtime(syspath(self.path)))
'Get the size of the underlying file in bytes. If the file is missing, return 0 (and log a warning).'
def try_filesize(self):
try: return os.path.getsize(syspath(self.path)) except (OSError, Exception) as exc: log.warning(u'could not get filesize: {0}', exc) return 0
'Removes the item. If `delete`, then the associated file is removed from disk. If `with_album`, then the item\'s album (if any) is removed if it the item was the last in the album.'
def remove(self, delete=False, with_album=True):
super(Item, self).remove() if with_album: album = self.get_album() if (album and (not album.items())): album.remove(delete, False) plugins.send('item_removed', item=self) if delete: util.remove(self.path) util.prune_dirs(os.path.dirname(self.path), self._db.di...
'Move the item to its designated location within the library directory (provided by destination()). Subdirectories are created as needed. If the operation succeeds, the item\'s path field is updated to reflect the new location. If `copy` is true, moving the file is copied rather than moved. Similarly, `link` creates a ...
def move(self, copy=False, link=False, hardlink=False, basedir=None, with_album=True, store=True):
self._check_db() dest = self.destination(basedir=basedir) util.mkdirall(dest) old_path = self.path self.move_file(dest, copy, link, hardlink) if store: self.store() if with_album: album = self.get_album() if album: album.move_art(copy) if store...
'Returns the path in the library directory designated for the item (i.e., where the file ought to be). fragment makes this method return just the path fragment underneath the root library directory; the path is also returned as Unicode instead of encoded as a bytestring. basedir can override the library\'s base directo...
def destination(self, fragment=False, basedir=None, platform=None, path_formats=None):
self._check_db() platform = (platform or sys.platform) basedir = (basedir or self._db.directory) path_formats = (path_formats or self._db.path_formats) for (query, path_format) in path_formats: if (query == PF_KEY_DEFAULT): continue (query, _) = parse_query_string(query, ...
'Returns an iterable over the items associated with this album.'
def items(self):
return self._db.items(dbcore.MatchQuery('album_id', self.id))
'Removes this album and all its associated items from the library. If delete, then the items\' files are also deleted from disk, along with any album art. The directories containing the album are also removed (recursively) if empty. Set with_items to False to avoid removing the album\'s items.'
def remove(self, delete=False, with_items=True):
super(Album, self).remove() if delete: artpath = self.artpath if artpath: util.remove(artpath) if with_items: for item in self.items(): item.remove(delete, False)
'Move or copy any existing album art so that it remains in the same directory as the items.'
def move_art(self, copy=False, link=False, hardlink=False):
old_art = self.artpath if (not old_art): return new_art = self.art_destination(old_art) if (new_art == old_art): return new_art = util.unique_path(new_art) log.debug(u'moving album art {0} to {1}', util.displayable_path(old_art), util.displayable_path(new_art)) ...
'Moves (or copies) all items to their destination. Any album art moves along with them. basedir overrides the library base directory for the destination. By default, the album is stored to the database, persisting any modifications to its metadata. If `store` is true however, the album is not stored automatically, and ...
def move(self, copy=False, link=False, hardlink=False, basedir=None, store=True):
basedir = (basedir or self._db.directory) if store: self.store() items = list(self.items()) for item in items: item.move(copy, link, hardlink, basedir=basedir, with_album=False, store=store) self.move_art(copy, link, hardlink) if store: self.store()
'Returns the directory containing the album\'s first item, provided that such an item exists.'
def item_dir(self):
item = self.items().get() if (not item): raise ValueError(u'empty album') return os.path.dirname(item.path)
'Return the total number of tracks on all discs on the album'
def _albumtotal(self):
if ((self.disctotal == 1) or (not beets.config['per_disc_numbering'])): return self.items()[0].tracktotal counted = [] total = 0 for item in self.items(): if (item.disc in counted): continue total += item.tracktotal counted.append(item.disc) if (len(co...
'Returns a path to the destination for the album art image for the album. `image` is the path of the image that will be moved there (used for its extension). The path construction uses the existing path of the album\'s items, so the album must contain at least one item or item_dir must be provided.'
def art_destination(self, image, item_dir=None):
image = bytestring_path(image) item_dir = (item_dir or self.item_dir()) filename_tmpl = Template(beets.config['art_filename'].as_str()) subpath = self.evaluate_template(filename_tmpl, True) if beets.config['asciify_paths']: subpath = util.asciify_path(subpath, beets.config['path_sep_replace'...
'Sets the album\'s cover art to the image at the given path. The image is copied (or moved) into place, replacing any existing art. Sends an \'art_set\' event with `self` as the sole argument.'
def set_art(self, path, copy=True):
path = bytestring_path(path) oldart = self.artpath artdest = self.art_destination(path) if (oldart and samefile(path, oldart)): return elif samefile(path, artdest): self.artpath = path return if (oldart == artdest): util.remove(oldart) artdest = util.unique_pa...
'Update the database with the album information. The album\'s tracks are also updated. :param fields: The fields to be stored. If not specified, all fields will be.'
def store(self, fields=None):
track_updates = {} for key in self.item_keys: if (key in self._dirty): track_updates[key] = self[key] with self._db.transaction(): super(Album, self).store(fields) if track_updates: for item in self.items(): for (key, value) in track_updates.it...
'Synchronize the album and its items with the database. Optionally, also write any new tags into the files and update their paths. `write` indicates whether to write tags to the item files, and `move` controls whether files (both audio and album art) are moved.'
def try_sync(self, write, move):
self.store() for item in self.items(): item.try_sync(write, move)
'Add the :class:`Item` or :class:`Album` object to the library database. Return the object\'s new id.'
def add(self, obj):
obj.add(self) self._memotable = {} return obj.id
'Create a new album consisting of a list of items. The items are added to the database if they don\'t yet have an ID. Return a new :class:`Album` object. The list items must not be empty.'
def add_album(self, items):
if (not items): raise ValueError(u'need at least one item') values = dict(((key, items[0][key]) for key in Album.item_keys)) album = Album(self, **values) with self.transaction(): album.add(self) for item in items: item.album_id = album.id if (...
'Parse a query and fetch. If a order specification is present in the query string the `sort` argument is ignored.'
def _fetch(self, model_cls, query, sort=None):
try: parsed_sort = None if isinstance(query, six.string_types): (query, parsed_sort) = parse_query_string(query, model_cls) elif isinstance(query, (list, tuple)): (query, parsed_sort) = parse_query_parts(query, model_cls) except dbcore.query.InvalidQueryArgumentTy...
'Get a :class:`Sort` object for albums from the config option.'
@staticmethod def get_default_album_sort():
return dbcore.sort_from_strings(Album, beets.config['sort_album'].as_str_seq())
'Get a :class:`Sort` object for items from the config option.'
@staticmethod def get_default_item_sort():
return dbcore.sort_from_strings(Item, beets.config['sort_item'].as_str_seq())
'Get :class:`Album` objects matching the query.'
def albums(self, query=None, sort=None):
return self._fetch(Album, query, (sort or self.get_default_album_sort()))
'Get :class:`Item` objects matching the query.'
def items(self, query=None, sort=None):
return self._fetch(Item, query, (sort or self.get_default_item_sort()))
'Fetch an :class:`Item` by its ID. Returns `None` if no match is found.'
def get_item(self, id):
return self._get(Item, id)
'Given an album ID or an item associated with an album, return an :class:`Album` object for the album. If no such album exists, returns `None`.'
def get_album(self, item_or_id):
if isinstance(item_or_id, int): album_id = item_or_id else: album_id = item_or_id.album_id if (album_id is None): return None return self._get(Album, album_id)
'Parametrize the functions. If `item` or `lib` is None, then some functions (namely, ``aunique``) will always evaluate to the empty string.'
def __init__(self, item=None, lib=None):
self.item = item self.lib = lib
'Returns a dictionary containing the functions defined in this object. The keys are function names (as exposed in templates) and the values are Python functions.'
def functions(self):
out = {} for key in self._func_names: out[key[len(self._prefix):]] = getattr(self, key) return out
'Convert a string to lower case.'
@staticmethod def tmpl_lower(s):
return s.lower()
'Covert a string to upper case.'
@staticmethod def tmpl_upper(s):
return s.upper()
'Convert a string to title case.'
@staticmethod def tmpl_title(s):
return s.title()
'Get the leftmost characters of a string.'
@staticmethod def tmpl_left(s, chars):
return s[0:_int_arg(chars)]
'Get the rightmost characters of a string.'
@staticmethod def tmpl_right(s, chars):
return s[(- _int_arg(chars)):]
'If ``condition`` is nonempty and nonzero, emit ``trueval``; otherwise, emit ``falseval`` (if provided).'
@staticmethod def tmpl_if(condition, trueval, falseval=u''):
try: int_condition = _int_arg(condition) except ValueError: if (condition.lower() == 'false'): return falseval else: condition = int_condition if condition: return trueval else: return falseval
'Translate non-ASCII characters to their ASCII equivalents.'
@staticmethod def tmpl_asciify(s):
return util.asciify_path(s, beets.config['path_sep_replace'].as_str())
'Format a time value using `strftime`.'
@staticmethod def tmpl_time(s, fmt):
cur_fmt = beets.config['time_format'].as_str() return time.strftime(fmt, time.strptime(s, cur_fmt))
'Generate a string that is guaranteed to be unique among all albums in the library who share the same set of keys. A fields from "disam" is used in the string if one is sufficient to disambiguate the albums. Otherwise, a fallback opaque value is used. Both "keys" and "disam" should be given as whitespace-separated list...
def tmpl_aunique(self, keys=None, disam=None, bracket=None):
if ((not self.item) or (not self.lib)): return u'' if (self.item.album_id is None): return u'' memokey = ('aunique', keys, disam, self.item.album_id) memoval = self.lib._memotable.get(memokey) if (memoval is not None): return memoval keys = (keys or 'albumartist album'...
'Gets the item(s) from x to y in a string separated by something and join then with something :param s: the string :param count: The number of items included :param skip: The number of items skipped :param sep: the separator. Usually is \'; \' (default) or \'/ \' :param join_str: the string which will join the items, d...
@staticmethod def tmpl_first(s, count=1, skip=0, sep=u'; ', join_str=u'; '):
skip = int(skip) count = (skip + int(count)) return join_str.join(s.split(sep)[skip:count])
'If field exists return trueval or the field (default) otherwise, emit return falseval (if provided). :param field: The name of the field :param trueval: The string if the condition is true :param falseval: The string if the condition is false :return: The string, based on condition'
def tmpl_ifdef(self, field, trueval=u'', falseval=u''):
if self.item.formatted().get(field): return (trueval if trueval else self.item.formatted().get(field)) else: return falseval
'Add a -a/--album option to match albums instead of tracks. If used then the format option can auto-detect whether we\'re setting the format for items or albums. Sets the album property on the options extracted from the CLI.'
def add_album_option(self, flags=('-a', '--album')):
album = optparse.Option(action='store_true', help=u'match albums instead of tracks', *flags) self.add_option(album) self._album_flags = set(flags)
'Internal callback that sets the correct format while parsing CLI arguments.'
def _set_format(self, option, opt_str, value, parser, target=None, fmt=None, store_true=False):
if store_true: setattr(parser.values, option.dest, True) if fmt: value = fmt elif value: (value,) = decargs([value]) else: value = u'' parser.values.format = value if target: config[target._format_config_key].set(value) elif self._album_flags: ...
'Add a -p/--path option to display the path instead of the default format. By default this affects both items and albums. If add_album_option() is used then the target will be autodetected. Sets the format property to u\'$path\' on the options extracted from the CLI.'
def add_path_option(self, flags=('-p', '--path')):
path = optparse.Option(nargs=0, action='callback', callback=self._set_format, callback_kwargs={'fmt': u'$path', 'store_true': True}, help=u'print paths for matched items or albums', *flags) self.add_option(path)
'Add -f/--format option to print some LibModel instances with a custom format. `target` is optional and can be one of ``library.Item``, \'item\', ``library.Album`` and \'album\'. Several behaviors are available: - if `target` is given then the format is only applied to that LibModel - if the album option is used then t...
def add_format_option(self, flags=('-f', '--format'), target=None):
kwargs = {} if target: if isinstance(target, six.string_types): target = {'item': library.Item, 'album': library.Album}[target] kwargs['target'] = target opt = optparse.Option(action='callback', callback=self._set_format, callback_kwargs=kwargs, help=u'print with custom ...
'Add album, path and format options.'
def add_all_common_options(self):
self.add_album_option() self.add_path_option() self.add_format_option()
'Creates a new subcommand. name is the primary way to invoke the subcommand; aliases are alternate names. parser is an OptionParser responsible for parsing the subcommand\'s options. help is a short description of the command. If no parser is given, it defaults to a new, empty CommonOptionsParser.'
def __init__(self, name, parser=None, help='', aliases=(), hide=False):
self.name = name self.parser = (parser or CommonOptionsParser()) self.aliases = aliases self.help = help self.hide = hide self._root_parser = None
'Create a new subcommand-aware option parser. All of the options to OptionParser.__init__ are supported in addition to subcommands, a sequence of Subcommand objects.'
def __init__(self, *args, **kwargs):
if ('usage' not in kwargs): kwargs['usage'] = u'\n %prog COMMAND [ARGS...]\n %prog help COMMAND' kwargs['add_help_option'] = False super(SubcommandsOptionParser, self).__init__(*args, **kwargs) self.disable_interspersed_args() self.subcommands = []
'Adds a Subcommand object to the parser\'s list of commands.'
def add_subcommand(self, *cmds):
for cmd in cmds: cmd.root_parser = self self.subcommands.append(cmd)
'Return the subcommand in self.subcommands matching the given name. The name may either be the name of a subcommand or an alias. If no subcommand matches, returns None.'
def _subcommand_for_name(self, name):
for subcommand in self.subcommands: if ((name == subcommand.name) or (name in subcommand.aliases)): return subcommand return None
'Parse options up to the subcommand argument. Returns a tuple of the options object and the remaining arguments.'
def parse_global_options(self, args):
(options, subargs) = self.parse_args(args) if options.help: subargs = ['help'] elif options.version: subargs = ['version'] return (options, subargs)
'Given the `args` left unused by a `parse_global_options`, return the invoked subcommand, the subcommand options, and the subcommand arguments.'
def parse_subcommand(self, args):
if (not args): args = ['help'] cmdname = args.pop(0) subcommand = self._subcommand_for_name(cmdname) if (not subcommand): raise UserError(u"unknown command '{0}'".format(cmdname)) (suboptions, subargs) = subcommand.parse_args(args) return (subcommand, suboptions, subargs)
'Given an initial autotagging of items, go through an interactive dance with the user to ask for a choice of metadata. Returns an AlbumMatch object, ASIS, or SKIP.'
def choose_match(self, task):
print_() print_((displayable_path(task.paths, u'\n') + u' ({0} items)'.format(len(task.items)))) action = _summary_judgment(task.rec) if (action == importer.action.APPLY): match = task.candidates[0] show_change(task.cur_artist, task.cur_album, match) return match elif (...
'Ask the user for a choice about tagging a single item. Returns either an action constant or a TrackMatch object.'
def choose_item(self, task):
print_() print_(displayable_path(task.item.path)) (candidates, rec) = (task.candidates, task.rec) action = _summary_judgment(task.rec) if (action == importer.action.APPLY): match = candidates[0] show_item_change(task.item, match) return match elif (action is not None): ...
'Decide what to do when a new album or item seems similar to one that\'s already in the library.'
def resolve_duplicate(self, task, found_duplicates):
log.warning(u'This {0} is already in the library!', (u'album' if task.is_album else u'item')) if config['import']['quiet']: log.info(u'Skipping.') sel = u's' else: for duplicate in found_duplicates: print_((u'Old: ' + summarize_items((list(duplicate.i...
'Get the list of prompt choices that should be presented to the user. This consists of both built-in choices and ones provided by plugins. The `before_choose_candidate` event is sent to the plugins, with session and task as its parameters. Plugins are responsible for checking the right conditions and returning a list o...
def _get_choices(self, task):
choices = [PromptChoice(u's', u'Skip', (lambda s, t: importer.action.SKIP)), PromptChoice(u'u', u'Use as-is', (lambda s, t: importer.action.ASIS))] if task.is_album: choices += [PromptChoice(u't', u'as Tracks', (lambda s, t: importer.action.TRACKS)), PromptChoice(u'g', u'Group albums', (lambda ...
'Create a session. `lib` is a Library object. `loghandler` is a logging.Handler. Either `paths` or `query` is non-null and indicates the source of files to be imported.'
def __init__(self, lib, loghandler, paths, query):
self.lib = lib self.logger = self._setup_logging(loghandler) self.paths = paths self.query = query self._is_resuming = dict() if self.paths: self.paths = list(map(normpath, self.paths))
'Set `config` property from global import config and make implied changes.'
def set_config(self, config):
iconfig = dict(config) self.config = iconfig if iconfig['incremental']: iconfig['resume'] = False if (self.query is not None): iconfig['resume'] = False iconfig['incremental'] = False if iconfig['move']: iconfig['copy'] = False iconfig['link'] = False ...
'Log a message about a given album to the importer log. The status should reflect the reason the album couldn\'t be tagged.'
def tag_log(self, status, paths):
self.logger.info(u'{0} {1}', status, displayable_path(paths))
'Logs the task\'s current choice if it should be logged. If ``duplicate``, then this is a secondary choice after a duplicate was detected and a decision was made.'
def log_choice(self, task, duplicate=False):
paths = task.paths if duplicate: if task.should_remove_duplicates: self.tag_log(u'duplicate-replace', paths) elif (task.choice_flag in (action.ASIS, action.APPLY)): self.tag_log(u'duplicate-keep', paths) elif (task.choice_flag is action.SKIP): self.tag...
'Run the import task.'
def run(self):
self.logger.info(u'import started {0}', time.asctime()) self.set_config(config['import']) if (self.query is None): stages = [read_tasks(self)] else: stages = [query_tasks(self)] if self.config['pretend']: stages += [log_files(self)] else: if (self.config['gr...
'Returns true if the files belonging to this task have already been imported in a previous session.'
def already_imported(self, toppath, paths):
if (self.is_resuming(toppath) and all([progress_element(toppath, p) for p in paths])): return True if (self.config['incremental'] and (tuple(paths) in self.history_dirs)): return True return False
'Return `True` if user wants to resume import of this path. You have to call `ask_resume` first to determine the return value.'
def is_resuming(self, toppath):
return self._is_resuming.get(toppath, False)
'If import of `toppath` was aborted in an earlier session, ask user if she wants to resume the import. Determines the return value of `is_resuming(toppath)`.'
def ask_resume(self, toppath):
if (self.want_resume and has_progress(toppath)): if ((self.want_resume is True) or self.should_resume(toppath)): log.warning(u'Resuming interrupted import of {0}', util.displayable_path(toppath)) self._is_resuming[toppath] = True else: progress_reset(t...
'Create a task. The primary fields that define a task are: * `toppath`: The user-specified base directory that contains the music for this task. If the task has *no* user-specified base (for example, when importing based on an -L query), this can be None. This is used for tracking progress and history. * `paths`: A lis...
def __init__(self, toppath, paths, items):
self.toppath = toppath self.paths = paths self.items = items
'Given an AlbumMatch or TrackMatch object or an action constant, indicates that an action has been selected for this task.'
def set_choice(self, choice):
assert (choice != action.APPLY) if (choice in (action.SKIP, action.ASIS, action.TRACKS, action.ALBUMS, action.RETAG)): self.choice_flag = choice self.match = None else: self.choice_flag = action.APPLY self.match = choice
'Updates the progress state to indicate that this album has finished.'
def save_progress(self):
if self.toppath: progress_add(self.toppath, *self.paths)
'Save the directory in the history for incremental imports.'
def save_history(self):
if self.paths: history_add(self.paths)
'Returns identifying metadata about the current choice. For albums, this is an (artist, album) pair. For items, this is (artist, title). May only be called when the choice flag is ASIS or RETAG (in which case the data comes from the files\' current metadata) or APPLY (data comes from the choice).'
def chosen_ident(self):
if (self.choice_flag in (action.ASIS, action.RETAG)): return (self.cur_artist, self.cur_album) elif (self.choice_flag is action.APPLY): return (self.match.info.artist, self.match.info.album)
'Return a list of Items that should be added to the library. If the tasks applies an album match the method only returns the matched items.'
def imported_items(self):
if (self.choice_flag in (action.ASIS, action.RETAG)): return list(self.items) elif (self.choice_flag == action.APPLY): return list(self.match.mapping.keys()) else: assert False
'Copy metadata from match info to the items.'
def apply_metadata(self):
autotag.apply_metadata(self.match.info, self.match.mapping)
'Save progress, clean up files, and emit plugin event.'
def finalize(self, session):
if session.want_resume: self.save_progress() if session.config['incremental']: self.save_history() self.cleanup(copy=session.config['copy'], delete=session.config['delete'], move=session.config['move']) if (not self.skip): self._emit_imported(session.lib)
'Remove and prune imported paths.'
def cleanup(self, copy=False, delete=False, move=False):
if self.skip: return items = self.imported_items() if (copy and delete): new_paths = [os.path.realpath(item.path) for item in items] for old_path in self.old_paths: if (old_path not in new_paths): util.remove(syspath(old_path), False) self....
'Send the `import_task_created` event for this task. Return a list of tasks that should continue through the pipeline. By default, this is a list containing only the task itself, but plugins can replace the task with new ones.'
def handle_created(self, session):
tasks = plugins.send('import_task_created', session=session, task=self) if (not tasks): tasks = [self] else: tasks = [t for inner in tasks for t in inner] return tasks
'Retrieve and store candidates for this album. User-specified candidate IDs are stored in self.search_ids: if present, the initial lookup is restricted to only those IDs.'
def lookup_candidates(self):
(artist, album, prop) = autotag.tag_album(self.items, search_ids=self.search_ids) self.cur_artist = artist self.cur_album = album self.candidates = prop.candidates self.rec = prop.recommendation
'Return a list of albums from `lib` with the same artist and album name as the task.'
def find_duplicates(self, lib):
(artist, album) = self.chosen_ident() if (artist is None): return [] duplicates = [] task_paths = set((i.path for i in self.items if i)) duplicate_query = dbcore.AndQuery((dbcore.MatchQuery('albumartist', artist), dbcore.MatchQuery('album', album))) for album in lib.albums(duplicate_quer...
'Make some album fields equal across `self.items`. For the RETAG action, we assume that the responsible for returning it (ie. a plugin) always ensures that the first item contains valid data on the relevant fields.'
def align_album_level_fields(self):
changes = {} if (self.choice_flag == action.ASIS): (plur_albumartist, freq) = util.plurality([(i.albumartist or i.artist) for i in self.items]) if ((freq == len(self.items)) or ((freq > 1) and ((float(freq) / len(self.items)) >= SINGLE_ARTIST_THRESH))): changes['albumartist'] = plur_...
'Add the items as an album to the library and remove replaced items.'
def add(self, lib):
self.align_album_level_fields() with lib.transaction(): self.record_replaced(lib) self.remove_replaced(lib) self.album = lib.add_album(self.imported_items()) self.reimport_metadata(lib)
'Records the replaced items and albums in the `replaced_items` and `replaced_albums` dictionaries.'
def record_replaced(self, lib):
self.replaced_items = defaultdict(list) self.replaced_albums = defaultdict(list) replaced_album_ids = set() for item in self.imported_items(): dup_items = list(lib.items(dbcore.query.BytesQuery('path', item.path))) self.replaced_items[item] = dup_items for dup_item in dup_items: ...
'For reimports, preserves metadata for reimported items and albums.'
def reimport_metadata(self, lib):
if self.is_album: replaced_album = self.replaced_albums.get(self.album.path) if replaced_album: self.album.added = replaced_album.added self.album.update(replaced_album._values_flex) self.album.artpath = replaced_album.artpath self.album.store() ...
'Removes all the items from the library that have the same path as an item from this task.'
def remove_replaced(self, lib):
for item in self.imported_items(): for dup_item in self.replaced_items[item]: log.debug(u'Replacing item {0}: {1}', dup_item.id, displayable_path(item.path)) dup_item.remove() log.debug(u'{0} of {1} items replaced', sum((bool(l) for l in self.replaced_items.v...
'Ask the session which match should apply and apply it.'
def choose_match(self, session):
choice = session.choose_match(self) self.set_choice(choice) session.log_choice(self)
'Reload albums and items from the database.'
def reload(self):
for item in self.imported_items(): item.load() self.album.load()
'Prune any empty directories above the given file. If this task has no `toppath` or the file path provided is not within the `toppath`, then this function has no effect. Similarly, if the file still exists, no pruning is performed, so it\'s safe to call when the file in question may not have been removed.'
def prune(self, filename):
if (self.toppath and (not os.path.exists(filename))): util.prune_dirs(os.path.dirname(filename), self.toppath, clutter=config['clutter'].as_str_seq())
'Return a list of items from `lib` that have the same artist and title as the task.'
def find_duplicates(self, lib):
(artist, title) = self.chosen_ident() found_items = [] query = dbcore.AndQuery((dbcore.MatchQuery('artist', artist), dbcore.MatchQuery('title', title))) for other_item in lib.items(query): if (other_item.path != self.item.path): found_items.append(other_item) return found_items
'Ask the session which match should apply and apply it.'
def choose_match(self, session):
choice = session.choose_item(self) self.set_choice(choice) session.log_choice(self)
'Returns true if the given path points to an archive that can be handled.'
@classmethod def is_archive(cls, path):
if (not os.path.isfile(path)): return False for (path_test, _) in cls.handlers(): if path_test(util.py3_path(path)): return True return False