| 1 |
"""Adds support for ipfs. Requires go-ipfs and a running ipfs daemon""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import os |
| 6 |
import shutil |
| 7 |
import subprocess |
| 8 |
import tempfile |
| 9 |
from contextlib import contextmanager |
| 10 |
from types import SimpleNamespace |
| 11 |
from typing import TYPE_CHECKING, Protocol |
| 12 |
|
| 13 |
from beets import config, library, ui, util |
| 14 |
from beets.plugins import BeetsPlugin |
| 15 |
|
| 16 |
if TYPE_CHECKING: |
| 17 |
from collections.abc import Iterator, Sequence |
| 18 |
|
| 19 |
from beets.dbcore import Results |
| 20 |
from beets.importer import ImportSession, ImportTask |
| 21 |
from beets.library import Album, Library |
| 22 |
|
| 23 |
|
| 24 |
class IPFSCLIOpts(Protocol): |
| 25 |
_import: bool | None |
| 26 |
_list: bool | None |
| 27 |
add: bool | None |
| 28 |
get: bool | None |
| 29 |
play: bool | None |
| 30 |
publish: bool | None |
| 31 |
|
| 32 |
|
| 33 |
class IPFSPlugin(BeetsPlugin): |
| 34 |
def __init__(self) -> None: |
| 35 |
super().__init__() |
| 36 |
self.config.add({"auto": True, "nocopy": False}) |
| 37 |
|
| 38 |
if self.config["auto"]: |
| 39 |
self.import_stages = [self.auto_add] |
| 40 |
|
| 41 |
def commands(self) -> list[ui.Subcommand]: |
| 42 |
cmd = ui.Subcommand("ipfs", help="interact with ipfs") |
| 43 |
cmd.parser.add_option( |
| 44 |
"-a", "--add", dest="add", action="store_true", help="Add to ipfs" |
| 45 |
) |
| 46 |
cmd.parser.add_option( |
| 47 |
"-g", "--get", dest="get", action="store_true", help="Get from ipfs" |
| 48 |
) |
| 49 |
cmd.parser.add_option( |
| 50 |
"-p", |
| 51 |
"--publish", |
| 52 |
dest="publish", |
| 53 |
action="store_true", |
| 54 |
help="Publish local library to ipfs", |
| 55 |
) |
| 56 |
cmd.parser.add_option( |
| 57 |
"-i", |
| 58 |
"--import", |
| 59 |
dest="_import", |
| 60 |
action="store_true", |
| 61 |
help="Import remote library from ipfs", |
| 62 |
) |
| 63 |
cmd.parser.add_option( |
| 64 |
"-l", |
| 65 |
"--list", |
| 66 |
dest="_list", |
| 67 |
action="store_true", |
| 68 |
help="Query imported libraries", |
| 69 |
) |
| 70 |
cmd.parser.add_option( |
| 71 |
"-m", |
| 72 |
"--play", |
| 73 |
dest="play", |
| 74 |
action="store_true", |
| 75 |
help="Play music from remote libraries", |
| 76 |
) |
| 77 |
|
| 78 |
def func(lib: Library, opts: IPFSCLIOpts, args: list[str]) -> None: |
| 79 |
if opts.add: |
| 80 |
for album in lib.albums(args): |
| 81 |
if len(album.items()) == 0: |
| 82 |
self._log.info( |
| 83 |
"{} does not contain items, aborting", album |
| 84 |
) |
| 85 |
|
| 86 |
self.ipfs_add(album) |
| 87 |
album.store() |
| 88 |
|
| 89 |
if opts.get: |
| 90 |
self.ipfs_get(lib, args) |
| 91 |
|
| 92 |
if opts.publish: |
| 93 |
self.ipfs_publish(lib) |
| 94 |
|
| 95 |
if opts._import: |
| 96 |
self.ipfs_import(lib, args) |
| 97 |
|
| 98 |
if opts._list: |
| 99 |
self.ipfs_list(lib, args) |
| 100 |
|
| 101 |
if opts.play: |
| 102 |
self.ipfs_play(lib, opts, args) |
| 103 |
|
| 104 |
cmd.func = func |
| 105 |
return [cmd] |
| 106 |
|
| 107 |
def auto_add(self, session: ImportSession, task: ImportTask) -> None: |
| 108 |
if task.is_album: |
| 109 |
if self.ipfs_add(task.album): |
| 110 |
task.album.store() |
| 111 |
|
| 112 |
def ipfs_play( |
| 113 |
self, lib: Library, opts: IPFSCLIOpts, args: list[str] |
| 114 |
) -> None: |
| 115 |
from beetsplug.play import PlayPlugin |
| 116 |
|
| 117 |
player = PlayPlugin() |
| 118 |
config["play"]["relative_to"] = None |
| 119 |
# set opts that `_play_command` expects |
| 120 |
play_opts = SimpleNamespace( |
| 121 |
album=True, randomize=None, args=None, yes=None |
| 122 |
) |
| 123 |
with self.remote_lib(lib) as jlib: |
| 124 |
player._play_command(jlib, play_opts, args) |
| 125 |
|
| 126 |
def ipfs_add(self, album: Album) -> bool: |
| 127 |
try: |
| 128 |
album_dir = album.item_dir() |
| 129 |
except AttributeError: |
| 130 |
return False |
| 131 |
try: |
| 132 |
if album.ipfs: |
| 133 |
self._log.debug("{} already added", album_dir) |
| 134 |
# Already added to ipfs |
| 135 |
return False |
| 136 |
except AttributeError: |
| 137 |
pass |
| 138 |
|
| 139 |
self._log.info("Adding {} to ipfs", album_dir) |
| 140 |
|
| 141 |
if self.config["nocopy"]: |
| 142 |
cmd = "ipfs add --nocopy -q -r".split() |
| 143 |
else: |
| 144 |
cmd = "ipfs add -q -r".split() |
| 145 |
cmd.append(os.fsdecode(album_dir)) |
| 146 |
try: |
| 147 |
output = util.command_output(cmd).stdout.split() |
| 148 |
except (OSError, subprocess.CalledProcessError) as exc: |
| 149 |
self._log.error("Failed to add {}, error: {}", album_dir, exc) |
| 150 |
return False |
| 151 |
length = len(output) |
| 152 |
|
| 153 |
for linenr, line in enumerate(output): |
| 154 |
line = line.strip() |
| 155 |
if linenr == length - 1: |
| 156 |
# last printed line is the album hash |
| 157 |
self._log.info("album: {}", line) |
| 158 |
album.ipfs = line |
| 159 |
else: |
| 160 |
try: |
| 161 |
item = album.items()[linenr] |
| 162 |
self._log.info("item: {}", line) |
| 163 |
item.ipfs = line |
| 164 |
item.store() |
| 165 |
except IndexError: |
| 166 |
# if there's non music files in the to-add folder they'll |
| 167 |
# get ignored here |
| 168 |
pass |
| 169 |
|
| 170 |
return True |
| 171 |
|
| 172 |
def ipfs_get(self, lib: Library, queries: Sequence[str]) -> None: |
| 173 |
query = queries[0] |
| 174 |
# Check if query is a hash |
| 175 |
# TODO: generalize to other hashes; probably use a multihash |
| 176 |
# implementation |
| 177 |
if query.startswith("Qm") and len(query) == 46: |
| 178 |
self.ipfs_get_from_hash(lib, query) |
| 179 |
else: |
| 180 |
albums = self.query(lib, query) |
| 181 |
for album in albums: |
| 182 |
self.ipfs_get_from_hash(lib, album.ipfs) |
| 183 |
|
| 184 |
def ipfs_get_from_hash(self, lib: Library, _hash: str) -> bool | None: |
| 185 |
try: |
| 186 |
cmd = "ipfs get".split() |
| 187 |
cmd.append(_hash) |
| 188 |
util.command_output(cmd) |
| 189 |
except (OSError, subprocess.CalledProcessError) as err: |
| 190 |
self._log.error( |
| 191 |
"Failed to get {} from ipfs.\n{.output}", _hash, err |
| 192 |
) |
| 193 |
return False |
| 194 |
|
| 195 |
self._log.info("Getting {} from ipfs", _hash) |
| 196 |
imp = ui.commands.TerminalImportSession( |
| 197 |
lib, loghandler=None, query=None, paths=[_hash] |
| 198 |
) |
| 199 |
imp.run() |
| 200 |
shutil.rmtree(_hash) |
| 201 |
return None |
| 202 |
|
| 203 |
def ipfs_publish(self, lib: Library) -> bool | None: |
| 204 |
with tempfile.NamedTemporaryFile() as tmp: |
| 205 |
self.ipfs_added_albums(lib, tmp.name) |
| 206 |
try: |
| 207 |
if self.config["nocopy"]: |
| 208 |
cmd = "ipfs add --nocopy -q ".split() |
| 209 |
else: |
| 210 |
cmd = "ipfs add -q ".split() |
| 211 |
cmd.append(tmp.name) |
| 212 |
output = util.command_output(cmd).stdout |
| 213 |
except (OSError, subprocess.CalledProcessError) as err: |
| 214 |
msg = f"Failed to publish library. Error: {err}" |
| 215 |
self._log.error(msg) |
| 216 |
return False |
| 217 |
self._log.info("hash of library: {}", output) |
| 218 |
return None |
| 219 |
|
| 220 |
def ipfs_import(self, lib: Library, args: Sequence[str]) -> bool | None: |
| 221 |
_hash = args[0] |
| 222 |
if len(args) > 1: |
| 223 |
lib_name = args[1] |
| 224 |
else: |
| 225 |
lib_name = _hash |
| 226 |
remote_libs = self._remote_libs_path(lib) |
| 227 |
if not os.path.exists(remote_libs): |
| 228 |
try: |
| 229 |
os.makedirs(remote_libs) |
| 230 |
except OSError as e: |
| 231 |
self._log.error( |
| 232 |
"Could not create {}. Error: {}", |
| 233 |
os.fsdecode(remote_libs), |
| 234 |
e, |
| 235 |
) |
| 236 |
return False |
| 237 |
path = os.path.join(remote_libs, lib_name.encode() + b".db") |
| 238 |
if not os.path.exists(path): |
| 239 |
cmd = f"ipfs get {_hash} -o".split() |
| 240 |
cmd.append(os.fsdecode(path)) |
| 241 |
try: |
| 242 |
util.command_output(cmd) |
| 243 |
except (OSError, subprocess.CalledProcessError): |
| 244 |
self._log.error("Could not import {}", _hash) |
| 245 |
return False |
| 246 |
|
| 247 |
# add all albums from remotes into a combined library |
| 248 |
jpath = os.path.join(remote_libs, b"joined.db") |
| 249 |
jlib = library.Library(jpath) |
| 250 |
nlib = library.Library(path) |
| 251 |
for album in nlib.albums(): |
| 252 |
if not self.already_added(album, jlib): |
| 253 |
new_album = [] |
| 254 |
for item in album.items(): |
| 255 |
item.id = None |
| 256 |
new_album.append(item) |
| 257 |
added_album = jlib.add_album(new_album) |
| 258 |
added_album.ipfs = album.ipfs |
| 259 |
added_album.store() |
| 260 |
return None |
| 261 |
|
| 262 |
def already_added(self, check: Album, jlib: Library) -> bool: |
| 263 |
for jalbum in jlib.albums(): |
| 264 |
if jalbum.mb_albumid == check.mb_albumid: |
| 265 |
return True |
| 266 |
return False |
| 267 |
|
| 268 |
def ipfs_list(self, lib: Library, args: Sequence[str]) -> None: |
| 269 |
fmt = config["format_album"].get() |
| 270 |
try: |
| 271 |
albums = self.query(lib, args) |
| 272 |
except OSError: |
| 273 |
ui.print_("No imported libraries yet.") |
| 274 |
return |
| 275 |
|
| 276 |
for album in albums: |
| 277 |
ui.print_(format(album, fmt), " : ", album.ipfs.decode()) |
| 278 |
|
| 279 |
def query(self, lib: Library, args: str | Sequence[str]) -> Results[Album]: |
| 280 |
with self.remote_lib(lib) as rlib: |
| 281 |
return rlib.albums(args) |
| 282 |
|
| 283 |
def _remote_libs_path(self, lib: Library) -> bytes: |
| 284 |
lib_root = os.path.dirname(os.fsencode(lib.path)) |
| 285 |
return os.path.join(lib_root, b"remotes") |
| 286 |
|
| 287 |
@contextmanager |
| 288 |
def remote_lib(self, lib: Library) -> Iterator[Library]: |
| 289 |
remote_libs = self._remote_libs_path(lib) |
| 290 |
path = os.path.join(remote_libs, b"joined.db") |
| 291 |
if not os.path.isfile(path): |
| 292 |
raise OSError |
| 293 |
|
| 294 |
remote_lib = library.Library(path) |
| 295 |
|
| 296 |
try: |
| 297 |
yield remote_lib |
| 298 |
finally: |
| 299 |
remote_lib._close() |
| 300 |
|
| 301 |
def ipfs_added_albums(self, rlib: Library, tmpname: str) -> Library: |
| 302 |
"""Returns a new library with only albums/items added to ipfs""" |
| 303 |
tmplib = library.Library( |
| 304 |
tmpname, directory="/ipfs/", set_music_dir=False |
| 305 |
) |
| 306 |
with tmplib.music_dir_context(): |
| 307 |
for album in rlib.albums(): |
| 308 |
try: |
| 309 |
if album.ipfs: |
| 310 |
self.create_new_album(album, tmplib) |
| 311 |
except AttributeError: |
| 312 |
pass |
| 313 |
return tmplib |
| 314 |
|
| 315 |
def create_new_album(self, album: Album, tmplib: Library) -> bool | None: |
| 316 |
items = [] |
| 317 |
for item in album.items(): |
| 318 |
try: |
| 319 |
if not item.ipfs: |
| 320 |
break |
| 321 |
except AttributeError: |
| 322 |
pass |
| 323 |
item_path = os.fsdecode(os.path.basename(item.path)) |
| 324 |
# Clear current path from item |
| 325 |
item.path = os.fsencode(f"{album.ipfs}/{item_path}") |
| 326 |
|
| 327 |
item.id = None |
| 328 |
items.append(item) |
| 329 |
if len(items) < 1: |
| 330 |
return False |
| 331 |
self._log.info("Adding '{}' to temporary library", album) |
| 332 |
new_album = tmplib.add_album(items) |
| 333 |
new_album.ipfs = album.ipfs |
| 334 |
new_album.store(inherit=False) |
| 335 |
return None |