| 1 |
from mediafile.utils import sc_decode, sc_encode |
| 2 |
|
| 3 |
|
| 4 |
class StorageStyle: |
| 5 |
"""A strategy for storing a value for a certain tag format (or set |
| 6 |
of tag formats). This basic StorageStyle describes simple 1:1 |
| 7 |
mapping from raw values to keys in a Mutagen file object; subclasses |
| 8 |
describe more sophisticated translations or format-specific access |
| 9 |
strategies. |
| 10 |
|
| 11 |
MediaFile uses a StorageStyle via three methods: ``get()``, |
| 12 |
``set()``, and ``delete()``. It passes a Mutagen file object to |
| 13 |
each. |
| 14 |
|
| 15 |
Internally, the StorageStyle implements ``get()`` and ``set()`` |
| 16 |
using two steps that may be overridden by subtypes. To get a value, |
| 17 |
the StorageStyle first calls ``fetch()`` to retrieve the value |
| 18 |
corresponding to a key and then ``deserialize()`` to convert the raw |
| 19 |
Mutagen value to a consumable Python value. Similarly, to set a |
| 20 |
field, we call ``serialize()`` to encode the value and then |
| 21 |
``store()`` to assign the result into the Mutagen object. |
| 22 |
|
| 23 |
Each StorageStyle type has a class-level `formats` attribute that is |
| 24 |
a list of strings indicating the formats that the style applies to. |
| 25 |
MediaFile only uses StorageStyles that apply to the correct type for |
| 26 |
a given audio file. |
| 27 |
""" |
| 28 |
|
| 29 |
formats = [ |
| 30 |
"FLAC", |
| 31 |
"OggOpus", |
| 32 |
"OggTheora", |
| 33 |
"OggSpeex", |
| 34 |
"OggVorbis", |
| 35 |
"OggFlac", |
| 36 |
"APEv2File", |
| 37 |
"WavPack", |
| 38 |
"Musepack", |
| 39 |
"MonkeysAudio", |
| 40 |
] |
| 41 |
"""List of mutagen classes the StorageStyle can handle. |
| 42 |
""" |
| 43 |
|
| 44 |
def __init__(self, key, as_type=str, suffix=None, float_places=2, read_only=False): |
| 45 |
"""Create a basic storage strategy. Parameters: |
| 46 |
|
| 47 |
- `key`: The key on the Mutagen file object used to access the |
| 48 |
field's data. |
| 49 |
- `as_type`: The Python type that the value is stored as |
| 50 |
internally (`unicode`, `int`, `bool`, or `bytes`). |
| 51 |
- `suffix`: When `as_type` is a string type, append this before |
| 52 |
storing the value. |
| 53 |
- `float_places`: When the value is a floating-point number and |
| 54 |
encoded as a string, the number of digits to store after the |
| 55 |
decimal point. |
| 56 |
- `read_only`: When true, writing to this field is disabled. |
| 57 |
Primary use case is so wrongly named fields can be addressed |
| 58 |
in a graceful manner. This does not block the delete method. |
| 59 |
|
| 60 |
""" |
| 61 |
self.key = key |
| 62 |
self.as_type = as_type |
| 63 |
self.suffix = suffix |
| 64 |
self.float_places = float_places |
| 65 |
self.read_only = read_only |
| 66 |
|
| 67 |
# Convert suffix to correct string type. |
| 68 |
if self.suffix and self.as_type is str and not isinstance(self.suffix, str): |
| 69 |
self.suffix = self.suffix.decode("utf-8") |
| 70 |
|
| 71 |
# Getter. |
| 72 |
|
| 73 |
def get(self, mutagen_file): |
| 74 |
"""Get the value for the field using this style.""" |
| 75 |
return self.deserialize(self.fetch(mutagen_file)) |
| 76 |
|
| 77 |
def fetch(self, mutagen_file): |
| 78 |
"""Retrieve the raw value of for this tag from the Mutagen file |
| 79 |
object. |
| 80 |
""" |
| 81 |
try: |
| 82 |
return mutagen_file[self.key][0] |
| 83 |
except (KeyError, IndexError): |
| 84 |
return None |
| 85 |
|
| 86 |
def deserialize(self, mutagen_value): |
| 87 |
"""Given a raw value stored on a Mutagen object, decode and |
| 88 |
return the represented value. |
| 89 |
""" |
| 90 |
if ( |
| 91 |
self.suffix |
| 92 |
and isinstance(mutagen_value, str) |
| 93 |
and mutagen_value.endswith(self.suffix) |
| 94 |
): |
| 95 |
return mutagen_value[: -len(self.suffix)] |
| 96 |
else: |
| 97 |
return mutagen_value |
| 98 |
|
| 99 |
# Setter. |
| 100 |
|
| 101 |
def set(self, mutagen_file, value): |
| 102 |
"""Assign the value for the field using this style.""" |
| 103 |
self.store(mutagen_file, self.serialize(value)) |
| 104 |
|
| 105 |
def store(self, mutagen_file, value): |
| 106 |
"""Store a serialized value in the Mutagen file object.""" |
| 107 |
mutagen_file[self.key] = [value] |
| 108 |
|
| 109 |
def serialize(self, value): |
| 110 |
"""Convert the external Python value to a type that is suitable for |
| 111 |
storing in a Mutagen file object. |
| 112 |
""" |
| 113 |
if isinstance(value, float) and self.as_type is str: |
| 114 |
value = "{0:.{1}f}".format(value, self.float_places) |
| 115 |
value = self.as_type(value) |
| 116 |
elif self.as_type is str: |
| 117 |
if isinstance(value, bool): |
| 118 |
# Store bools as 1/0 instead of True/False. |
| 119 |
value = str(int(bool(value))) |
| 120 |
elif isinstance(value, bytes): |
| 121 |
value = value.decode("utf-8", "ignore") |
| 122 |
else: |
| 123 |
value = str(value) |
| 124 |
else: |
| 125 |
value = self.as_type(value) |
| 126 |
|
| 127 |
if self.suffix: |
| 128 |
value += self.suffix |
| 129 |
|
| 130 |
return value |
| 131 |
|
| 132 |
def delete(self, mutagen_file): |
| 133 |
"""Remove the tag from the file.""" |
| 134 |
if self.key in mutagen_file: |
| 135 |
del mutagen_file[self.key] |
| 136 |
|
| 137 |
|
| 138 |
class ListStorageStyle(StorageStyle): |
| 139 |
"""Abstract storage style that provides access to lists. |
| 140 |
|
| 141 |
The ListMediaField descriptor uses a ListStorageStyle via two |
| 142 |
methods: ``get_list()`` and ``set_list()``. It passes a Mutagen file |
| 143 |
object to each. |
| 144 |
|
| 145 |
Subclasses may overwrite ``fetch`` and ``store``. ``fetch`` must |
| 146 |
return a (possibly empty) list or `None` if the tag does not exist. |
| 147 |
``store`` receives a serialized list of values as the second argument. |
| 148 |
|
| 149 |
The `serialize` and `deserialize` methods (from the base |
| 150 |
`StorageStyle`) are still called with individual values. This class |
| 151 |
handles packing and unpacking the values into lists. |
| 152 |
""" |
| 153 |
|
| 154 |
def get(self, mutagen_file): |
| 155 |
"""Get the first value in the field's value list.""" |
| 156 |
values = self.get_list(mutagen_file) |
| 157 |
if values is None: |
| 158 |
return None |
| 159 |
|
| 160 |
try: |
| 161 |
return values[0] |
| 162 |
except IndexError: |
| 163 |
return None |
| 164 |
|
| 165 |
def get_list(self, mutagen_file): |
| 166 |
"""Get a list of all values for the field using this style.""" |
| 167 |
raw_values = self.fetch(mutagen_file) |
| 168 |
if raw_values is None: |
| 169 |
return None |
| 170 |
|
| 171 |
return [self.deserialize(item) for item in raw_values] |
| 172 |
|
| 173 |
def fetch(self, mutagen_file): |
| 174 |
"""Get the list of raw (serialized) values.""" |
| 175 |
try: |
| 176 |
return mutagen_file[self.key] |
| 177 |
except KeyError: |
| 178 |
return None |
| 179 |
|
| 180 |
def set(self, mutagen_file, value): |
| 181 |
"""Set an individual value as the only value for the field using |
| 182 |
this style. |
| 183 |
""" |
| 184 |
if value is None: |
| 185 |
self.store(mutagen_file, None) |
| 186 |
else: |
| 187 |
self.set_list(mutagen_file, [value]) |
| 188 |
|
| 189 |
def set_list(self, mutagen_file, values): |
| 190 |
"""Set all values for the field using this style. `values` |
| 191 |
should be an iterable. |
| 192 |
""" |
| 193 |
if values is None: |
| 194 |
self.delete(mutagen_file) |
| 195 |
else: |
| 196 |
self.store(mutagen_file, [self.serialize(value) for value in values]) |
| 197 |
|
| 198 |
def store(self, mutagen_file, values): |
| 199 |
"""Set the list of all raw (serialized) values for this field.""" |
| 200 |
mutagen_file[self.key] = values |
| 201 |
|
| 202 |
|
| 203 |
class SoundCheckStorageStyleMixin: |
| 204 |
"""A mixin for storage styles that read and write iTunes SoundCheck |
| 205 |
analysis values. The object must have an `index` field that |
| 206 |
indicates which half of the gain/peak pair---0 or 1---the field |
| 207 |
represents. |
| 208 |
""" |
| 209 |
|
| 210 |
def get(self, mutagen_file): |
| 211 |
data = self.fetch(mutagen_file) |
| 212 |
if data is not None: |
| 213 |
return sc_decode(data)[self.index] |
| 214 |
|
| 215 |
def set(self, mutagen_file, value): |
| 216 |
data = self.fetch(mutagen_file) |
| 217 |
if data is None: |
| 218 |
gain_peak = [0, 0] |
| 219 |
else: |
| 220 |
gain_peak = list(sc_decode(data)) |
| 221 |
gain_peak[self.index] = value or 0 |
| 222 |
data = self.serialize(sc_encode(*gain_peak)) |
| 223 |
self.store(mutagen_file, data) |