funkwhale/api/funkwhale_api/music/importers.py

51 wiersze
1.7 KiB
Python
Czysty Zwykły widok Historia

def load(model, *args, **kwargs):
importer = registry[model.__name__](model=model)
return importer.load(*args, **kwargs)
2018-06-09 13:36:16 +00:00
EXCLUDE_VALIDATION = {"Track": ["artist"]}
class Importer(object):
def __init__(self, model):
self.model = model
def load(self, cleaned_data, raw_data, import_hooks):
2018-06-09 13:36:16 +00:00
mbid = cleaned_data.pop("mbid")
# let's validate data, just in case
instance = self.model(**cleaned_data)
exclude = EXCLUDE_VALIDATION.get(self.model.__name__, [])
2018-09-22 12:29:30 +00:00
instance.full_clean(exclude=["mbid", "uuid", "fid", "from_activity"] + exclude)
m = self.model.objects.update_or_create(mbid=mbid, defaults=cleaned_data)[0]
for hook in import_hooks:
hook(m, cleaned_data, raw_data)
return m
2018-06-09 13:36:16 +00:00
class Mapping(object):
"""Cast musicbrainz data to funkwhale data and vice-versa"""
2018-06-09 13:36:16 +00:00
def __init__(self, musicbrainz_mapping):
self.musicbrainz_mapping = musicbrainz_mapping
self._from_musicbrainz = {}
self._to_musicbrainz = {}
for field_name, conf in self.musicbrainz_mapping.items():
2018-06-09 13:36:16 +00:00
self._from_musicbrainz[conf["musicbrainz_field_name"]] = {
"field_name": field_name,
"converter": conf.get("converter", lambda v: v),
}
self._to_musicbrainz[field_name] = {
2018-06-09 13:36:16 +00:00
"field_name": conf["musicbrainz_field_name"],
"converter": conf.get("converter", lambda v: v),
}
2018-06-09 13:36:16 +00:00
def from_musicbrainz(self, key, value):
2018-06-09 13:36:16 +00:00
return (
self._from_musicbrainz[key]["field_name"],
self._from_musicbrainz[key]["converter"](value),
)
registry = {"Artist": Importer, "Track": Importer, "Album": Importer}