]> git.treefish.org Git - photosort.git/blob - src/dirtrigger.py
fixing null registry checks
[photosort.git] / src / dirtrigger.py
1 import logging
2 import threading
3 import time
4 from watchdog.events import DirDeletedEvent, FileDeletedEvent, FileSystemEventHandler
5 from watchdog.observers import Observer
6
7 class DirTrigger(FileSystemEventHandler):
8
9     def __init__(self, dir_path, cool_time, max_time):
10         self._dir_path = dir_path
11         self._cool_time = cool_time
12         self._max_time = max_time
13         self._got_event = False
14         self._last_event_time = 0.0
15         self._last_reset_time = 0.0
16         self._lock = threading.Lock()
17         self._observer = Observer()
18         self._observer.schedule(self, path=dir_path, recursive=True)
19
20     def start(self):
21         try:
22             self._observer.start()
23         except Exception as e:
24             logging.warning("Error starting file observer for %s: %s", self._dir_path, str(e))
25
26     def stop(self):
27         self._observer.stop()
28
29     def is_triggering(self):
30         self._lock.acquire()
31         try:
32             now = time.time()
33             return ( self._got_event and
34                      (now - self._last_event_time > self._cool_time) ) or \
35                      now - self._last_reset_time > self._max_time
36         finally:
37             self._lock.release()
38
39     def reset(self):
40         self._lock.acquire()
41         try:
42             self._got_event = False
43             self._last_reset_time = time.time()
44         finally:
45             self._lock.release()
46
47     def on_any_event(self, event):
48         if event.event_type == FileDeletedEvent or event.event_type == DirDeletedEvent:
49             return
50
51         self._lock.acquire()
52         try:
53             self._got_event = True
54             self._last_event_time = time.time()
55         finally:
56             self._lock.release()