-
Notifications
You must be signed in to change notification settings - Fork 22
/
monitor.py
71 lines (49 loc) · 1.87 KB
/
monitor.py
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
70
71
from config import MONITORED_DIRS_PATH
from utils import filter_subdirectories
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
import pickle
import os
import threading
from config import CHANGE_FILES
class FileChangeHandler(FileSystemEventHandler):
def __init__(self):
self.change_files = CHANGE_FILES
self.file_lock = threading.Lock()
if not os.path.exists(MONITORED_DIRS_PATH):
self.monitored_dirs = set()
else:
with open(MONITORED_DIRS_PATH, 'rb') as file:
self.monitored_dirs = pickle.load(file)
def write_change(self, change):
with self.file_lock:
with open(self.changes_file, "a") as file:
file.write(change + "\n")
def on_created(self, event):
change = "add: {event.src_path}"
self.write_change(change)
def on_deleted(self, event):
change = "delete: {event.src_path}"
self.write_change(change)
def on_modified(self, event):
change = "modify: {event.src_path}"
self.write_change(change)
def on_moved(self, event):
change = "move from {event.src_path} to {event.dest_path}"
self.write_change(change)
def close(self):
with open(MONITORED_DIRS_PATH, 'wb') as file:
self.monitored_dirs = filter_subdirectories(self.monitored_dirs)
pickle.dump(self.monitored_dirs, file)
def monitor_dirs():
event_handler = FileChangeHandler()
observer = Observer()
for directory in event_handler.monitored_dirs:
observer.schedule(event_handler, directory, recursive=True)
observer.start()
event_handler.close()
observer.stop()
observer.join()
def backend_monitor():
monitor_thread = threading.Thread(target=monitor_dirs)
monitor_thread.start()