summaryrefslogtreecommitdiff
path: root/watcher.py
blob: d1e4ab6c55ca5fd58e7a461ac291ebe3102ad701 (plain)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import atexit
import configparser

import pyinotify

import library


class EventHandler(pyinotify.ProcessEvent):
    def process_IN_CREATE(self, event):
        print("Creating:", event.pathname)
        library.run(event.pathname)

    def process_IN_DELETE(self, event):
        print("Removing:", event.pathname)
        library.delete_file(event.pathname)

    def process_IN_MOVED_TO(self, event):
        print("Moved to:", event.pathname)
        library.update_track_filename(event.src_pathname, event.pathname)

        # moving the file may also hint that the metadata has changed
        library.update_file(event.pathname)

    def process_IN_MODIFY(self, event):
        print("Modified:", event.pathname)
        library.update_file(event.pathname)


class LibraryWatcher:

    def __init__(self, path):
        print("Setting up library watcher")

        if not hasattr(self, "path"):
            setattr(self, "path", path)

        if not hasattr(self, "wm"):
            setattr(self, "wm", pyinotify.WatchManager())

        mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE | \
            pyinotify.IN_MOVED_TO | pyinotify.IN_MOVED_FROM | \
            pyinotify.IN_MODIFY

        if not hasattr(self, "notifier"):
            setattr(self,
                    "notifier",
                    pyinotify.ThreadedNotifier(self.wm, EventHandler()))

        self.notifier.coalesce_events()
        self.notifier.start()

        if not hasattr(self, "wdd"):
            setattr(self, "wdd", self.wm.add_watch(path, mask, rec=True,
                                                   auto_add=True))

        print("Set up watch on ", path)

        atexit.register(self.stop)

    def stop(self):
        if self.wdd[self.path] > 0:
            self.wm.rm_watch(self.wdd[self.path], rec=True)

if __name__ == "__main__":
    config = configparser.ConfigParser()
    config.read("mach2.ini")

    watch = LibraryWatcher(config["DEFAULT"]["media_dir"])