| 1 |
import base64 |
| 2 |
|
| 3 |
import mutagen |
| 4 |
import mutagen.flac |
| 5 |
|
| 6 |
from mediafile.utils import Image |
| 7 |
|
| 8 |
from .base import ListStorageStyle |
| 9 |
|
| 10 |
|
| 11 |
class VorbisImageStorageStyle(ListStorageStyle): |
| 12 |
"""Store images in Vorbis comments. Both legacy COVERART fields and |
| 13 |
modern METADATA_BLOCK_PICTURE tags are supported. Data is |
| 14 |
base64-encoded. Values are `Image` objects. |
| 15 |
""" |
| 16 |
|
| 17 |
formats = ["OggOpus", "OggTheora", "OggSpeex", "OggVorbis", "OggFlac"] |
| 18 |
|
| 19 |
def __init__(self): |
| 20 |
super().__init__(key="metadata_block_picture") |
| 21 |
self.as_type = bytes |
| 22 |
|
| 23 |
def fetch(self, mutagen_file): |
| 24 |
images = [] |
| 25 |
if "metadata_block_picture" not in mutagen_file: |
| 26 |
# Try legacy COVERART tags. |
| 27 |
if "coverart" in mutagen_file: |
| 28 |
for data in mutagen_file["coverart"]: |
| 29 |
images.append(Image(base64.b64decode(data))) |
| 30 |
return images |
| 31 |
for data in mutagen_file["metadata_block_picture"]: |
| 32 |
try: |
| 33 |
pic = mutagen.flac.Picture(base64.b64decode(data)) |
| 34 |
except (TypeError, AttributeError): |
| 35 |
continue |
| 36 |
images.append(Image(data=pic.data, desc=pic.desc, type=pic.type)) |
| 37 |
return images |
| 38 |
|
| 39 |
def store(self, mutagen_file, image_data): |
| 40 |
# Strip all art, including legacy COVERART. |
| 41 |
if "coverart" in mutagen_file: |
| 42 |
del mutagen_file["coverart"] |
| 43 |
if "coverartmime" in mutagen_file: |
| 44 |
del mutagen_file["coverartmime"] |
| 45 |
super().store(mutagen_file, image_data) |
| 46 |
|
| 47 |
def serialize(self, image): |
| 48 |
"""Turn a Image into a base64 encoded FLAC picture block.""" |
| 49 |
pic = mutagen.flac.Picture() |
| 50 |
pic.data = image.data |
| 51 |
pic.type = image.type_index |
| 52 |
pic.mime = image.mime_type |
| 53 |
pic.desc = image.desc or "" |
| 54 |
|
| 55 |
# Encoding with base64 returns bytes on both Python 2 and 3. |
| 56 |
# Mutagen requires the data to be a Unicode string, so we decode |
| 57 |
# it before passing it along. |
| 58 |
return base64.b64encode(pic.write()).decode("ascii") |