X-Git-Url: http://git.treefish.org/~alex/photosort.git/blobdiff_plain/ef745f5c8e8191f8ff341cb6fcf39179e34eb2bd..e97415dff8bbc02a90428374c37d4d105d2a38ce:/src/dirtrigger.py?ds=inline diff --git a/src/dirtrigger.py b/src/dirtrigger.py index f8f67cf..1ef7e8b 100644 --- a/src/dirtrigger.py +++ b/src/dirtrigger.py @@ -1,6 +1,56 @@ -class DirTrigger: - def __init__(self, dir_path): - pass +import logging +import threading +import time +from watchdog.events import DirDeletedEvent, FileDeletedEvent, FileSystemEventHandler +from watchdog.observers import Observer + +class DirTrigger(FileSystemEventHandler): + + def __init__(self, dir_path, cool_time, max_time): + self._dir_path = dir_path + self._cool_time = cool_time + self._max_time = max_time + self._got_event = False + self._last_event_time = 0.0 + self._last_reset_time = 0.0 + self._lock = threading.Lock() + self._observer = Observer() + self._observer.schedule(self, path=dir_path, recursive=True) + + def start(self): + try: + self._observer.start() + except Exception as e: + logging.warning("Error starting file observer for %s: %s", self._dir_path, str(e)) + + def stop(self): + self._observer.stop() def is_triggering(self): - return False + self._lock.acquire() + try: + now = time.time() + return ( self._got_event and + (now - self._last_event_time > self._cool_time) ) or \ + now - self._last_reset_time > self._max_time + finally: + self._lock.release() + + def reset(self): + self._lock.acquire() + try: + self._got_event = False + self._last_reset_time = time.time() + finally: + self._lock.release() + + def on_any_event(self, event): + if event.event_type == FileDeletedEvent or event.event_type == DirDeletedEvent: + return + + self._lock.acquire() + try: + self._got_event = True + self._last_event_time = time.time() + finally: + self._lock.release()