Debian Codegraph @

beetsplug/metasync/itunes.py

raw
1 """Synchronize information from iTunes's library"""
2
3 from __future__ import annotations
4
5 import os
6 import plistlib
7 import shutil
8 import tempfile
9 from contextlib import contextmanager
10 from time import mktime
11 from typing import TYPE_CHECKING, ClassVar
12 from urllib.parse import unquote, urlparse
13
14 from confuse import ConfigValueError
15
16 from beets import util
17 from beets.dbcore import types
18 from beets.util import bytestring_path, syspath
19 from beetsplug.metasync import MetaSource
20
21 if TYPE_CHECKING:
22 from collections.abc import Iterator
23
24 from confuse import ConfigView
25
26 from beets.library import Item
27 from beets.logging import BeetsLogger as Logger
28
29
30 @contextmanager
31 def create_temporary_copy(path: util.PathLike) -> Iterator[bytes]:
32 temp_dir = bytestring_path(tempfile.mkdtemp())
33 temp_path = os.path.join(temp_dir, b"temp_itunes_lib")
34 shutil.copyfile(syspath(path), syspath(temp_path))
35 try:
36 yield temp_path
37 finally:
38 shutil.rmtree(syspath(temp_dir))
39
40
41 def _norm_itunes_path(path: bytes) -> bytes:
42 # Itunes prepends the location with 'file://' on posix systems,
43 # and with 'file://localhost/' on Windows systems.
44 # The actual path to the file is always saved as posix form
45 # E.g., 'file://Users/Music/bar' or 'file://localhost/G:/Music/bar'
46
47 # The entire path will also be capitalized (e.g., '/Music/Alt-J')
48 # Note that this means the path will always have a leading separator,
49 # which is unwanted in the case of Windows systems.
50 # E.g., '\\G:\\Music\\bar' needs to be stripped to 'G:\\Music\\bar'
51
52 return util.bytestring_path(
53 os.path.normpath(unquote(urlparse(path).path)).lstrip("\\")
54 ).lower()
55
56
57 class Itunes(MetaSource):
58 item_types: ClassVar[dict[str, types.Type]] = {
59 "itunes_rating": types.INTEGER, # 0..100 scale
60 "itunes_playcount": types.INTEGER,
61 "itunes_skipcount": types.INTEGER,
62 "itunes_lastplayed": types.DATE,
63 "itunes_lastskipped": types.DATE,
64 "itunes_dateadded": types.DATE,
65 }
66
67 def __init__(self, config: ConfigView, log: Logger) -> None:
68 super().__init__(config, log)
69
70 config.add({"itunes": {"library": "~/Music/iTunes/iTunes Library.xml"}})
71
72 # Load the iTunes library, which has to be the .xml one (not the .itl)
73 library_path = config["itunes"]["library"].as_filename()
74
75 try:
76 self._log.debug("loading iTunes library from {}", library_path)
77 with create_temporary_copy(library_path) as library_copy:
78 with open(library_copy, "rb") as library_copy_f:
79 raw_library = plistlib.load(library_copy_f)
80 except OSError as e:
81 raise ConfigValueError(f"invalid iTunes library: {e.strerror}")
82 except Exception:
83 # It's likely the user configured their '.itl' library (<> xml)
84 if os.path.splitext(library_path)[1].lower() != ".xml":
85 hint = (
86 ": please ensure that the configured path"
87 " points to the .XML library"
88 )
89 else:
90 hint = ""
91 raise ConfigValueError(f"invalid iTunes library{hint}")
92
93 # Make the iTunes library queryable using the path
94 self.collection = {
95 _norm_itunes_path(track["Location"]): track
96 for track in raw_library["Tracks"].values()
97 if "Location" in track
98 }
99
100 def sync_from_source(self, item: Item) -> None:
101 result = self.collection.get(util.bytestring_path(item.path).lower())
102
103 if not result:
104 self._log.warning("no iTunes match found for {}", item)
105 return
106
107 item.itunes_rating = result.get("Rating")
108 item.itunes_playcount = result.get("Play Count")
109 item.itunes_skipcount = result.get("Skip Count")
110
111 if result.get("Play Date UTC"):
112 item.itunes_lastplayed = mktime(
113 result.get("Play Date UTC").timetuple()
114 )
115
116 if result.get("Skip Date"):
117 item.itunes_lastskipped = mktime(
118 result.get("Skip Date").timetuple()
119 )
120
121 if result.get("Date Added"):
122 item.itunes_dateadded = mktime(result.get("Date Added").timetuple())