aboutsummaryrefslogtreecommitdiffstats
path: root/beetsplug/extras.py
blob: ea394b605cc7caf4d7ca228591f13bcb235f010b (plain) (blame)
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
import os
import shutil

import beets.plugins


class ExtrasPlugin(beets.plugins.BeetsPlugin):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.register_listener("item_moved", self.on_item_moved)
        self.register_listener("item_copied", self.on_item_copied)

    def on_item_moved(self, item, source, destination):
        for sourcepath, destpath in self.gather(source, destination):
            # need to decode to str here as shutil.move (still) breaks on bytes
            # arguments because of _destinsrc using str.endswith
            shutil.move(sourcepath.decode(), destpath.decode())

    def on_item_copied(self, item, source, destination):
        for sourcepath, destpath in self.gather(source, destination):
            if os.path.isdir(sourcepath):
                shutil.copytree(sourcepath, destpath)
            else:
                shutil.copy(sourcepath, destpath)

    def gather(self, source, destination):
        candidates = []
        sourcedir = os.path.dirname(source)
        destdir = os.path.dirname(destination)

        if sourcedir == destdir:
            return []

        paths = [beets.util.bytestring_path(p) for p in self.config["paths"].get()]

        for path in paths:
            sourcepath = os.path.join(sourcedir, path)
            if not os.path.exists(sourcepath):
                continue

            destpath = os.path.join(destdir, path)
            if os.path.exists(destpath):
                continue

            candidates.append((sourcepath, destpath))

        return candidates