Debian Codegraph @

beetsplug/importsource.py

raw
1 """Adds a `source_path` attribute to imported albums indicating from what path
2 the album was imported from. Also suggests removing that source path in case
3 you've removed the album from the library.
4
5 """
6
7 from __future__ import annotations
8
9 import os
10 from pathlib import Path
11 from shutil import rmtree
12 from typing import TYPE_CHECKING
13
14 from beets.dbcore.query import PathQuery
15 from beets.plugins import BeetsPlugin
16 from beets.ui import input_options
17 from beets.util.color import colorize
18
19 if TYPE_CHECKING:
20 from beets.importer import ImportSession, ImportTask
21 from beets.library import Item
22
23
24 class ImportSourcePlugin(BeetsPlugin):
25 """Main plugin class."""
26
27 stop_suggestions_for_albums: set[str]
28
29 def __init__(self) -> None:
30 """Initialize the plugin and read configuration."""
31 super().__init__()
32 self.config.add({"suggest_removal": False})
33 self.import_stages = [self.import_stage]
34 # In order to stop future removal suggestions for an album we keep
35 # track of `mb_albumid`s in this set. Always initialize to avoid
36 # AttributeError when methods access this even if feature disabled.
37 self.stop_suggestions_for_albums = set()
38 # Only register removal suggestion listeners if the feature is enabled
39 if self.config["suggest_removal"]:
40 self.register_listener("item_removed", self.suggest_removal)
41 # During reimports (import --library) both the import_task_choice and
42 # the item_removed event are triggered. The item_removed event is
43 # triggered first. For the import_task_choice event we prevent removal
44 # suggestions using the existing stop_suggestions_for_album mechanism.
45 self.register_listener(
46 "import_task_choice", self.prevent_suggest_removal
47 )
48
49 def prevent_suggest_removal(
50 self, session: ImportSession, task: ImportTask
51 ) -> None:
52 if task.skip:
53 return
54 for item in task.imported_items():
55 if "mb_albumid" in item:
56 self.stop_suggestions_for_albums.add(item.mb_albumid)
57
58 def import_stage(self, _, task: ImportTask) -> None:
59 """Event handler for albums import finished."""
60 for item in task.imported_items():
61 # During reimports (import --library), we prevent overwriting the
62 # source_path attribute with the path from the music library
63 if "source_path" in item:
64 self._log.info(
65 "Preserving source_path of reimported item {}", item.id
66 )
67 continue
68 item["source_path"] = item.path
69 item.try_sync(write=False, move=False)
70
71 def suggest_removal(self, item: Item) -> None:
72 """Prompts the user to delete the original path the item was imported from."""
73 if item.mb_albumid in self.stop_suggestions_for_albums:
74 return
75
76 if "source_path" not in item:
77 self._log.warning(
78 "Item without source_path (probably imported before plugin "
79 "usage): {}",
80 item.filepath,
81 )
82 return
83
84 srcpath = Path(os.fsdecode(item.source_path))
85 if not srcpath.is_file():
86 self._log.warning(
87 "Original source file no longer exists or is not accessible: {}",
88 srcpath,
89 )
90 return
91
92 if not (
93 os.access(srcpath, os.W_OK)
94 and os.access(srcpath.parent, os.W_OK | os.X_OK)
95 ):
96 self._log.warning(
97 "Original source file cannot be deleted (insufficient permissions): {}",
98 srcpath,
99 )
100 return
101
102 # We ask the user whether they'd like to delete the item's source
103 # directory
104 item_path = colorize("text_warning", item.filepath)
105 source_path = colorize("text_warning", srcpath)
106
107 print(
108 f"The item:\n{item_path}\nis originated from:\n{source_path}\n"
109 "What would you like to do?"
110 )
111
112 resp = input_options(
113 [
114 "Delete the item's source",
115 "Recursively delete the source's directory",
116 "do Nothing",
117 "do nothing and Stop suggesting to delete items from this album",
118 ],
119 require=True,
120 )
121
122 # Handle user response
123 if resp == "d":
124 self._log.info("Deleting the item's source file: {}", srcpath)
125 srcpath.unlink()
126
127 elif resp == "r":
128 self._log.info(
129 "Searching for other items with a source_path attr containing: {}",
130 srcpath.parent,
131 )
132
133 source_dir_query = PathQuery(
134 "source_path",
135 os.fsencode(srcpath.parent),
136 # The "source_path" attribute may not be present in all
137 # items of the library, so we avoid errors with this:
138 fast=False,
139 )
140
141 print("Doing so will delete the following items' sources as well:")
142 for searched_item in item.db.items(source_dir_query):
143 print(colorize("text_warning", searched_item.filepath))
144
145 print("Would you like to continue?")
146 continue_resp = input_options(
147 ["Yes", "delete None", "delete just the File"],
148 require=False, # Yes is the a default
149 )
150
151 if continue_resp == "y":
152 self._log.info(
153 "Deleting the item's source directory: {}", srcpath.parent
154 )
155 rmtree(srcpath.parent)
156
157 elif continue_resp == "n":
158 self._log.info("doing nothing - aborting hook function")
159 return
160
161 elif continue_resp == "f":
162 self._log.info(
163 "removing just the item's original source: {}", srcpath
164 )
165 srcpath.unlink()
166
167 elif resp == "s":
168 self.stop_suggestions_for_albums.add(item.mb_albumid)
169
170 else:
171 self._log.info("Doing nothing")