2023-10-17 19:33:31 +01:00
|
|
|
import asyncio
|
2023-10-23 03:24:54 +01:00
|
|
|
import shutil
|
2023-11-12 23:20:40 +00:00
|
|
|
import stat
|
2023-11-08 20:38:40 +00:00
|
|
|
import sys
|
2023-10-17 19:33:31 +01:00
|
|
|
import threading
|
2023-10-19 21:52:37 +01:00
|
|
|
import time
|
2023-11-12 23:20:40 +00:00
|
|
|
from os import stat_result
|
2023-10-17 23:06:27 +01:00
|
|
|
from pathlib import Path, PurePosixPath
|
2023-10-14 23:29:50 +01:00
|
|
|
|
|
|
|
import msgspec
|
2023-11-12 23:20:40 +00:00
|
|
|
from natsort import humansorted, natsort_keygen, ns
|
2023-11-08 20:38:40 +00:00
|
|
|
from sanic.log import logging
|
2023-10-14 23:29:50 +01:00
|
|
|
|
2023-10-21 17:17:09 +01:00
|
|
|
from cista import config
|
2023-11-08 20:38:40 +00:00
|
|
|
from cista.fileio import fuid
|
2023-11-12 23:20:40 +00:00
|
|
|
from cista.protocol import FileEntry, Space, UpdDel, UpdIns, UpdKeep
|
2023-10-14 23:29:50 +01:00
|
|
|
|
|
|
|
pubsub = {}
|
2023-11-12 23:20:40 +00:00
|
|
|
sortkey = natsort_keygen(alg=ns.LOCALE)
|
|
|
|
|
|
|
|
|
|
|
|
class State:
|
|
|
|
def __init__(self):
|
|
|
|
self.lock = threading.RLock()
|
|
|
|
self._space = Space(0, 0, 0, 0)
|
|
|
|
self._listing: list[FileEntry] = []
|
|
|
|
|
|
|
|
@property
|
|
|
|
def space(self):
|
|
|
|
with self.lock:
|
|
|
|
return self._space
|
|
|
|
|
|
|
|
@space.setter
|
|
|
|
def space(self, space):
|
|
|
|
with self.lock:
|
|
|
|
self._space = space
|
|
|
|
|
|
|
|
@property
|
|
|
|
def root(self) -> list[FileEntry]:
|
|
|
|
with self.lock:
|
|
|
|
return self._listing[:]
|
|
|
|
|
|
|
|
@root.setter
|
|
|
|
def root(self, listing: list[FileEntry]):
|
|
|
|
with self.lock:
|
|
|
|
self._listing = listing
|
|
|
|
|
|
|
|
def _slice(self, idx: PurePosixPath | tuple[PurePosixPath, int]):
|
|
|
|
relpath, relfile = idx if isinstance(idx, tuple) else (idx, 0)
|
|
|
|
begin, end = 0, len(self._listing)
|
|
|
|
level = 0
|
|
|
|
isfile = 0
|
|
|
|
|
|
|
|
# Special case for root
|
|
|
|
if not relpath.parts:
|
|
|
|
return slice(begin, end)
|
|
|
|
|
|
|
|
begin += 1
|
|
|
|
for part in relpath.parts:
|
|
|
|
level += 1
|
|
|
|
found = False
|
|
|
|
|
|
|
|
while begin < end:
|
|
|
|
entry = self._listing[begin]
|
|
|
|
|
|
|
|
if entry.level < level:
|
|
|
|
break
|
|
|
|
|
|
|
|
if entry.level == level:
|
|
|
|
if entry.name == part:
|
|
|
|
found = True
|
|
|
|
if level == len(relpath.parts):
|
|
|
|
isfile = relfile
|
|
|
|
else:
|
|
|
|
begin += 1
|
|
|
|
break
|
|
|
|
cmp = entry.isfile - isfile or sortkey(entry.name) > sortkey(part)
|
|
|
|
if cmp > 0:
|
|
|
|
break
|
|
|
|
|
|
|
|
begin += 1
|
|
|
|
|
|
|
|
if not found:
|
|
|
|
return slice(begin, begin)
|
|
|
|
|
|
|
|
# Found the starting point, now find the end of the slice
|
|
|
|
for end in range(begin + 1, len(self._listing) + 1):
|
|
|
|
if end == len(self._listing) or self._listing[end].level <= level:
|
|
|
|
break
|
|
|
|
return slice(begin, end)
|
|
|
|
|
|
|
|
def __getitem__(self, index: PurePosixPath | tuple[PurePosixPath, int]):
|
|
|
|
with self.lock:
|
|
|
|
return self._listing[self._slice(index)]
|
|
|
|
|
|
|
|
def __setitem__(
|
|
|
|
self, index: tuple[PurePosixPath, int], value: list[FileEntry]
|
|
|
|
) -> None:
|
|
|
|
rel, isfile = index
|
|
|
|
with self.lock:
|
|
|
|
if rel.parts:
|
|
|
|
parent = self._slice(rel.parent)
|
|
|
|
if parent.start == parent.stop:
|
|
|
|
raise ValueError(
|
|
|
|
f"Parent folder {rel.as_posix()} is missing for {rel.name}"
|
|
|
|
)
|
|
|
|
self._listing[self._slice(index)] = value
|
|
|
|
|
|
|
|
def __delitem__(self, relpath: PurePosixPath):
|
|
|
|
with self.lock:
|
|
|
|
del self._listing[self._slice(relpath)]
|
|
|
|
|
|
|
|
|
|
|
|
state = State()
|
2023-10-23 22:57:50 +01:00
|
|
|
rootpath: Path = None # type: ignore
|
2023-10-19 21:52:37 +01:00
|
|
|
quit = False
|
2023-10-26 15:18:59 +01:00
|
|
|
modified_flags = (
|
|
|
|
"IN_CREATE",
|
|
|
|
"IN_DELETE",
|
|
|
|
"IN_DELETE_SELF",
|
|
|
|
"IN_MODIFY",
|
|
|
|
"IN_MOVE_SELF",
|
|
|
|
"IN_MOVED_FROM",
|
|
|
|
"IN_MOVED_TO",
|
|
|
|
)
|
2023-10-19 21:52:37 +01:00
|
|
|
|
2023-10-26 15:18:59 +01:00
|
|
|
|
2023-10-19 21:52:37 +01:00
|
|
|
def watcher_thread(loop):
|
2023-11-12 23:20:40 +00:00
|
|
|
global rootpath
|
2023-11-08 20:38:40 +00:00
|
|
|
import inotify.adapters
|
2023-10-23 03:24:54 +01:00
|
|
|
|
2023-10-19 21:52:37 +01:00
|
|
|
while True:
|
2023-10-23 22:57:50 +01:00
|
|
|
rootpath = config.config.path
|
2023-10-19 21:52:37 +01:00
|
|
|
i = inotify.adapters.InotifyTree(rootpath.as_posix())
|
2023-11-12 23:20:40 +00:00
|
|
|
# Initialize the tree from filesystem
|
|
|
|
new = walk()
|
|
|
|
with state.lock:
|
|
|
|
old = state.root
|
|
|
|
if old != new:
|
|
|
|
state.root = new
|
|
|
|
broadcast(format_update(old, new), loop)
|
2023-10-19 21:52:37 +01:00
|
|
|
|
2023-11-14 00:19:33 +00:00
|
|
|
# The watching is not entirely reliable, so do a full refresh every 30 seconds
|
|
|
|
refreshdl = time.monotonic() + 30.0
|
2023-10-19 21:52:37 +01:00
|
|
|
|
|
|
|
for event in i.event_gen():
|
2023-10-26 15:18:59 +01:00
|
|
|
if quit:
|
|
|
|
return
|
2023-10-23 22:57:50 +01:00
|
|
|
# Disk usage update
|
2023-10-23 03:24:54 +01:00
|
|
|
du = shutil.disk_usage(rootpath)
|
2023-11-12 23:20:40 +00:00
|
|
|
space = Space(*du, storage=state.root[0].size)
|
|
|
|
if space != state.space:
|
|
|
|
state.space = space
|
|
|
|
broadcast(format_space(space), loop)
|
2023-10-23 22:57:50 +01:00
|
|
|
break
|
|
|
|
# Do a full refresh?
|
2023-10-26 15:18:59 +01:00
|
|
|
if time.monotonic() > refreshdl:
|
|
|
|
break
|
|
|
|
if event is None:
|
|
|
|
continue
|
2023-10-19 21:52:37 +01:00
|
|
|
_, flags, path, filename = event
|
|
|
|
if not any(f in modified_flags for f in flags):
|
|
|
|
continue
|
2023-10-23 22:57:50 +01:00
|
|
|
# Update modified path
|
2023-10-19 21:52:37 +01:00
|
|
|
path = PurePosixPath(path) / filename
|
2023-10-23 22:57:50 +01:00
|
|
|
try:
|
|
|
|
update(path.relative_to(rootpath), loop)
|
|
|
|
except Exception as e:
|
2023-11-08 20:38:40 +00:00
|
|
|
print("Watching error", e, path, rootpath)
|
|
|
|
raise
|
2023-10-19 21:52:37 +01:00
|
|
|
i = None # Free the inotify object
|
2023-10-14 23:29:50 +01:00
|
|
|
|
2023-10-26 15:18:59 +01:00
|
|
|
|
2023-11-08 20:38:40 +00:00
|
|
|
def watcher_thread_poll(loop):
|
2023-11-12 23:20:40 +00:00
|
|
|
global rootpath
|
2023-11-08 20:38:40 +00:00
|
|
|
|
|
|
|
while not quit:
|
|
|
|
rootpath = config.config.path
|
2023-11-12 23:20:40 +00:00
|
|
|
new = walk()
|
|
|
|
with state.lock:
|
|
|
|
old = state.root
|
|
|
|
if old != new:
|
|
|
|
state.root = new
|
|
|
|
broadcast(format_update(old, new), loop)
|
2023-11-08 20:38:40 +00:00
|
|
|
|
|
|
|
# Disk usage update
|
|
|
|
du = shutil.disk_usage(rootpath)
|
2023-11-12 23:20:40 +00:00
|
|
|
space = Space(*du, storage=state.root[0].size)
|
|
|
|
if space != state.space:
|
|
|
|
state.space = space
|
|
|
|
broadcast(format_space(space), loop)
|
2023-11-08 20:38:40 +00:00
|
|
|
|
2023-11-12 23:20:40 +00:00
|
|
|
time.sleep(2.0)
|
2023-11-08 20:38:40 +00:00
|
|
|
|
|
|
|
|
2023-11-12 23:20:40 +00:00
|
|
|
def walk(rel=PurePosixPath()) -> list[FileEntry]: # noqa: B008
|
|
|
|
path = rootpath / rel
|
|
|
|
try:
|
|
|
|
st = path.stat()
|
|
|
|
except OSError:
|
|
|
|
return []
|
|
|
|
return _walk(rel, int(not stat.S_ISDIR(st.st_mode)), st)
|
2023-10-26 15:18:59 +01:00
|
|
|
|
2023-10-23 03:24:54 +01:00
|
|
|
|
2023-11-12 23:20:40 +00:00
|
|
|
def _walk(rel: PurePosixPath, isfile: int, st: stat_result) -> list[FileEntry]:
|
|
|
|
entry = FileEntry(
|
|
|
|
level=len(rel.parts),
|
|
|
|
name=rel.name,
|
|
|
|
key=fuid(st),
|
|
|
|
mtime=int(st.st_mtime),
|
|
|
|
size=st.st_size if isfile else 0,
|
|
|
|
isfile=isfile,
|
|
|
|
)
|
|
|
|
if isfile:
|
|
|
|
return [entry]
|
|
|
|
ret = [entry]
|
|
|
|
path = rootpath / rel
|
2023-10-14 23:29:50 +01:00
|
|
|
try:
|
2023-11-12 23:20:40 +00:00
|
|
|
li = []
|
|
|
|
for f in path.iterdir():
|
|
|
|
if f.name.startswith("."):
|
|
|
|
continue # No dotfiles
|
|
|
|
s = f.stat()
|
|
|
|
li.append((int(not stat.S_ISDIR(s.st_mode)), f.name, s))
|
|
|
|
for [isfile, name, s] in humansorted(li):
|
|
|
|
subtree = _walk(rel / name, isfile, s)
|
|
|
|
child = subtree[0]
|
|
|
|
entry.mtime = max(entry.mtime, child.mtime)
|
|
|
|
entry.size += child.size
|
|
|
|
ret.extend(subtree)
|
2023-10-17 19:33:31 +01:00
|
|
|
except FileNotFoundError:
|
2023-11-12 23:20:40 +00:00
|
|
|
pass # Things may be rapidly in motion
|
2023-10-14 23:29:50 +01:00
|
|
|
except OSError as e:
|
|
|
|
print("OS error walking path", path, e)
|
2023-11-12 23:20:40 +00:00
|
|
|
return ret
|
2023-10-14 23:29:50 +01:00
|
|
|
|
2023-10-26 15:18:59 +01:00
|
|
|
|
2023-10-23 22:57:50 +01:00
|
|
|
def update(relpath: PurePosixPath, loop):
|
2023-10-19 18:54:33 +01:00
|
|
|
"""Called by inotify updates, check the filesystem and broadcast any changes."""
|
2023-11-08 20:38:40 +00:00
|
|
|
if rootpath is None or relpath is None:
|
|
|
|
print("ERROR", rootpath, relpath)
|
2023-11-12 23:20:40 +00:00
|
|
|
new = walk(relpath)
|
|
|
|
with state.lock:
|
|
|
|
old = state[relpath]
|
|
|
|
if old == new:
|
|
|
|
return
|
|
|
|
old = state.root
|
|
|
|
if new:
|
|
|
|
state[relpath, new[0].isfile] = new
|
|
|
|
else:
|
|
|
|
del state[relpath]
|
|
|
|
broadcast(format_update(old, state.root), loop)
|
|
|
|
|
|
|
|
|
|
|
|
def format_update(old, new):
|
|
|
|
# Make keep/del/insert diff until one of the lists ends
|
|
|
|
oidx, nidx = 0, 0
|
2023-10-17 19:33:31 +01:00
|
|
|
update = []
|
2023-11-12 23:20:40 +00:00
|
|
|
keep_count = 0
|
|
|
|
while oidx < len(old) and nidx < len(new):
|
|
|
|
if old[oidx] == new[nidx]:
|
|
|
|
keep_count += 1
|
|
|
|
oidx += 1
|
|
|
|
nidx += 1
|
|
|
|
continue
|
|
|
|
if keep_count > 0:
|
|
|
|
update.append(UpdKeep(keep_count))
|
|
|
|
keep_count = 0
|
|
|
|
|
|
|
|
del_count = 0
|
|
|
|
rest = new[nidx:]
|
|
|
|
while oidx < len(old) and old[oidx] not in rest:
|
|
|
|
del_count += 1
|
|
|
|
oidx += 1
|
|
|
|
if del_count:
|
|
|
|
update.append(UpdDel(del_count))
|
|
|
|
continue
|
|
|
|
|
|
|
|
insert_items = []
|
|
|
|
rest = old[oidx:]
|
|
|
|
while nidx < len(new) and new[nidx] not in rest:
|
|
|
|
insert_items.append(new[nidx])
|
|
|
|
nidx += 1
|
|
|
|
update.append(UpdIns(insert_items))
|
|
|
|
|
|
|
|
# Diff any remaining
|
|
|
|
if keep_count > 0:
|
|
|
|
update.append(UpdKeep(keep_count))
|
|
|
|
if oidx < len(old):
|
|
|
|
update.append(UpdDel(len(old) - oidx))
|
|
|
|
elif nidx < len(new):
|
|
|
|
update.append(UpdIns(new[nidx:]))
|
|
|
|
|
|
|
|
return msgspec.json.encode({"update": update}).decode()
|
|
|
|
|
|
|
|
|
|
|
|
def format_space(usage):
|
|
|
|
return msgspec.json.encode({"space": usage}).decode()
|
|
|
|
|
|
|
|
|
|
|
|
def format_root(root):
|
|
|
|
return msgspec.json.encode({"root": root}).decode()
|
|
|
|
|
|
|
|
|
|
|
|
def broadcast(msg, loop):
|
|
|
|
return asyncio.run_coroutine_threadsafe(abroadcast(msg), loop).result()
|
|
|
|
|
|
|
|
|
|
|
|
async def abroadcast(msg):
|
2023-11-08 20:38:40 +00:00
|
|
|
try:
|
|
|
|
for queue in pubsub.values():
|
|
|
|
queue.put_nowait(msg)
|
|
|
|
except Exception:
|
|
|
|
# Log because asyncio would silently eat the error
|
|
|
|
logging.exception("Broadcast error")
|
|
|
|
|
2023-10-17 19:33:31 +01:00
|
|
|
|
2023-10-23 02:51:39 +01:00
|
|
|
async def start(app, loop):
|
|
|
|
config.load_config()
|
2023-11-14 00:19:33 +00:00
|
|
|
use_inotify = sys.platform == "linux"
|
2023-11-08 20:38:40 +00:00
|
|
|
app.ctx.watcher = threading.Thread(
|
2023-11-12 23:20:40 +00:00
|
|
|
target=watcher_thread if use_inotify else watcher_thread_poll,
|
2023-11-08 20:38:40 +00:00
|
|
|
args=[loop],
|
|
|
|
)
|
2023-10-23 02:51:39 +01:00
|
|
|
app.ctx.watcher.start()
|
2023-10-17 19:33:31 +01:00
|
|
|
|
2023-10-26 15:18:59 +01:00
|
|
|
|
2023-10-23 02:51:39 +01:00
|
|
|
async def stop(app, loop):
|
|
|
|
global quit
|
|
|
|
quit = True
|
|
|
|
app.ctx.watcher.join()
|