desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Sends the "update" command to the MPD server indicated,
possibly authenticating with a password first.'
| def update_mpd(self, host='localhost', port=6600, password=None):
| self._log.info('Updating MPD database...')
try:
s = BufferedSocket(host, port)
except socket.error as e:
self._log.warning(u'MPD connection failed: {0}', six.text_type(e.strerror))
return
resp = s.readline()
if ('OK MPD' not in resp):
self._log.warni... |
'Get a list of file type classes from the Mutagen module.'
| @staticmethod
def _mutagen_classes():
| classes = []
for (modname, clsname) in _MUTAGEN_FORMATS.items():
mod = __import__('mutagen.{0}'.format(modname), fromlist=[clsname])
classes.append(getattr(mod, clsname))
return classes
|
'Remove all tags from a file.'
| def _scrub(self, path):
| for cls in self._mutagen_classes():
try:
f = cls(util.syspath(path))
except Exception:
continue
if (f.tags is None):
continue
try:
f.delete()
except NotImplementedError:
for tag in f.keys():
del f[tag... |
'Remove tags from an Item\'s associated file and, if `restore`
is enabled, write the database\'s tags back to the file.'
| def _scrub_item(self, item, restore=True):
| if restore:
try:
mf = mediafile.MediaFile(util.syspath(item.path), config['id3v23'].get(bool))
except mediafile.UnreadableFileError as exc:
self._log.error(u'could not open file to scrub: {0}', exc)
return
images = mf.images
self._scr... |
'Automatically scrub imported files.'
| def import_task_files(self, session, task):
| for item in task.imported_items():
self._log.debug(u'auto-scrubbing {0}', util.displayable_path(item.path))
self._scrub_item(item)
|
'The CLI command function for the `beet edit` command.'
| def _edit_command(self, lib, opts, args):
| query = ui.decargs(args)
(items, albums) = _do_query(lib, query, opts.album, False)
objs = (albums if opts.album else items)
if (not objs):
ui.print_(u'Nothing to edit.')
return
if opts.all:
fields = None
else:
fields = self._get_fields(opts.album, opts.fiel... |
'Get the set of fields to edit.'
| def _get_fields(self, album, extra):
| if album:
fields = self.config['albumfields'].as_str_seq()
else:
fields = self.config['itemfields'].as_str_seq()
if extra:
fields += extra
fields.append('id')
return set(fields)
|
'The core editor function.
- `album`: A flag indicating whether we\'re editing Items or Albums.
- `objs`: The `Item`s or `Album`s to edit.
- `fields`: The set of field names to edit (or None to edit
everything).'
| def edit(self, album, objs, fields):
| success = self.edit_objects(objs, fields)
if success:
self.save_changes(objs)
|
'Dump a set of Model objects to a file as text, ask the user
to edit it, and apply any changes to the objects.
Return a boolean indicating whether the edit succeeded.'
| def edit_objects(self, objs, fields):
| old_data = [flatten(o, fields) for o in objs]
if six.PY2:
new = NamedTemporaryFile(mode='w', suffix='.yaml', delete=False)
else:
new = NamedTemporaryFile(mode='w', suffix='.yaml', delete=False, encoding='utf-8')
old_str = dump(old_data)
new.write(old_str)
if six.PY2:
old_... |
'Take potentially-updated data and apply it to a set of Model
objects.
The objects are not written back to the database, so the changes
are temporary.'
| def apply_data(self, objs, old_data, new_data):
| if (len(old_data) != len(new_data)):
self._log.warning(u'number of objects changed from {} to {}', len(old_data), len(new_data))
obj_by_id = {o.id: o for o in objs}
ignore_fields = self.config['ignore_fields'].as_str_seq()
for (old_dict, new_dict) in zip(old_data, new_data):... |
'Save a list of updated Model objects to the database.'
| def save_changes(self, objs):
| for ob in objs:
if ob._dirty:
self._log.debug(u'saving changes to {}', ob)
ob.try_sync(ui.should_write(), ui.should_move())
|
'Append an "Edit" choice and an "edit Candidates" choice (if
there are candidates) to the interactive importer prompt.'
| def before_choose_candidate_listener(self, session, task):
| choices = [PromptChoice('d', 'eDit', self.importer_edit)]
if task.candidates:
choices.append(PromptChoice('c', 'edit Candidates', self.importer_edit_candidate))
return choices
|
'Callback for invoking the functionality during an interactive
import session on the *original* item tags.'
| def importer_edit(self, session, task):
| for (i, obj) in enumerate(task.items):
obj.id = (i + 1)
fields = self._get_fields(album=False, extra=[])
success = self.edit_objects(task.items, fields)
for obj in task.items:
obj.id = None
if success:
return action.RETAG
else:
for obj in task.items:
o... |
'Callback for invoking the functionality during an interactive
import session on a *candidate*. The candidate\'s metadata is
applied to the original items.'
| def importer_edit_candidate(self, session, task):
| sel = ui.input_options([], numrange=(1, len(task.candidates)))
task.match = task.candidates[(sel - 1)]
task.apply_metadata()
return self.importer_edit(session, task)
|
'Initiate the client with OAuth information.
For the initial authentication with the backend `auth_key` and
`auth_secret` can be `None`. Use `get_authorize_url` and
`get_access_token` to obtain them for subsequent uses of the API.
:param c_key: OAuth1 client key
:param c_secret: OAuth1 client secret
:param aut... | def __init__(self, c_key, c_secret, auth_key=None, auth_secret=None):
| self.api = OAuth1Session(client_key=c_key, client_secret=c_secret, resource_owner_key=auth_key, resource_owner_secret=auth_secret, callback_uri='oob')
self.api.headers = {'User-Agent': USER_AGENT}
|
'Generate the URL for the user to authorize the application.
Retrieves a request token from the Beatport API and returns the
corresponding authorization URL on their end that the user has
to visit.
This is the first step of the initial authorization process with the
API. Once the user has visited the URL, call
:py:meth... | def get_authorize_url(self):
| self.api.fetch_request_token(self._make_url('/identity/1/oauth/request-token'))
return self.api.authorization_url(self._make_url('/identity/1/oauth/authorize'))
|
'Obtain the final access token and secret for the API.
:param auth_data: URL-encoded authorization data as displayed at
the authorization url (obtained via
:py:meth:`get_authorize_url`) after signing in
:type auth_data: unicode
:returns: OAuth resource owner key and secret
:rtype: (unicode, u... | def get_access_token(self, auth_data):
| self.api.parse_authorization_response(('http://beets.io/auth?' + auth_data))
access_data = self.api.fetch_access_token(self._make_url('/identity/1/oauth/access-token'))
return (access_data['oauth_token'], access_data['oauth_token_secret'])
|
'Perform a search of the Beatport catalogue.
:param query: Query string
:param release_type: Type of releases to search for, can be
\'release\' or \'track\'
:param details: Retrieve additional information about the
search results. Currently this will fetch
the tracklist for releases and do nothing ... | def search(self, query, release_type='release', details=True):
| response = self._get('catalog/3/search', query=query, perPage=5, facets=['fieldType:{0}'.format(release_type)])
for item in response:
if (release_type == 'release'):
if details:
release = self.get_release(item['id'])
else:
release = BeatportRelease... |
'Get information about a single release.
:param beatport_id: Beatport ID of the release
:returns: The matching release
:rtype: :py:class:`BeatportRelease`'
| def get_release(self, beatport_id):
| response = self._get('/catalog/3/releases', id=beatport_id)
release = BeatportRelease(response[0])
release.tracks = self.get_release_tracks(beatport_id)
return release
|
'Get all tracks for a given release.
:param beatport_id: Beatport ID of the release
:returns: Tracks in the matching release
:rtype: list of :py:class:`BeatportTrack`'
| def get_release_tracks(self, beatport_id):
| response = self._get('/catalog/3/tracks', releaseId=beatport_id, perPage=100)
return [BeatportTrack(t) for t in response]
|
'Get information about a single track.
:param beatport_id: Beatport ID of the track
:returns: The matching track
:rtype: :py:class:`BeatportTrack`'
| def get_track(self, beatport_id):
| response = self._get('/catalog/3/tracks', id=beatport_id)
return BeatportTrack(response[0])
|
'Get complete URL for a given API endpoint.'
| def _make_url(self, endpoint):
| if (not endpoint.startswith('/')):
endpoint = ('/' + endpoint)
return (self._api_base + endpoint)
|
'Perform a GET request on a given API endpoint.
Automatically extracts result data from the response and converts HTTP
exceptions into :py:class:`BeatportAPIError` objects.'
| def _get(self, endpoint, **kwargs):
| try:
response = self.api.get(self._make_url(endpoint), params=kwargs)
except Exception as e:
raise BeatportAPIError('Error connecting to Beatport API: {}'.format(e.message))
if (not response):
raise BeatportAPIError("Error {0.status_code} for '{0.request.path_... |
'Get the path to the JSON file for storing the OAuth token.'
| def _tokenfile(self):
| return self.config['tokenfile'].get(confit.Filename(in_app_dir=True))
|
'Returns the beatport source weight and the maximum source weight
for albums.'
| def album_distance(self, items, album_info, mapping):
| dist = Distance()
if (album_info.data_source == 'Beatport'):
dist.add('source', self.config['source_weight'].as_number())
return dist
|
'Returns the beatport source weight and the maximum source weight
for individual tracks.'
| def track_distance(self, item, track_info):
| dist = Distance()
if (track_info.data_source == 'Beatport'):
dist.add('source', self.config['source_weight'].as_number())
return dist
|
'Returns a list of AlbumInfo objects for beatport search results
matching release and artist (if not various).'
| def candidates(self, items, artist, release, va_likely):
| if va_likely:
query = release
else:
query = ('%s %s' % (artist, release))
try:
return self._get_releases(query)
except BeatportAPIError as e:
self._log.debug(u'API Error: {0} (query: {1})', e, query)
return []
|
'Returns a list of TrackInfo objects for beatport search results
matching title and artist.'
| def item_candidates(self, item, artist, title):
| query = ('%s %s' % (artist, title))
try:
return self._get_tracks(query)
except BeatportAPIError as e:
self._log.debug(u'API Error: {0} (query: {1})', e, query)
return []
|
'Fetches a release by its Beatport ID and returns an AlbumInfo object
or None if the release is not found.'
| def album_for_id(self, release_id):
| self._log.debug(u'Searching for release {0}', release_id)
match = re.search('(^|beatport\\.com/release/.+/)(\\d+)$', release_id)
if (not match):
return None
release = self.client.get_release(match.group(2))
album = self._get_album_info(release)
return album
|
'Fetches a track by its Beatport ID and returns a TrackInfo object
or None if the track is not found.'
| def track_for_id(self, track_id):
| self._log.debug(u'Searching for track {0}', track_id)
match = re.search('(^|beatport\\.com/track/.+/)(\\d+)$', track_id)
if (not match):
return None
bp_track = self.client.get_track(match.group(2))
track = self._get_track_info(bp_track)
return track
|
'Returns a list of AlbumInfo objects for a beatport search query.'
| def _get_releases(self, query):
| query = re.sub('\\W+', ' ', query, flags=re.UNICODE)
query = re.sub('\\b(CD|disc)\\s*\\d+', '', query, flags=re.I)
albums = [self._get_album_info(x) for x in self.client.search(query)]
return albums
|
'Returns an AlbumInfo object for a Beatport Release object.'
| def _get_album_info(self, release):
| va = (len(release.artists) > 3)
(artist, artist_id) = self._get_artist(release.artists)
if va:
artist = u'Various Artists'
tracks = [self._get_track_info(x) for x in release.tracks]
return AlbumInfo(album=release.name, album_id=release.beatport_id, artist=artist, artist_id=artist_id, trac... |
'Returns a TrackInfo object for a Beatport Track object.'
| def _get_track_info(self, track):
| title = track.name
if (track.mix_name != u'Original Mix'):
title += u' ({0})'.format(track.mix_name)
(artist, artist_id) = self._get_artist(track.artists)
length = track.length.total_seconds()
return TrackInfo(title=title, track_id=track.beatport_id, artist=artist, artist_id=artist_id,... |
'Returns an artist string (all artists) and an artist_id (the main
artist) for a list of Beatport release or track artists.'
| def _get_artist(self, artists):
| artist_id = None
bits = []
for artist in artists:
if (not artist_id):
artist_id = artist[0]
name = artist[1]
name = re.sub(' \\(\\d+\\)$', '', name)
name = re.sub('^(.*?), (a|an|the)$', '\\2 \\1', name, flags=re.I)
bits.append(name)
artist = (... |
'Returns a list of TrackInfo objects for a Beatport query.'
| def _get_tracks(self, query):
| bp_tracks = self.client.search(query, release_type='track')
tracks = [self._get_track_info(x) for x in bp_tracks]
return tracks
|
'Populate `self.fields_to_progs` for a given field.
Do some sanity checks then compile the regexes.'
| def _set_pattern(self, field):
| if (field not in MediaFile.fields()):
self._log.error(u'invalid field: {0}', field)
elif (field in ('id', 'path', 'album_id')):
self._log.warning(u"field '{0}' ignored, zeroing it would be dangerous", field)
else:
try:
for pattern in self.config... |
'Set values in `tags` to `None` if the field is in
`self.fields_to_progs` and any of the corresponding `progs` matches the
field value.
Also update the `item` itself if `update_database` is set in the
config.'
| def set_fields(self, item, tags):
| fields_set = False
if (not self.fields_to_progs):
self._log.warning(u'no fields, nothing to do')
return False
for (field, progs) in self.fields_to_progs.items():
if (field in tags):
value = tags[field]
match = _match_progs(tags[field], progs)
... |
'Listens for beets db change and register the update for the end.'
| def listen_for_db_change(self, lib, model):
| self.register_listener('cli_exit', self.update)
|
'When the client exists try to send refresh request to Emby.'
| def update(self, lib):
| self._log.info(u'Updating Emby library...')
host = config['emby']['host'].get()
port = config['emby']['port'].get()
username = config['emby']['username'].get()
password = config['emby']['password'].get()
token = config['emby']['apikey'].get()
if (not any([password, token])):
se... |
'Listens for beets db change and register the update'
| def listen_for_db_change(self, lib, model):
| self.register_listener('cli_exit', self.update)
|
'When the client exists try to send refresh request to Kodi server.'
| def update(self, lib):
| self._log.info(u'Updating Kodi library...')
try:
update_kodi(config['kodi']['host'].get(), config['kodi']['port'].get(), config['kodi']['user'].get(), config['kodi']['pwd'].get())
self._log.info(u'... started.')
except requests.exceptions.RequestException:
self._log.warning(... |
'Process group of patterns (warn or skip) and returns True if
task is hated and not whitelisted.'
| @classmethod
def do_i_hate_this(cls, task, action_patterns):
| if action_patterns:
for query_string in action_patterns:
(query, _) = parse_query_string(query_string, (Album if task.is_album else Item))
if any((query.match(item) for item in task.imported_items())):
return True
return False
|
'Setup plugin from config options'
| def setup(self):
| if self.config['auto']:
self.import_stages = [self.imported]
self._genre_cache = {}
self.whitelist = set()
wl_filename = self.config['whitelist'].get()
if (wl_filename in (True, '')):
wl_filename = WHITELIST
if wl_filename:
wl_filename = normpath(wl_filename)
with... |
'A tuple of allowed genre sources. May contain \'track\',
\'album\', or \'artist.\''
| @property
def sources(self):
| source = self.config['source'].as_choice(('track', 'album', 'artist'))
if (source == 'track'):
return ('track', 'album', 'artist')
elif (source == 'album'):
return ('album', 'artist')
elif (source == 'artist'):
return ('artist',)
|
'Find the depth of a tag in the genres tree.'
| def _get_depth(self, tag):
| depth = None
for (key, value) in enumerate(self.c14n_branches):
if (tag in value):
depth = value.index(tag)
break
return depth
|
'Given a list of tags, sort the tags by their depths in the
genre tree.'
| def _sort_by_depth(self, tags):
| depth_tag_pairs = [(self._get_depth(t), t) for t in tags]
depth_tag_pairs = [e for e in depth_tag_pairs if (e[0] is not None)]
depth_tag_pairs.sort(reverse=True)
return [p[1] for p in depth_tag_pairs]
|
'Given a list of strings, return a genre by joining them into a
single string and (optionally) canonicalizing each.'
| def _resolve_genres(self, tags):
| if (not tags):
return None
count = self.config['count'].get(int)
if self.c14n_branches:
tags_all = []
for tag in tags:
if self.whitelist:
parents = [x for x in find_parents(tag, self.c14n_branches) if self._is_allowed(x)]
else:
... |
'Return the genre for a pylast entity or None if no suitable genre
can be found. Ex. \'Electronic, House, Dance\''
| def fetch_genre(self, lastfm_obj):
| min_weight = self.config['min_weight'].get(int)
return self._resolve_genres(self._tags_for(lastfm_obj, min_weight))
|
'Determine whether the genre is present in the whitelist,
returning a boolean.'
| def _is_allowed(self, genre):
| if (genre is None):
return False
if ((not self.whitelist) or (genre in self.whitelist)):
return True
return False
|
'Get a genre based on the named entity using the callable `method`
whose arguments are given in the sequence `args`. The genre lookup
is cached based on the entity name and the arguments. Before the
lookup, each argument is has some Unicode characters replaced with
rough ASCII equivalents in order to return better resu... | def _last_lookup(self, entity, method, *args):
| if any(((not s) for s in args)):
return None
key = u'{0}.{1}'.format(entity, u'-'.join((six.text_type(a) for a in args)))
if (key in self._genre_cache):
return self._genre_cache[key]
else:
args_replaced = []
for arg in args:
for (k, v) in REPLACE.items():
... |
'Return the album genre for this Item or Album.'
| def fetch_album_genre(self, obj):
| return self._last_lookup(u'album', LASTFM.get_album, obj.albumartist, obj.album)
|
'Return the album artist genre for this Item or Album.'
| def fetch_album_artist_genre(self, obj):
| return self._last_lookup(u'artist', LASTFM.get_artist, obj.albumartist)
|
'Returns the track artist genre for this Item.'
| def fetch_artist_genre(self, item):
| return self._last_lookup(u'artist', LASTFM.get_artist, item.artist)
|
'Returns the track genre for this Item.'
| def fetch_track_genre(self, obj):
| return self._last_lookup(u'track', LASTFM.get_track, obj.artist, obj.title)
|
'Get the genre string for an Album or Item object based on
self.sources. Return a `(genre, source)` pair. The
prioritization order is:
- track (for Items only)
- album
- artist
- original
- fallback
- None'
| def _get_genre(self, obj):
| if ((not self.config['force']) and self._is_allowed(obj.genre)):
return (obj.genre, 'keep')
if isinstance(obj, library.Item):
if ('track' in self.sources):
result = self.fetch_track_genre(obj)
if result:
return (result, 'track')
if ('album' in self.sou... |
'Event hook called when an import task finishes.'
| def imported(self, session, task):
| if task.is_album:
album = task.album
(album.genre, src) = self._get_genre(album)
self._log.debug(u'added last.fm album genre ({0}): {1}', src, album.genre)
album.store()
if ('track' in self.sources):
for item in album.items():
(item.... |
'Core genre identification routine.
Given a pylast entity (album or track), return a list of
tag names for that entity. Return an empty list if the entity is
not found or another error occurs.
If `min_weight` is specified, tags are filtered by weight.'
| def _tags_for(self, obj, min_weight=None):
| if isinstance(obj, pylast.Album):
obj = super(pylast.Album, obj)
try:
res = obj.get_top_tags()
except PYLAST_EXCEPTIONS as exc:
self._log.debug(u'last.fm error: {0}', exc)
return []
except Exception as exc:
self._log.debug(u'{}', traceback.format_exc())
... |
'Listens for beets db change and register the update for the end'
| def listen_for_db_change(self, lib, model):
| self.register_listener('cli_exit', self.update)
|
'When the client exists try to send refresh request to Plex server.'
| def update(self, lib):
| self._log.info(u'Updating Plex library...')
try:
update_plex(config['plex']['host'].get(), config['plex']['port'].get(), config['plex']['token'].get(), config['plex']['library_name'].get())
self._log.info(u'... started.')
except requests.exceptions.RequestException:
self._lo... |
'Given a Python expression or function body, compile it as a path
field function. The returned function takes a single argument, an
Item, and returns a Unicode string. If the expression cannot be
compiled, then an error is logged and this function returns None.'
| def compile_inline(self, python_code, album):
| try:
code = compile(u'({0})'.format(python_code), 'inline', 'eval')
except SyntaxError:
try:
func = _compile_func(python_code)
except SyntaxError:
self._log.error(u'syntax error in inline field definition:\n{0}', traceback.format_exc())
... |
'Connect to the MPD.'
| def connect(self):
| host = mpd_config['host'].as_str()
port = mpd_config['port'].get(int)
if (host[0] in ['/', '~']):
host = os.path.expanduser(host)
self._log.info(u'connecting to {0}:{1}', host, port)
try:
self.client.connect(host, port)
except socket.error as e:
raise ui.UserError(u... |
'Disconnect from the MPD.'
| def disconnect(self):
| self.client.close()
self.client.disconnect()
|
'Wrapper for requests to the MPD server. Tries to re-connect if the
connection was lost (f.ex. during MPD\'s library refresh).'
| def get(self, command, retries=RETRIES):
| try:
return getattr(self.client, command)()
except (select.error, mpd.ConnectionError) as err:
self._log.error(u'{0}', err)
if (retries <= 0):
raise ui.UserError(u'communication with MPD server failed')
time.sleep(RETRY_INTERVAL)
try:
self.disconnect()
... |
'Return the currently active playlist. Prefixes paths with the
music_directory, to get the absolute path.'
| def playlist(self):
| result = {}
for entry in self.get('playlistinfo'):
if (not is_url(entry['file'])):
result[entry['id']] = os.path.join(self.music_directory, entry['file'])
else:
result[entry['id']] = entry['file']
return result
|
'Return the current status of the MPD.'
| def status(self):
| return self.get('status')
|
'Return list of events. This may block a long time while waiting for
an answer from MPD.'
| def events(self):
| return self.get('idle')
|
'Calculate a new rating for a song based on play count, skip count,
old rating and the fact if it was skipped or not.'
| def rating(self, play_count, skip_count, rating, skipped):
| if skipped:
rolling = (rating - (rating / 2.0))
else:
rolling = (rating + ((1.0 - rating) / 2.0))
stable = ((play_count + 1.0) / ((play_count + skip_count) + 2.0))
return ((self.rating_mix * stable) + ((1.0 - self.rating_mix) * rolling))
|
'Return the beets item related to path.'
| def get_item(self, path):
| query = library.PathQuery('path', path)
item = self.lib.items(query).get()
if item:
return item
else:
self._log.info(u'item not found: {0}', displayable_path(path))
|
'Update the beets item. Set attribute to value or increment the value
of attribute. If the increment argument is used the value is cast to
the corresponding type.'
| def update_item(self, item, attribute, value=None, increment=None):
| if (item is None):
return
if (increment is not None):
item.load()
value = (type(increment)(item.get(attribute, 0)) + increment)
if (value is not None):
item[attribute] = value
item.store()
self._log.debug(u'updated: {0} = {1} [{2}]', attribute, ite... |
'Update the rating for a beets item. The `item` can either be a
beets `Item` or None. If the item is None, nothing changes.'
| def update_rating(self, item, skipped):
| if (item is None):
return
item.load()
rating = self.rating(int(item.get('play_count', 0)), int(item.get('skip_count', 0)), float(item.get('rating', 0.5)), skipped)
self.update_item(item, 'rating', rating)
|
'Determine if a song was skipped or not and update its attributes.
To this end the difference between the song\'s supposed end time
and the current time is calculated. If it\'s greater than a threshold,
the song is considered skipped.
Returns whether the change was manual (skipped previous song or not)'
| def handle_song_change(self, song):
| diff = abs((song['remaining'] - (time.time() - song['started'])))
skipped = (diff >= self.time_threshold)
if skipped:
self.handle_skipped(song)
else:
self.handle_played(song)
if self.do_rating:
self.update_rating(song['beets_item'], skipped)
return skipped
|
'Updates the play count of a song.'
| def handle_played(self, song):
| self.update_item(song['beets_item'], 'play_count', increment=1)
self._log.info(u'played {0}', displayable_path(song['path']))
|
'Updates the skip count of a song.'
| def handle_skipped(self, song):
| self.update_item(song['beets_item'], 'skip_count', increment=1)
self._log.info(u'skipped {0}', displayable_path(song['path']))
|
'Import hook for moving featuring artist automatically.'
| def imported(self, session, task):
| drop_feat = self.config['drop'].get(bool)
for item in task.imported_items():
self.ft_in_title(item, drop_feat)
item.store()
|
'Choose how to add new artists to the title and set the new
metadata. Also, print out messages about any changes that are made.
If `drop_feat` is set, then do not add the artist to the title; just
remove it from the artist field.'
| def update_metadata(self, item, feat_part, drop_feat):
| self._log.info(u'artist: {0} -> {1}', item.artist, item.albumartist)
item.artist = item.albumartist
if item.artist_sort:
(item.artist_sort, _) = split_on_feat(item.artist_sort)
if ((not drop_feat) and (not contains_feat(item.title))):
feat_format = self.config['format'].as_str()... |
'Look for featured artists in the item\'s artist fields and move
them to the title.'
| def ft_in_title(self, item, drop_feat):
| artist = item.artist.strip()
albumartist = item.albumartist.strip()
(_, featured) = split_on_feat(artist)
if (featured and (albumartist != artist) and albumartist):
self._log.info('{}', displayable_path(item.path))
feat_part = None
feat_part = find_feat_part(artist, albumartist)
... |
'Automatically embed art after art has been set'
| def process_album(self, album):
| if (self.config['auto'] and ui.should_write()):
max_width = self.config['maxwidth'].get(int)
art.embed_album(self._log, album, max_width, True, self.config['compare_threshold'].get(int), self.config['ifempty'].get(bool))
self.remove_artfile(album)
|
'Possibly delete the album art file for an album (if the
appropriate configuration option is enabled.'
| def remove_artfile(self, album):
| if (self.config['remove_art_file'] and album.artpath):
if os.path.isfile(album.artpath):
self._log.debug(u'Removing album art file for {0}', album)
os.remove(album.artpath)
album.artpath = None
album.store()
|
'Process Item `item`.'
| def _process_item(self, item, copy=False, move=False, delete=False, tag=False, fmt=u''):
| print_(format(item, fmt))
if copy:
item.move(basedir=copy, copy=True)
item.store()
if move:
item.move(basedir=move, copy=False)
item.store()
if delete:
item.remove(delete=True)
if tag:
try:
(k, v) = tag.split('=')
except Exception:
... |
'Run external `prog` on file path associated with `item`, cache
output as flexattr on a key that is the name of the program, and
return the key, checksum tuple.'
| def _checksum(self, item, prog):
| args = [p.format(file=item.path) for p in shlex.split(prog)]
key = args[0]
checksum = getattr(item, key, False)
if (not checksum):
self._log.debug(u'key {0} on item {1} not cached:computing checksum', key, displayable_path(item.path))
try:
checksum = comm... |
'Return a dictionary with keys arbitrary concatenations of attributes
and values lists of objects (Albums or Items) with those keys.
If strict, all attributes must be defined for a duplicate match.'
| def _group_by(self, objs, keys, strict):
| import collections
counts = collections.defaultdict(list)
for obj in objs:
values = [getattr(obj, k, None) for k in keys]
values = [v for v in values if (v not in (None, ''))]
if (strict and (len(values) < len(keys))):
self._log.debug(u'some keys {0} on item ... |
'Return the objects (Items or Albums) sorted by descending
order of priority.
If provided, the `tiebreak` dict indicates the field to use to
prioritize the objects. Otherwise, Items are placed in order of
"completeness" (objects with more non-null fields come first)
and Albums are ordered by their track count.'
| def _order(self, objs, tiebreak=None):
| if tiebreak:
kind = ('items' if all((isinstance(o, Item) for o in objs)) else 'albums')
key = (lambda x: tuple((getattr(x, k) for k in tiebreak[kind])))
else:
kind = (Item if all((isinstance(o, Item) for o in objs)) else Album)
if (kind is Item):
def truthy(v):
... |
'Merge Item objs by copying missing fields from items in the tail to
the head item.
Return same number of items, with the head item modified.'
| def _merge_items(self, objs):
| fields = Item.all_keys()
for f in fields:
for o in objs[1:]:
if (getattr(objs[0], f, None) in (None, '')):
value = getattr(o, f, None)
if value:
self._log.debug(u'key {0} on item {1} is null or empty: setting f... |
'Merge Album objs by copying missing items from albums in the tail
to the head album.
Return same number of albums, with the head album modified.'
| def _merge_albums(self, objs):
| ids = [i.mb_trackid for i in objs[0].items()]
for o in objs[1:]:
for i in o.items():
if (i.mb_trackid not in ids):
missing = Item.from_path(i.path)
missing.album_id = objs[0].id
missing.add(i._db)
self._log.debug(u'item {0} ... |
'Merge duplicate items. See ``_merge_items`` and ``_merge_albums``
for the relevant strategies.'
| def _merge(self, objs):
| kind = (Item if all((isinstance(o, Item) for o in objs)) else Album)
if (kind is Item):
objs = self._merge_items(objs)
else:
objs = self._merge_albums(objs)
return objs
|
'Generate triples of keys, duplicate counts, and constituent objects.'
| def _duplicates(self, objs, keys, full, strict, tiebreak, merge):
| offset = (0 if full else 1)
for (k, objs) in self._group_by(objs, keys, strict).items():
if (len(objs) > 1):
objs = self._order(objs, tiebreak)
if merge:
objs = self._merge(objs)
(yield (k, (len(objs) - offset), objs[offset:]))
|
'Instanciate queries for the playlists.
Each playlist has 2 queries: one or items one for albums, each with a
sort. We must also remember its name. _unmatched_playlists is a set of
tuples (name, (q, q_sort), (album_q, album_q_sort)).
sort may be any sort, or NullSort, or None. None and NullSort are
equivalent and both ... | def build_queries(self):
| self._unmatched_playlists = set()
self._matched_playlists = set()
for playlist in self.config['playlists'].get(list):
if ('name' not in playlist):
self._log.warning(u'playlist configuration is missing name')
continue
playlist_data = (playlist['name'],)
... |
'Write the given mtime to the destination path.'
| def write_file_mtime(self, path, mtime):
| stat = os.stat(util.syspath(path))
os.utime(util.syspath(path), (stat.st_atime, mtime))
|
'Write the given mtime to an item\'s `mtime` field and to the mtime
of the item\'s file.'
| def write_item_mtime(self, item, mtime):
| self.write_file_mtime(util.syspath(item.path), mtime)
item.mtime = mtime
|
'Record the file mtime of an item\'s path before its import.'
| def record_import_mtime(self, item, source, destination):
| mtime = os.stat(util.syspath(source)).st_mtime
self.item_mtime[destination] = mtime
self._log.debug(u"Recorded mtime {0} for item '{1}' imported from '{2}'", mtime, util.displayable_path(destination), util.displayable_path(source))
|
'Update the mtime of the item\'s file with the item.added value
after each write of the item if `preserve_write_mtimes` is enabled.'
| def update_after_write_time(self, item):
| if item.added:
if self.config['preserve_write_mtimes'].get(bool):
self.write_item_mtime(item, item.added)
self._log.debug(u"Write of item '{0}', selected item.added={1}", util.displayable_path(item.path), item.added)
|
'Creates a new coding formatter with the provided coding.'
| def __init__(self, coding):
| self._coding = coding
|
'Formats the provided string using the provided arguments and keyword
arguments.
This method decodes the format string using the formatter\'s coding.
See str.format and string.Formatter.format.'
| def format(self, format_string, *args, **kwargs):
| try:
format_string = format_string.decode(self._coding)
except UnicodeEncodeError:
pass
return super(CodingFormatter, self).format(format_string, *args, **kwargs)
|
'Converts the provided value given a conversion type.
This method decodes the converted value using the formatter\'s coding.
See string.Formatter.convert_field.'
| def convert_field(self, value, conversion):
| converted = super(CodingFormatter, self).convert_field(value, conversion)
try:
converted = converted.decode(self._coding)
except UnicodeEncodeError:
pass
return converted
|
'Test the output of the "print tracks" choice.'
| def test_print_tracks_output(self):
| self.matcher.matching = AutotagStub.BAD
with capture_stdout() as output:
with control_stdin('\n'.join(['p', 's'])):
self.importer.run()
tracklist = u'Print tracks? 01. Tag Title 1 - Tag Artist (0:01)\n02. Tag Title 2 - Tag Artist (0:01)'
... |
'Test the output of the "print tracks" choice, as singletons.'
| def test_print_tracks_output_as_tracks(self):
| self.matcher.matching = AutotagStub.BAD
with capture_stdout() as output:
with control_stdin('\n'.join(['t', 's', 'p', 's'])):
self.importer.run()
tracklist = u'Print tracks? 02. Tag Title 2 - Tag Artist (0:01)'
self.assertIn(tracklist, output.getvalue())
|
'Fetch genres with whitelist and c14n deactivated'
| def test_default(self):
| self._setup_config()
self.assertEqual(self.plugin._resolve_genres(['delta blues']), u'Delta Blues')
|
'Default c14n tree funnels up to most common genre except for *wrong*
genres that stay unchanged.'
| def test_c14n_only(self):
| self._setup_config(canonical=True, count=99)
self.assertEqual(self.plugin._resolve_genres(['delta blues']), u'Blues')
self.assertEqual(self.plugin._resolve_genres(['iota blues']), u'Iota Blues')
|
'Default whitelist rejects *wrong* (non existing) genres.'
| def test_whitelist_only(self):
| self._setup_config(whitelist=True)
self.assertEqual(self.plugin._resolve_genres(['iota blues']), u'')
|
'Default whitelist and c14n both activated result in all parents
genres being selected (from specific to common).'
| def test_whitelist_c14n(self):
| self._setup_config(canonical=True, whitelist=True, count=99)
self.assertEqual(self.plugin._resolve_genres(['delta blues']), u'Delta Blues, Blues')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.