-
Notifications
You must be signed in to change notification settings - Fork 4
/
album.py
565 lines (461 loc) · 19.3 KB
/
album.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
"""An Album in the database and any related logic."""
import datetime
import logging
from pathlib import Path, PurePath
from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union, cast
import pluggy
import sqlalchemy as sa
from sqlalchemy import JSON, Column, Date, Integer, String
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.ext.mutable import MutableDict, MutableSet
from sqlalchemy.orm import relationship
import moe
from moe import config
from moe.library.lib_item import LibItem, LibraryError, MetaLibItem, SABase, SetType
if TYPE_CHECKING:
from moe.library.extra import Extra
from moe.library.track import MetaTrack, Track
__all__ = ["Album", "AlbumError", "MetaAlbum"]
log = logging.getLogger("moe.album")
class Hooks:
"""Album hook specifications."""
@staticmethod
@moe.hookspec
def create_custom_album_fields() -> dict[str, Any]: # type: ignore
"""Creates new custom fields for an Album.
Returns:
Dict of the field names to their default values or ``None`` for no default.
Example:
.. code:: python
return {"my_new_field": "default value", "other_field": None}
You can then access your new field as if it were a normal field::
album.my_new_field = "awesome new value"
Important:
Your custom field should follow the same naming rules as any other python
variable i.e. no spaces, starts with a letter, and consists solely of
alpha-numeric and underscore characters.
""" # noqa: DAR202
@staticmethod
@moe.hookspec
def is_unique_album(album: "Album", other: "Album") -> bool: # type: ignore
"""Add new conditions to determine whether two albums are unique.
"Uniqueness" is meant in terms of whether the two albums should be considered
duplicates in the library. These additional conditions will be applied inside a
album's :meth:`is_unique` method.
"""
@moe.hookimpl
def add_hooks(pm: pluggy.manager.PluginManager):
"""Registers `album` hookspecs to Moe."""
from moe.library.album import Hooks
pm.add_hookspecs(Hooks)
class AlbumError(LibraryError):
"""Error performing some operation on an Album."""
class MetaAlbum(MetaLibItem):
"""A album containing only metadata.
It does not exist on the filesystem nor in the library. It can be used
to represent information about a album to later be merged into a full ``Album``
instance.
There are no guarantees about information present in a ``MetaAlbum`` object i.e.
all attributes may be ``None``.
Attributes:
artist (Optional[str]): AKA albumartist.
barcode (Optional[str]): UPC barcode.
catalog_nums (Optional[set[str]]): Set of all catalog numbers.
country (Optional[str]): Country the album was released in
(two character identifier).
date (Optional[datetime.date]): Album release date.
disc_total (Optional[int]): Number of discs in the album.
label (Optional[str]): Album release label.
media (Optional[str]): Album release format (e.g. CD, Digital, etc.)
original_date (Optional[datetime.date]): Date of the original release of the
album.
title (Optional[str])
track_total (Optional[int]): Number of tracks that *should* be in the album.
If an album is missing tracks, then ``len(tracks) < track_total``.
tracks (list[Track]): Album's corresponding tracks.
"""
def __init__(
self,
artist: Optional[str] = None,
barcode: Optional[str] = None,
catalog_nums: Optional[set[str]] = None,
country: Optional[str] = None,
date: Optional[datetime.date] = None,
disc_total: Optional[int] = None,
label: Optional[str] = None,
media: Optional[str] = None,
original_date: Optional[datetime.date] = None,
title: Optional[str] = None,
track_total: Optional[int] = None,
tracks: Optional[list["MetaTrack"]] = None,
**kwargs,
):
"""Creates a MetaAlbum object with any additional custom fields as kwargs."""
self._custom_fields = self._get_default_custom_fields()
self._custom_fields_set = set(self._custom_fields)
self.artist = artist
self.barcode = barcode
self.catalog_nums = catalog_nums
self.country = country
self.date = date
self.disc_total = disc_total
self.label = label
self.media = media
self.original_date = original_date
self.title = title
self.track_total = track_total
if not tracks:
self.tracks = []
for key, value in kwargs.items():
setattr(self, key, value)
if config.CONFIG.settings.original_date and self.original_date:
self.date = self.original_date
log.debug(f"MetaAlbum created. [album={self!r}]")
@property
def catalog_num(self) -> Optional[str]:
"""Returns a string of all catalog_nums concatenated with ';'."""
if self.catalog_nums is None:
return None
return ";".join(self.catalog_nums)
@catalog_num.setter
def catalog_num(self, catalog_num_str: Optional[str]):
"""Sets a track's catalog_num from a string.
Args:
catalog_num_str: For more than one catalog_num, they should be split with
';'.
"""
if catalog_num_str is None:
self.catalog_nums = None
else:
self.catalog_nums = {
catalog_num.strip() for catalog_num in catalog_num_str.split(";")
}
@property
def fields(self) -> set[str]:
"""Returns any editable album fields."""
return {
"artist",
"barcode",
"catalog_nums",
"country",
"date",
"disc_total",
"label",
"media",
"original_date",
"title",
"track_total",
}.union(self._custom_fields)
def get_track(self, track_num: int, disc: int = 1) -> Optional["MetaTrack"]:
"""Gets a MetaTrack by its track number."""
return next(
(
track
for track in self.tracks
if track.track_num == track_num and track.disc == disc
),
None,
)
def merge(self, other: "MetaAlbum", overwrite: bool = False) -> None:
"""Merges another album into this one.
Args:
other: Other album to be merged with the current album.
overwrite: Whether or not to overwrite self if a conflict exists.
"""
log.debug(f"Merging MetaAlbums. [album_a={self!r}, album_b={other!r}")
new_tracks: list["MetaTrack"] = []
for other_track in other.tracks:
conflict_track = None
if other_track.track_num and other_track.disc:
conflict_track = self.get_track(other_track.track_num, other_track.disc)
if conflict_track:
conflict_track.merge(other_track, overwrite)
else:
new_tracks.append(other_track)
self.tracks.extend(new_tracks)
for field in self.fields:
other_value = getattr(other, field)
self_value = getattr(self, field)
if other_value and (overwrite or (not overwrite and not self_value)):
setattr(self, field, other_value)
log.debug(
f"MetaAlbums merged. [album_a={self!r}, album_b={other!r}, {overwrite=!r}]"
)
def __eq__(self, other: "MetaAlbum") -> bool:
"""Compares MetaAlbums by their fields."""
if type(self) != type(other):
return False
for field in self.fields:
if not hasattr(other, field) or (
getattr(self, field) != getattr(other, field)
):
return False
return True
def __lt__(self, other: "MetaAlbum") -> bool:
"""Sort an album based on its title, then artist, then date."""
if self.title == other.title:
if self.artist == other.artist:
if self.date is None:
return False
if other.date is None:
return True
return self.date < other.date
if self.artist is None:
return False
if other.artist is None:
return True
return self.artist < other.artist
if self.title is None:
return False
if other.title is None:
return True
return self.title < other.title
def __str__(self):
"""String representation of an Album."""
album_str = f"{self.artist} - {self.title}"
if self.date:
album_str += f" ({self.date.year})"
return album_str
def __repr__(self):
"""Represents an Album using its fields."""
field_reprs = []
for field in self.fields:
if hasattr(self, field):
field_reprs.append(f"{field}={getattr(self, field)!r}")
repr_str = "AlbumInfo(" + ", ".join(field_reprs)
custom_field_reprs = []
for custom_field, value in self._custom_fields.items():
custom_field_reprs.append(f"{custom_field}={value}")
if custom_field_reprs:
repr_str += ", custom_fields=[" + ", ".join(custom_field_reprs) + "]"
track_reprs = []
for track in sorted(self.tracks):
track_reprs.append(f"{track.disc}.{track.track_num} - {track.title}")
repr_str += ", tracks=[" + ", ".join(track_reprs) + "]"
repr_str += ")"
return repr_str
def _get_default_custom_fields(self) -> dict[str, Any]:
"""Returns the default custom album fields."""
return {
field: default_val
for plugin_fields in config.CONFIG.pm.hook.create_custom_album_fields()
for field, default_val in plugin_fields.items()
}
# Album generic, used for typing classmethod
A = TypeVar("A", bound="Album")
class Album(LibItem, SABase, MetaAlbum):
"""An album is a collection of tracks and represents a specific album release.
Albums also house any attributes that are shared by tracks e.g. albumartist.
Attributes:
artist (str): AKA albumartist.
barcode (Optional[str]): UPC barcode.
catalog_nums (Optional[set[str]]): Set of all catalog numbers.
country (Optional[str]): Country the album was released in
(two character identifier).
date (datetime.date): Album release date.
disc_total (int): Number of discs in the album.
extras (list[Extra]): Extra non-track files associated with the album.
label (Optional[str]): Album release label.
media (Optional[str]): Album release format (e.g. CD, Digital, etc.)
original_date (Optional[datetime.date]): Date of the original release of the
album.
path (pathlib.Path): Filesystem path of the album directory.
title (str)
track_total (Optional[int]): Number of tracks that *should* be in the album.
If an album is missing tracks, then ``len(tracks) < track_total``.
tracks (list[Track]): Album's corresponding tracks.
"""
__tablename__ = "album"
artist: str = cast(str, Column(String, nullable=False))
barcode: Optional[str] = cast(Optional[str], Column(String, nullable=True))
catalog_nums: Optional[set[str]] = cast(
Optional[set[str]], MutableSet.as_mutable(Column(SetType, nullable=True))
)
country: Optional[str] = cast(Optional[str], Column(String, nullable=True))
date: datetime.date = cast(datetime.date, Column(Date, nullable=False))
disc_total: int = cast(int, Column(Integer, nullable=False, default=1))
label: Optional[str] = cast(Optional[str], Column(String, nullable=True))
media: Optional[str] = cast(Optional[str], Column(String, nullable=True))
original_date: Optional[datetime.date] = cast(
Optional[datetime.date], Column(Date, nullable=True)
)
title: str = cast(str, Column(String, nullable=False))
track_total: Optional[int] = cast(Optional[int], Column(Integer, nullable=True))
_custom_fields: dict[str, Any] = cast(
dict[str, Any],
Column(
MutableDict.as_mutable(JSON(none_as_null=True)),
default="{}",
nullable=False,
),
)
tracks: list["Track"] = relationship(
"Track",
back_populates="album",
cascade="all, delete-orphan",
collection_class=list,
)
extras: list["Extra"] = relationship(
"Extra",
back_populates="album",
cascade="all, delete-orphan",
collection_class=list,
)
def __init__(
self,
path: Path,
artist: str,
title: str,
date: datetime.date,
disc_total=1,
**kwargs,
):
"""Creates an Album.
Args:
path: Filesystem path of the album directory.
artist: Album artist.
title: Album title.
date: Album release date.
disc_total: Number of discs in the album.
**kwargs: Any other fields to assign to the album.
"""
self._custom_fields = self._get_default_custom_fields()
self._custom_fields_set = set(self._custom_fields)
self.path = path
self.artist = artist
self.title = title
self.date = date
self.disc_total = disc_total
for key, value in kwargs.items():
setattr(self, key, value)
if config.CONFIG.settings.original_date and self.original_date:
self.date = self.original_date
log.debug(f"Album created. [album={self!r}]")
@classmethod
def from_dir(cls: type[A], album_path: Path) -> A:
"""Creates an album from a directory.
Args:
album_path: Album directory path. The directory will be scanned for any
files to be added to the album. Any non-track files will be added as
extras.
Returns:
Created album.
Raises:
AlbumError: No tracks found in the given directory.
"""
from moe.library.extra import Extra
from moe.library.track import Track, TrackError
log.debug(f"Creating album from directory. [dir={album_path}]")
extra_paths = []
album_file_paths = [path for path in album_path.rglob("*") if path.is_file()]
album: Optional[Album] = None
for file_path in album_file_paths:
try:
track = Track.from_file(file_path, album)
except TrackError:
extra_paths.append(file_path)
else:
if not album:
album = track.album
if not album:
raise AlbumError(f"No tracks found in album directory. [dir={album_path}]")
for extra_path in extra_paths:
Extra(album, extra_path)
log.debug(f"Album created from directory. [dir={album_path}, {album=!r}]")
return album
@property
def fields(self) -> set[str]:
"""Returns any editable, track-specific fields."""
return super().fields.union({"path"})
def get_extra(self, rel_path: PurePath) -> Optional["Extra"]:
"""Gets an Extra by its path."""
return next(
(extra for extra in self.extras if extra.rel_path == rel_path), None
)
def get_track(self, track_num: int, disc: int = 1) -> Optional["Track"]:
"""Gets a Track by its track number."""
return cast("Track", super().get_track(track_num, disc))
def is_unique(self, other: "Album") -> bool:
"""Returns whether an album is unique in the library from ``other``."""
if self.path == other.path:
return False
custom_uniqueness = config.CONFIG.pm.hook.is_unique_album(
album=self, other=other
)
if False in custom_uniqueness:
return False
return True
def merge(self, other: Union["Album", MetaAlbum], overwrite: bool = False) -> None:
"""Merges another album into this one.
Args:
other: Other album to be merged with the current album.
overwrite: Whether or not to overwrite self if a conflict exists.
"""
log.debug(f"Merging albums. [album_a={self!r}, album_b={other!r}")
new_tracks: list["Track"] = []
for other_track in other.tracks:
conflict_track = None
if other_track.track_num and other_track.disc:
conflict_track = self.get_track(other_track.track_num, other_track.disc)
if conflict_track:
conflict_track.merge(other_track, overwrite)
else:
new_tracks.append(other_track)
self.tracks.extend(new_tracks)
if isinstance(other, Album):
new_extras: list["Extra"] = []
for other_extra in other.extras:
conflict_extra = self.get_extra(other_extra.rel_path)
if conflict_extra:
conflict_extra.merge(other_extra, overwrite)
else:
new_extras.append(other_extra)
self.extras.extend(new_extras)
for field in self.fields:
other_value = getattr(other, field, None)
self_value = getattr(self, field, None)
if other_value and (overwrite or (not overwrite and not self_value)):
setattr(self, field, other_value)
log.debug(
f"Albums merged. [album_a={self!r}, album_b={other!r}, {overwrite=!r}]"
)
@hybrid_property
def original_year(self) -> Optional[int]: # type: ignore
"""Gets an Album's year."""
if self.original_date is None:
return None
return self.original_date.year
@original_year.expression # type: ignore
def original_year(cls): # noqa: B902
"""Returns a year at the sql level."""
return sa.extract("year", cls.original_date)
@hybrid_property
def year(self) -> int: # type: ignore
"""Gets an Album's year."""
return self.date.year
@year.expression # type: ignore
def year(cls): # noqa: B902
"""Returns a year at the sql level."""
return sa.extract("year", cls.date)
def __repr__(self):
"""Represents an Album using its fields."""
field_reprs = []
for field in self.fields:
if hasattr(self, field):
field_reprs.append(f"{field}={getattr(self, field)!r}")
repr_str = "Album(" + ", ".join(field_reprs)
custom_field_reprs = []
for custom_field, value in self._custom_fields.items():
custom_field_reprs.append(f"{custom_field}={value}")
if custom_field_reprs:
repr_str += ", custom_fields=[" + ", ".join(custom_field_reprs) + "]"
track_reprs = []
for track in sorted(self.tracks):
track_reprs.append(f"{track.disc}.{track.track_num} - {track.title}")
repr_str += ", tracks=[" + ", ".join(track_reprs) + "]"
extra_reprs = []
for extra in sorted(self.extras):
extra_reprs.append(f"{extra.path.name}")
repr_str += ", extras=[" + ", ".join(extra_reprs) + "]"
repr_str += ")"
return repr_str