Files
am-downloader/am_deduper/watcher.py
T

67 lines
2.0 KiB
Python

from __future__ import annotations
import time
from pathlib import Path
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
from .constants import MUSIC_EXTENSIONS, STABILITY_CHECKS, STABILITY_INTERVAL_SECONDS
from .db import connect
from .exact import exact_dedupe
from .l2 import acoustic_dedupe
from .scanner import index_file
class Handler(FileSystemEventHandler):
def __init__(self, root: Path, db_path: Path, l2: bool = False):
self.root = root
self.db_path = db_path
self.l2 = l2
def _process(self, filename: str) -> None:
path = Path(filename)
if path.is_symlink() or path.suffix.lower() not in MUSIC_EXTENSIONS or ".dedupe" in path.parts:
return
try:
previous = path.stat().st_size
stable = 0
while stable < STABILITY_CHECKS - 1:
time.sleep(STABILITY_INTERVAL_SECONDS)
size = path.stat().st_size
if size == previous:
stable += 1
else:
previous = size
stable = 0
with connect(self.db_path) as conn:
index_file(conn, path)
# Exact dedupe is byte-for-byte safe. Acoustic dedupe is opt-in.
exact_dedupe(self.db_path, self.root)
if self.l2:
acoustic_dedupe(self.db_path, self.root)
except (FileNotFoundError, PermissionError, OSError):
return
def on_created(self, event):
if not event.is_directory:
self._process(event.src_path)
def on_moved(self, event):
if not event.is_directory:
self._process(event.dest_path)
def watch(root: Path, db_path: Path, l2: bool = False) -> None:
root = root.resolve()
observer = Observer()
observer.schedule(Handler(root, db_path, l2=l2), str(root), recursive=True)
observer.start()
try:
while True:
time.sleep(1)
finally:
observer.stop()
observer.join()