| 1 |
"""Write paths of imported files in various formats to ease later import in a |
| 2 |
music player. Also allow printing the new file locations to stdout in case |
| 3 |
one wants to manually add music to a player by its path. |
| 4 |
""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import datetime |
| 9 |
import os |
| 10 |
import re |
| 11 |
from typing import TYPE_CHECKING |
| 12 |
|
| 13 |
from beets import config |
| 14 |
from beets.plugins import BeetsPlugin |
| 15 |
from beets.util import ( |
| 16 |
FilesystemError, |
| 17 |
bytestring_path, |
| 18 |
link, |
| 19 |
mkdirall, |
| 20 |
normpath, |
| 21 |
syspath, |
| 22 |
) |
| 23 |
|
| 24 |
if TYPE_CHECKING: |
| 25 |
from collections.abc import Sequence |
| 26 |
|
| 27 |
from beets.importer import ImportSession |
| 28 |
from beets.library import Album, Item, Library |
| 29 |
|
| 30 |
|
| 31 |
M3U_DEFAULT_NAME = "imported.m3u" |
| 32 |
|
| 33 |
|
| 34 |
def _build_m3u_session_filename(basename: str) -> bytes: |
| 35 |
"""Builds unique m3u filename by putting current date between given |
| 36 |
basename and file ending.""" |
| 37 |
date = datetime.datetime.now().strftime("%Y%m%d_%Hh%M") |
| 38 |
basename = re.sub(r"(\.m3u|\.M3U)", "", basename) |
| 39 |
return normpath( |
| 40 |
os.path.join( |
| 41 |
config["importfeeds"]["dir"].as_filename(), f"{basename}_{date}.m3u" |
| 42 |
) |
| 43 |
) |
| 44 |
|
| 45 |
|
| 46 |
def _build_m3u_filename(basename: str) -> bytes: |
| 47 |
"""Builds unique m3u filename by appending given basename to current |
| 48 |
date.""" |
| 49 |
basename = re.sub(r"[\s,/\\'\"]", "_", basename) |
| 50 |
date = datetime.datetime.now().strftime("%Y%m%d_%Hh%M") |
| 51 |
return normpath( |
| 52 |
os.path.join( |
| 53 |
config["importfeeds"]["dir"].as_filename(), f"{date}_{basename}.m3u" |
| 54 |
) |
| 55 |
) |
| 56 |
|
| 57 |
|
| 58 |
def _write_m3u(m3u_path: bytes, items_paths: Sequence[bytes]) -> None: |
| 59 |
"""Append relative paths to items into m3u file.""" |
| 60 |
mkdirall(m3u_path) |
| 61 |
with open(syspath(m3u_path), "ab") as f: |
| 62 |
for path in items_paths: |
| 63 |
f.write(path + b"\n") |
| 64 |
|
| 65 |
|
| 66 |
class ImportFeedsPlugin(BeetsPlugin): |
| 67 |
def __init__(self) -> None: |
| 68 |
super().__init__() |
| 69 |
|
| 70 |
self.config.add( |
| 71 |
{ |
| 72 |
"formats": [], |
| 73 |
"m3u_name": "imported.m3u", |
| 74 |
"dir": None, |
| 75 |
"relative_to": None, |
| 76 |
"absolute_path": False, |
| 77 |
} |
| 78 |
) |
| 79 |
|
| 80 |
relative_to = self.config["relative_to"].get() |
| 81 |
if relative_to: |
| 82 |
self.config["relative_to"] = normpath(relative_to) |
| 83 |
else: |
| 84 |
self.config["relative_to"] = self.get_feeds_dir() |
| 85 |
|
| 86 |
self.register_listener("album_imported", self.album_imported) |
| 87 |
self.register_listener("item_imported", self.item_imported) |
| 88 |
self.register_listener("import_begin", self.import_begin) |
| 89 |
|
| 90 |
def get_feeds_dir(self) -> str | bytes: |
| 91 |
feeds_dir = self.config["dir"].get() |
| 92 |
if feeds_dir: |
| 93 |
return os.path.expanduser(bytestring_path(feeds_dir)) |
| 94 |
return config["directory"].as_filename() |
| 95 |
|
| 96 |
def _record_items( |
| 97 |
self, lib: Library, basename: str, items: Sequence[Item] |
| 98 |
) -> None: |
| 99 |
"""Records relative paths to the given items for each feed format""" |
| 100 |
feedsdir = bytestring_path(self.get_feeds_dir()) |
| 101 |
formats = self.config["formats"].as_str_seq() |
| 102 |
relative_to = self.config["relative_to"].get() or self.get_feeds_dir() |
| 103 |
relative_to = bytestring_path(relative_to) |
| 104 |
|
| 105 |
paths = [] |
| 106 |
for item in items: |
| 107 |
if self.config["absolute_path"]: |
| 108 |
paths.append(item.path) |
| 109 |
else: |
| 110 |
try: |
| 111 |
relpath = os.path.relpath(item.path, relative_to) |
| 112 |
except ValueError: |
| 113 |
# On Windows, it is sometimes not possible to construct a |
| 114 |
# relative path (if the files are on different disks). |
| 115 |
relpath = item.path |
| 116 |
paths.append(relpath) |
| 117 |
|
| 118 |
if "m3u" in formats: |
| 119 |
m3u_basename = bytestring_path(self.config["m3u_name"].as_str()) |
| 120 |
m3u_path = os.path.join(feedsdir, m3u_basename) |
| 121 |
_write_m3u(m3u_path, paths) |
| 122 |
|
| 123 |
if "m3u_session" in formats: |
| 124 |
m3u_path = os.path.join(feedsdir, self.m3u_session) |
| 125 |
_write_m3u(m3u_path, paths) |
| 126 |
|
| 127 |
if "m3u_multi" in formats: |
| 128 |
m3u_path = _build_m3u_filename(basename) |
| 129 |
_write_m3u(m3u_path, paths) |
| 130 |
|
| 131 |
if "link" in formats: |
| 132 |
for path in paths: |
| 133 |
dest = os.path.join(feedsdir, os.path.basename(path)) |
| 134 |
if not os.path.exists(syspath(dest)): |
| 135 |
try: |
| 136 |
link(path, dest) |
| 137 |
except FilesystemError as exc: |
| 138 |
self._log.warning( |
| 139 |
"could not create symlink for {}: {}", path, exc |
| 140 |
) |
| 141 |
|
| 142 |
if "echo" in formats: |
| 143 |
self._log.info("Location of imported music:") |
| 144 |
for path in paths: |
| 145 |
self._log.info(" {}", path) |
| 146 |
|
| 147 |
def album_imported(self, lib: Library, album: Album) -> None: |
| 148 |
self._record_items(lib, album.album, album.items()) |
| 149 |
|
| 150 |
def item_imported(self, lib: Library, item: Item) -> None: |
| 151 |
self._record_items(lib, item.title, [item]) |
| 152 |
|
| 153 |
def import_begin(self, session: ImportSession) -> None: |
| 154 |
formats = self.config["formats"].as_str_seq() |
| 155 |
if "m3u_session" in formats: |
| 156 |
self.m3u_session = _build_m3u_session_filename( |
| 157 |
self.config["m3u_name"].as_str() |
| 158 |
) |