desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Fetch album art for each of the albums. This implements the manual fetchart CLI command.'
def batch_fetch_art(self, lib, albums, force):
for album in albums: if (album.artpath and (not force) and os.path.isfile(album.artpath)): message = ui.colorize('text_highlight_minor', u'has album art') else: local_paths = (None if force else [album.path]) candidate = self.art_for_album(album, local_paths...
'Command handler for the mbsync function.'
def func(self, lib, opts, args):
move = ui.should_move(opts.move) pretend = opts.pretend write = ui.should_write(opts.write) query = ui.decargs(args) self.singletons(lib, query, move, pretend, write) self.albums(lib, query, move, pretend, write)
'Retrieve and apply info from the autotagger for items matched by query.'
def singletons(self, lib, query, move, pretend, write):
for item in lib.items((query + [u'singleton:true'])): item_formatted = format(item) if (not item.mb_trackid): self._log.info(u'Skipping singleton with no mb_trackid: {0}', item_formatted) continue track_info = hooks.track_for_mbid(item.mb_trackid) ...
'Retrieve and apply info from the autotagger for albums matched by query and their items.'
def albums(self, lib, query, move, pretend, write):
for a in lib.albums(query): album_formatted = format(a) if (not a.mb_albumid): self._log.info(u'Skipping album with no mb_albumid: {0}', album_formatted) continue items = list(a.items()) album_info = hooks.album_for_mbid(a.mb_albumid) if...
'Fix the permissions for an imported Item or Album.'
def fix(self, lib, item=None, album=None):
file_perm = config['permissions']['file'].get() dir_perm = config['permissions']['dir'].get() file_perm = convert_perm(file_perm) dir_perm = convert_perm(dir_perm) file_chmod_queue = [] if item: file_chmod_queue.append(item.path) elif album: for album_item in album.items(): ...
'Returns a string to be used as the response code for the erring command.'
def response(self):
return self.template.substitute({'resp': RESP_ERR, 'code': self.code, 'index': self.index, 'cmd_name': self.cmd_name, 'message': self.message})
'Create a new server bound to address `host` and listening on port `port`. If `password` is given, it is required to do anything significant on the server.'
def __init__(self, host, port, password):
(self.host, self.port, self.password) = (host, port, password) self.random = False self.repeat = False self.volume = VOLUME_MAX self.crossfade = 0 self.playlist = [] self.playlist_version = 0 self.current_index = (-1) self.paused = False self.error = None self.random_obj = ra...
'Block and start listening for connections from clients. An interrupt (^C) closes the server.'
def run(self):
self.startup_time = time.time() bluelet.run(bluelet.server(self.host, self.port, Connection.handler(self)))
'An abstract method that should response lines containing a single song\'s metadata.'
def _item_info(self, item):
raise NotImplementedError
'An abstract method returning the integer id for an item.'
def _item_id(self, item):
raise NotImplementedError
'Searches the playlist for a song with the given id and returns its index in the playlist.'
def _id_to_index(self, track_id):
track_id = cast_arg(int, track_id) for (index, track) in enumerate(self.playlist): if (self._item_id(track) == track_id): return index raise ArgumentNotFoundError()
'Returns a random index different from the current one. If there are no songs in the playlist it returns -1. If there is only one song in the playlist it returns 0.'
def _random_idx(self):
if (len(self.playlist) < 2): return (len(self.playlist) - 1) new_index = self.random_obj.randint(0, (len(self.playlist) - 1)) while (new_index == self.current_index): new_index = self.random_obj.randint(0, (len(self.playlist) - 1)) return new_index
'Returns the index for the next song to play. It also considers random and repeat flags. No boundaries are checked.'
def _succ_idx(self):
if self.repeat: return self.current_index if self.random: return self._random_idx() return (self.current_index + 1)
'Returns the index for the previous song to play. It also considers random and repeat flags. No boundaries are checked.'
def _prev_idx(self):
if self.repeat: return self.current_index if self.random: return self._random_idx() return (self.current_index - 1)
'Succeeds.'
def cmd_ping(self, conn):
pass
'Exits the server process.'
def cmd_kill(self, conn):
exit(0)
'Closes the connection.'
def cmd_close(self, conn):
raise BPDClose()
'Attempts password authentication.'
def cmd_password(self, conn, password):
if (password == self.password): conn.authenticated = True else: conn.authenticated = False raise BPDError(ERROR_PASSWORD, u'incorrect password')
'Lists the commands available to the user.'
def cmd_commands(self, conn):
if (self.password and (not conn.authenticated)): for cmd in SAFE_COMMANDS: (yield (u'command: ' + cmd)) else: for func in dir(self): if func.startswith('cmd_'): (yield (u'command: ' + func[4:]))
'Lists all unavailable commands.'
def cmd_notcommands(self, conn):
if (self.password and (not conn.authenticated)): for func in dir(self): if func.startswith('cmd_'): cmd = func[4:] if (cmd not in SAFE_COMMANDS): (yield (u'command: ' + cmd)) else: pass
'Returns some status information for use with an implementation of cmd_status. Gives a list of response-lines for: volume, repeat, random, playlist, playlistlength, and xfade.'
def cmd_status(self, conn):
(yield ((u'volume: ' + six.text_type(self.volume)), (u'repeat: ' + six.text_type(int(self.repeat))), (u'random: ' + six.text_type(int(self.random))), (u'playlist: ' + six.text_type(self.playlist_version)), (u'playlistlength: ' + six.text_type(len(self.playlist))), (u'xfade: ' + six.text_type(self....
'Removes the persistent error state of the server. This error is set when a problem arises not in response to a command (for instance, when playing a file).'
def cmd_clearerror(self, conn):
self.error = None
'Set or unset random (shuffle) mode.'
def cmd_random(self, conn, state):
self.random = cast_arg('intbool', state)
'Set or unset repeat mode.'
def cmd_repeat(self, conn, state):
self.repeat = cast_arg('intbool', state)
'Set the player\'s volume level (0-100).'
def cmd_setvol(self, conn, vol):
vol = cast_arg(int, vol) if ((vol < VOLUME_MIN) or (vol > VOLUME_MAX)): raise BPDError(ERROR_ARG, u'volume out of range') self.volume = vol
'Set the number of seconds of crossfading.'
def cmd_crossfade(self, conn, crossfade):
crossfade = cast_arg(int, crossfade) if (crossfade < 0): raise BPDError(ERROR_ARG, u'crossfade time must be nonnegative')
'Clear the playlist.'
def cmd_clear(self, conn):
self.playlist = [] self.playlist_version += 1 self.cmd_stop(conn)
'Remove the song at index from the playlist.'
def cmd_delete(self, conn, index):
index = cast_arg(int, index) try: del self.playlist[index] except IndexError: raise ArgumentIndexError() self.playlist_version += 1 if (self.current_index == index): self.cmd_stop(conn) elif (index < self.current_index): self.current_index -= 1
'Move a track in the playlist.'
def cmd_move(self, conn, idx_from, idx_to):
idx_from = cast_arg(int, idx_from) idx_to = cast_arg(int, idx_to) try: track = self.playlist.pop(idx_from) self.playlist.insert(idx_to, track) except IndexError: raise ArgumentIndexError() if (idx_from == self.current_index): self.current_index = idx_to elif (idx_...
'Swaps two tracks in the playlist.'
def cmd_swap(self, conn, i, j):
i = cast_arg(int, i) j = cast_arg(int, j) try: track_i = self.playlist[i] track_j = self.playlist[j] except IndexError: raise ArgumentIndexError() self.playlist[j] = track_i self.playlist[i] = track_j if (self.current_index == i): self.current_index = j el...
'Indicates supported URL schemes. None by default.'
def cmd_urlhandlers(self, conn):
pass
'Gives metadata information about the entire playlist or a single track, given by its index.'
def cmd_playlistinfo(self, conn, index=(-1)):
index = cast_arg(int, index) if (index == (-1)): for track in self.playlist: (yield self._item_info(track)) else: try: track = self.playlist[index] except IndexError: raise ArgumentIndexError() (yield self._item_info(track))
'Sends playlist changes since the given version. This is a "fake" implementation that ignores the version and just returns the entire playlist (rather like version=0). This seems to satisfy many clients.'
def cmd_plchanges(self, conn, version):
return self.cmd_playlistinfo(conn)
'Like plchanges, but only sends position and id. Also a dummy implementation.'
def cmd_plchangesposid(self, conn, version):
for (idx, track) in enumerate(self.playlist): (yield (u'cpos: ' + six.text_type(idx))) (yield (u'Id: ' + six.text_type(track.id)))
'Sends information about the currently-playing song.'
def cmd_currentsong(self, conn):
if (self.current_index != (-1)): track = self.playlist[self.current_index] (yield self._item_info(track))
'Advance to the next song in the playlist.'
def cmd_next(self, conn):
self.current_index = self._succ_idx() if (self.current_index >= len(self.playlist)): return self.cmd_stop(conn) else: return self.cmd_play(conn)
'Step back to the last song.'
def cmd_previous(self, conn):
self.current_index = self._prev_idx() if (self.current_index < 0): return self.cmd_stop(conn) else: return self.cmd_play(conn)
'Set the pause state playback.'
def cmd_pause(self, conn, state=None):
if (state is None): self.paused = (not self.paused) else: self.paused = cast_arg('intbool', state)
'Begin playback, possibly at a specified playlist index.'
def cmd_play(self, conn, index=(-1)):
index = cast_arg(int, index) if ((index < (-1)) or (index > len(self.playlist))): raise ArgumentIndexError() if (index == (-1)): if (not self.playlist): return self.cmd_stop(conn) if (self.current_index == (-1)): self.current_index = 0 else: self.c...
'Stop playback.'
def cmd_stop(self, conn):
self.current_index = (-1) self.paused = False
'Seek to a specified point in a specified song.'
def cmd_seek(self, conn, index, pos):
index = cast_arg(int, index) if ((index < 0) or (index >= len(self.playlist))): raise ArgumentIndexError() self.current_index = index
'Memory profiling for debugging.'
def cmd_profile(self, conn):
from guppy import hpy heap = hpy().heap() print(heap)
'Create a new connection for the accepted socket `client`.'
def __init__(self, server, sock):
self.server = server self.sock = sock self.authenticated = False
'Send lines, which which is either a single string or an iterable consisting of strings, to the client. A newline is added after every string. Returns a Bluelet event that sends the data.'
def send(self, lines):
if isinstance(lines, six.string_types): lines = [lines] out = (NEWLINE.join(lines) + NEWLINE) log.debug('{}', out[:(-1)]) if isinstance(out, six.text_type): out = out.encode('utf-8') return self.sock.sendall(out)
'A coroutine that runs the given command and sends an appropriate response.'
def do_command(self, command):
try: (yield bluelet.call(command.run(self))) except BPDError as e: (yield self.send(e.response())) else: (yield self.send(RESP_OK))
'Send a greeting to the client and begin processing commands as they arrive.'
def run(self):
(yield self.send(HELLO)) clist = None while True: line = (yield self.sock.readline()) if (not line): break line = line.strip() if (not line): break line = line.decode('utf8') log.debug(u'{}', line) if (clist is not None): ...
'Creates a new `Command` from the given string, `s`, parsing the string for command name and arguments.'
def __init__(self, s):
command_match = self.command_re.match(s) self.name = command_match.group(1) self.args = [] arg_matches = self.arg_re.findall(s[command_match.end():]) for match in arg_matches: if match[0]: arg = match[0] arg = arg.replace(u'\\"', u'"').replace(u'\\\\', u'\\') ...
'A coroutine that executes the command on the given connection.'
def run(self, conn):
func_name = ('cmd_' + self.name) if (not hasattr(conn.server, func_name)): raise BPDError(ERROR_UNKNOWN, u'unknown command', self.name) func = getattr(conn.server, func_name) if (conn.server.password and (not conn.authenticated) and (self.name not in SAFE_COMMANDS)): raise BPDError(ER...
'Create a new `CommandList` from the given sequence of `Command`s. If `verbose`, this is a verbose command list.'
def __init__(self, sequence=None, verbose=False):
if sequence: for item in sequence: self.append(item) self.verbose = verbose
'Coroutine executing all the commands in this list.'
def run(self, conn):
for (i, command) in enumerate(self): try: (yield bluelet.call(command.run(conn))) except BPDError as e: e.index = i raise e if self.verbose: (yield conn.send(RESP_CLIST_VERBOSE))
'A callback invoked every time our player finishes a track.'
def play_finished(self):
self.cmd_next(None)
'Updates the catalog to reflect the current database state.'
def cmd_update(self, conn, path=u'/'):
print(u'Building directory tree...') self.tree = vfs.libtree(self.lib) print(u'... done.') self.updated_time = time.time()
'Returns a VFS node or an item ID located at the path given. If the path does not exist, raises a'
def _resolve_path(self, path):
components = path.split(u'/') node = self.tree for component in components: if (not component): continue if isinstance(node, int): raise ArgumentNotFoundError() if (component in node.files): node = node.files[component] elif (component in n...
'Smashes together two BPD paths.'
def _path_join(self, p1, p2):
out = ((p1 + u'/') + p2) return out.replace(u'//', u'/').replace(u'//', u'/')
'Sends info on all the items in the path.'
def cmd_lsinfo(self, conn, path=u'/'):
node = self._resolve_path(path) if isinstance(node, int): raise BPDError(ERROR_ARG, u'this is not a directory') else: for (name, itemid) in iter(sorted(node.files.items())): item = self.lib.get_item(itemid) (yield self._item_info(item)) for (name, ...
'Helper function for recursive listing. If info, show tracks\' complete info; otherwise, just show items\' paths.'
def _listall(self, basepath, node, info=False):
if isinstance(node, int): if info: item = self.lib.get_item(node) (yield self._item_info(item)) else: (yield (u'file: ' + basepath)) else: for (name, itemid) in sorted(node.files.items()): newpath = self._path_join(basepath, name) ...
'Send the paths all items in the directory, recursively.'
def cmd_listall(self, conn, path=u'/'):
return self._listall(path, self._resolve_path(path), False)
'Send info on all the items in the directory, recursively.'
def cmd_listallinfo(self, conn, path=u'/'):
return self._listall(path, self._resolve_path(path), True)
'Generator yielding all items under a VFS node.'
def _all_items(self, node):
if isinstance(node, int): (yield self.lib.get_item(node)) else: for (name, itemid) in sorted(node.files.items()): for v in self._all_items(itemid): (yield v) for (name, subdir) in sorted(node.dirs.items()): for v in self._all_items(subdir): ...
'Adds a track or directory to the playlist, specified by the path. If `send_id`, write each item\'s id to the client.'
def _add(self, path, send_id=False):
for item in self._all_items(self._resolve_path(path)): self.playlist.append(item) if send_id: (yield (u'Id: ' + six.text_type(item.id))) self.playlist_version += 1
'Adds a track or directory to the playlist, specified by a path.'
def cmd_add(self, conn, path):
return self._add(path, False)
'Same as `cmd_add` but sends an id back to the client.'
def cmd_addid(self, conn, path):
return self._add(path, True)
'Sends some statistics about the library.'
def cmd_stats(self, conn):
with self.lib.transaction() as tx: statement = 'SELECT COUNT(DISTINCT artist), COUNT(DISTINCT album), COUNT(id), SUM(length) FROM items' (artists, albums, songs, totaltime) = tx.query(statement)[0] (yield ((u'artists: ' + six.text_type(artists)), (u'albums: ' + six....
'Returns a list of the metadata (tag) fields available for searching.'
def cmd_tagtypes(self, conn):
for tag in self.tagtype_map: (yield (u'tagtype: ' + tag))
'Uses `tagtype_map` to look up the beets column name for an MPD tagtype (or throw an appropriate exception). Returns both the canonical name of the MPD tagtype and the beets column name.'
def _tagtype_lookup(self, tag):
for (test_tag, key) in self.tagtype_map.items(): if (test_tag.lower() == tag.lower()): return (test_tag, key) raise BPDError(ERROR_UNKNOWN, u'no such tagtype')
'Helper function returns a query object that will find items according to the library query type provided and the key-value pairs specified. The any_query_type is used for queries of type "any"; if None, then an error is thrown.'
def _metadata_query(self, query_type, any_query_type, kv):
if kv: queries = [] it = iter(kv) for (tag, value) in zip(it, it): if (tag.lower() == u'any'): if any_query_type: queries.append(any_query_type(value, ITEM_KEYS_WRITABLE, query_type)) else: raise BPDError(ERR...
'Perform a substring match for items.'
def cmd_search(self, conn, *kv):
query = self._metadata_query(dbcore.query.SubstringQuery, dbcore.query.AnyFieldQuery, kv) for item in self.lib.items(query): (yield self._item_info(item))
'Perform an exact match for items.'
def cmd_find(self, conn, *kv):
query = self._metadata_query(dbcore.query.MatchQuery, None, kv) for item in self.lib.items(query): (yield self._item_info(item))
'List distinct metadata values for show_tag, possibly filtered by matching match_tag to match_term.'
def cmd_list(self, conn, show_tag, *kv):
(show_tag_canon, show_key) = self._tagtype_lookup(show_tag) query = self._metadata_query(dbcore.query.MatchQuery, None, kv) (clause, subvals) = query.clause() statement = ((((('SELECT DISTINCT ' + show_key) + ' FROM items WHERE ') + clause) + ' ORDER BY ') + show_key) with...
'Returns the number and total time of songs matching the tag/value query.'
def cmd_count(self, conn, tag, value):
(_, key) = self._tagtype_lookup(tag) songs = 0 playtime = 0.0 for item in self.lib.items(dbcore.query.MatchQuery(key, value)): songs += 1 playtime += item.length (yield (u'songs: ' + six.text_type(songs))) (yield (u'playtime: ' + six.text_type(int(playtime))))
'List the available outputs.'
def cmd_outputs(self, conn):
(yield (u'outputid: 0', u'outputname: gstreamer', u'outputenabled: 1'))
'Seeks to the specified position in the specified song.'
def cmd_seek(self, conn, index, pos):
index = cast_arg(int, index) pos = cast_arg(int, pos) super(Server, self).cmd_seek(conn, index, pos) self.player.seek(pos)
'Starts a BPD server.'
def start_bpd(self, lib, host, port, password, volume, debug):
if debug: self._log.setLevel(logging.DEBUG) else: self._log.setLevel(logging.WARNING) try: server = Server(lib, host, port, password) server.cmd_setvol(None, volume) server.run() except NoGstreamerError: global_log.error(u'Gstreamer Python bindings ...
'Initialize a player. If a finished_callback is provided, it is called every time a track started with play_file finishes. Once the player has been created, call run() to begin the main runloop in a separate thread.'
def __init__(self, finished_callback=None):
self.player = Gst.ElementFactory.make('playbin', 'player') if (self.player is None): raise ui.UserError('Could not create playbin') fakesink = Gst.ElementFactory.make('fakesink', 'fakesink') if (fakesink is None): raise ui.UserError('Could not create fakesink') self...
'Returns the current state flag of the playbin.'
def _get_state(self):
return self.player.get_state(Gst.CLOCK_TIME_NONE)[1]
'Callback for status updates from GStreamer.'
def _handle_message(self, bus, message):
if (message.type == Gst.MessageType.EOS): self.player.set_state(Gst.State.NULL) self.playing = False self.cached_time = None if self.finished_callback: self.finished_callback() elif (message.type == Gst.MessageType.ERROR): self.player.set_state(Gst.State.NULL)...
'Set the volume level to a value in the range [0, 1.5].'
def _set_volume(self, volume):
self._volume = volume self.player.set_property('volume', volume)
'Get the volume as a float in the range [0, 1.5].'
def _get_volume(self):
return self._volume
'Immediately begin playing the audio file at the given path.'
def play_file(self, path):
self.player.set_state(Gst.State.NULL) if isinstance(path, six.text_type): path = path.encode('utf-8') uri = ('file://' + urllib.parse.quote(path)) self.player.set_property('uri', uri) self.player.set_state(Gst.State.PLAYING) self.playing = True
'If paused, resume playback.'
def play(self):
if (self._get_state() == Gst.State.PAUSED): self.player.set_state(Gst.State.PLAYING) self.playing = True
'Pause playback.'
def pause(self):
self.player.set_state(Gst.State.PAUSED)
'Halt playback.'
def stop(self):
self.player.set_state(Gst.State.NULL) self.playing = False self.cached_time = None
'Start a new thread for the player. Call this function before trying to play any music with play_file() or play().'
def run(self):
def start(): loop = GLib.MainLoop() loop.run() _thread.start_new_thread(start, ())
'Returns a tuple containing (position, length) where both values are integers in seconds. If no stream is available, returns (0, 0).'
def time(self):
fmt = Gst.Format(Gst.Format.TIME) try: posq = self.player.query_position(fmt) if (not posq[0]): raise QueryError('query_position failed') pos = (posq[1] // (10 ** 9)) lengthq = self.player.query_duration(fmt) if (not lengthq[0]): raise QueryErro...
'Seeks to position (in seconds).'
def seek(self, position):
(cur_pos, cur_len) = self.time() if (position > cur_len): self.stop() return fmt = Gst.Format(Gst.Format.TIME) ns = (position * (10 ** 9)) self.player.seek_simple(fmt, Gst.SeekFlags.FLUSH, ns) self.cached_time = (position, cur_len)
'Block until playing finishes.'
def block(self):
while self.playing: time.sleep(1)
'Encode `source` to `dest` using command template `command`. Raises `subprocess.CalledProcessError` if the command exited with a non-zero status code.'
def encode(self, command, source, dest, pretend=False):
assert isinstance(command, bytes) assert isinstance(source, bytes) assert isinstance(dest, bytes) quiet = self.config['quiet'].get(bool) if ((not quiet) and (not pretend)): self._log.info(u'Encoding {0}', util.displayable_path(source)) if (not six.PY2): command = command.decod...
'A pipeline thread that converts `Item` objects from a library.'
def convert_item(self, dest_dir, keep_new, path_formats, fmt, pretend=False):
(command, ext) = get_format(fmt) (item, original, converted) = (None, None, None) while True: item = (yield (item, original, converted)) dest = item.destination(basedir=dest_dir, path_formats=path_formats) if keep_new: original = dest converted = item.path ...
'Copies or converts the associated cover art of the album. Album must have at least one track.'
def copy_album_art(self, album, dest_dir, path_formats, pretend=False):
if ((not album) or (not album.artpath)): return album_item = album.items().get() if (not album_item): return dest = album_item.destination(basedir=dest_dir, path_formats=path_formats) dest = os.path.join(*util.components(dest)[:(-1)]) dest = album.art_destination(album.artpath, i...
'Transcode a file automatically after it is imported into the library.'
def convert_on_import(self, lib, item):
fmt = self.config['format'].as_str().lower() if should_transcode(item, fmt): (command, ext) = get_format() tmpdir = self.config['tmpdir'].get() if tmpdir: tmpdir = util.py3_path(util.bytestring_path(tmpdir)) (fd, dest) = tempfile.mkstemp(util.py3_path(('.' + ext)), di...
'Print a listing of tracks missing from each album in the library matching query.'
def _missing_tracks(self, lib, query):
albums = lib.albums(query) count = self.config['count'].get() total = self.config['total'].get() fmt = config[('format_album' if count else 'format_item')].get() if total: print(sum([_missing_count(a) for a in albums])) return if count: fmt += ': $missing' for albu...
'Print a listing of albums missing from each artist in the library matching query.'
def _missing_albums(self, lib, query):
total = self.config['total'].get() albums = lib.albums(query) albums_by_artist = defaultdict(list) for alb in albums: artist = (alb['albumartist'], alb['mb_albumartistid']) albums_by_artist[artist].append(alb) total_missing = 0 for (artist, albums) in albums_by_artist.items(): ...
'Query MusicBrainz to determine items missing from `album`.'
def _missing(self, album):
item_mbids = [x.mb_trackid for x in album.items()] if (len([i for i in album.items()]) < album.albumtotal): album_info = hooks.album_for_mbid(album.mb_albumid) for track_info in getattr(album_info, 'tracks', []): if (track_info.track_id not in item_mbids): item = _ite...
'Function is called upon beet import.'
def import_task_files(self, session, task):
self._fetch_info(task.imported_items(), False, True)
'Fetch additional information from AcousticBrainz for the `item`s.'
def _fetch_info(self, items, write, force):
for item in items: if (not force): mood_str = item.get('mood_acoustic', u'') if mood_str: self._log.info(u'data already present for: {}', item) continue if (not item.mb_trackid): continue self._log.info(u'getting...
'Given `data` as a structure of nested dictionaries, and `scheme` as a structure of nested dictionaries , `yield` tuples `(attr, val)` where `attr` and `val` are corresponding leaf nodes in `scheme` and `data`. As its name indicates, `scheme` defines how the data is structured, so this function tries to find leaf nodes...
def _map_data_to_scheme(self, data, scheme):
composites = defaultdict(list) for (attr, val) in self._data_to_scheme_child(data, scheme, composites): (yield (attr, val)) for (composite_attr, value_parts) in composites.items(): (yield (composite_attr, ' '.join(value_parts)))
'The recursive business logic of :meth:`_map_data_to_scheme`: Traverse two structures of nested dictionaries in parallel and `yield` tuples of corresponding leaf nodes. If a leaf node belongs to a composite attribute (is a `tuple`), populate `composites` rather than yielding straight away. All the child functions for a...
def _data_to_scheme_child(self, subdata, subscheme, composites):
for (k, v) in subscheme.items(): if (k in subdata): if (type(v) == dict): for (attr, val) in self._data_to_scheme_child(subdata[k], v, composites): (yield (attr, val)) elif (type(v) == tuple): (composite_attribute, part_number) = v ...
'Command handler for the metasync function.'
def func(self, lib, opts, args):
pretend = opts.pretend query = ui.decargs(args) sources = [] for source in opts.sources: sources.extend(source.split(',')) sources = (sources or self.config['source'].as_str_seq()) meta_source_instances = {} items = lib.items(query) if (not items): self._log.info(u'No ...
'Returns a new library with only albums/items added to ipfs'
def ipfs_added_albums(self, rlib, tmpname):
tmplib = library.Library(tmpname) for album in rlib.albums(): try: if album.ipfs: self.create_new_album(album, tmplib) except AttributeError: pass return tmplib
'Records relative paths to the given items for each feed format'
def _record_items(self, lib, basename, items):
feedsdir = bytestring_path(self.config['dir'].as_filename()) formats = self.config['formats'].as_str_seq() relative_to = (self.config['relative_to'].get() or self.config['dir'].as_filename()) relative_to = bytestring_path(relative_to) paths = [] for item in items: if self.config['absolut...