2023-10-17 19:33:31 +01:00
|
|
|
import asyncio
|
2023-10-23 03:24:54 +01:00
|
|
|
import shutil
|
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-10-17 23:06:27 +01:00
|
|
|
from pathlib import Path, PurePosixPath
|
2023-10-14 23:29:50 +01:00
|
|
|
|
|
|
|
import msgspec
|
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-10-21 17:17:09 +01:00
|
|
|
from cista.protocol import DirEntry, FileEntry, UpdateEntry
|
2023-10-14 23:29:50 +01:00
|
|
|
|
|
|
|
pubsub = {}
|
2023-10-19 21:52:37 +01:00
|
|
|
tree = {"": None}
|
|
|
|
tree_lock = threading.Lock()
|
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-23 03:24:54 +01:00
|
|
|
disk_usage = None
|
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-08 20:38:40 +00:00
|
|
|
global disk_usage, rootpath
|
|
|
|
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-10-23 03:24:54 +01:00
|
|
|
old = format_tree() if tree[""] else None
|
2023-10-19 21:52:37 +01:00
|
|
|
with tree_lock:
|
|
|
|
# Initialize the tree from filesystem
|
|
|
|
tree[""] = walk(rootpath)
|
2023-10-23 03:24:54 +01:00
|
|
|
msg = format_tree()
|
2023-10-19 21:52:37 +01:00
|
|
|
if msg != old:
|
|
|
|
asyncio.run_coroutine_threadsafe(broadcast(msg), loop)
|
|
|
|
|
|
|
|
# The watching is not entirely reliable, so do a full refresh every minute
|
|
|
|
refreshdl = time.monotonic() + 60.0
|
|
|
|
|
|
|
|
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)
|
|
|
|
if du != disk_usage:
|
|
|
|
disk_usage = du
|
|
|
|
asyncio.run_coroutine_threadsafe(broadcast(format_du()), 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):
|
|
|
|
global disk_usage, rootpath
|
|
|
|
|
|
|
|
while not quit:
|
|
|
|
rootpath = config.config.path
|
|
|
|
old = format_tree() if tree[""] else None
|
|
|
|
with tree_lock:
|
|
|
|
# Initialize the tree from filesystem
|
|
|
|
tree[""] = walk(rootpath)
|
|
|
|
msg = format_tree()
|
|
|
|
if msg != old:
|
|
|
|
asyncio.run_coroutine_threadsafe(broadcast(msg), loop)
|
|
|
|
|
|
|
|
# Disk usage update
|
|
|
|
du = shutil.disk_usage(rootpath)
|
|
|
|
if du != disk_usage:
|
|
|
|
disk_usage = du
|
|
|
|
asyncio.run_coroutine_threadsafe(broadcast(format_du()), loop)
|
|
|
|
|
|
|
|
time.sleep(1.0)
|
|
|
|
|
|
|
|
|
2023-10-23 03:24:54 +01:00
|
|
|
def format_du():
|
2023-10-26 15:18:59 +01:00
|
|
|
return msgspec.json.encode(
|
|
|
|
{
|
|
|
|
"space": {
|
|
|
|
"disk": disk_usage.total,
|
|
|
|
"used": disk_usage.used,
|
|
|
|
"free": disk_usage.free,
|
|
|
|
"storage": tree[""].size,
|
2023-11-08 20:38:40 +00:00
|
|
|
},
|
|
|
|
},
|
2023-10-26 15:18:59 +01:00
|
|
|
).decode()
|
|
|
|
|
2023-10-23 03:24:54 +01:00
|
|
|
|
|
|
|
def format_tree():
|
|
|
|
root = tree[""]
|
2023-11-08 20:38:40 +00:00
|
|
|
return msgspec.json.encode({"root": root}).decode()
|
2023-10-26 15:18:59 +01:00
|
|
|
|
2023-10-23 03:24:54 +01:00
|
|
|
|
2023-10-19 00:06:14 +01:00
|
|
|
def walk(path: Path) -> DirEntry | FileEntry | None:
|
2023-10-14 23:29:50 +01:00
|
|
|
try:
|
|
|
|
s = path.stat()
|
2023-11-08 20:38:40 +00:00
|
|
|
key = fuid(s)
|
|
|
|
assert key, repr(key)
|
2023-10-14 23:29:50 +01:00
|
|
|
mtime = int(s.st_mtime)
|
|
|
|
if path.is_file():
|
2023-11-08 20:38:40 +00:00
|
|
|
return FileEntry(key, s.st_size, mtime)
|
2023-10-14 23:29:50 +01:00
|
|
|
|
2023-10-26 15:18:59 +01:00
|
|
|
tree = {
|
|
|
|
p.name: v
|
|
|
|
for p in path.iterdir()
|
|
|
|
if not p.name.startswith(".")
|
|
|
|
if (v := walk(p)) is not None
|
|
|
|
}
|
2023-10-14 23:29:50 +01:00
|
|
|
if tree:
|
|
|
|
size = sum(v.size for v in tree.values())
|
2023-11-08 20:38:40 +00:00
|
|
|
mtime = max(mtime, *(v.mtime for v in tree.values()))
|
2023-10-14 23:29:50 +01:00
|
|
|
else:
|
|
|
|
size = 0
|
2023-11-08 20:38:40 +00:00
|
|
|
return DirEntry(key, size, mtime, tree)
|
2023-10-17 19:33:31 +01:00
|
|
|
except FileNotFoundError:
|
|
|
|
return None
|
2023-10-14 23:29:50 +01:00
|
|
|
except OSError as e:
|
|
|
|
print("OS error walking path", path, e)
|
|
|
|
return None
|
|
|
|
|
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-10-19 00:06:14 +01:00
|
|
|
new = walk(rootpath / relpath)
|
2023-10-17 19:33:31 +01:00
|
|
|
with tree_lock:
|
2023-10-19 18:54:33 +01:00
|
|
|
update = update_internal(relpath, new)
|
2023-10-26 15:18:59 +01:00
|
|
|
if not update:
|
|
|
|
return # No changes
|
2023-10-19 18:54:33 +01:00
|
|
|
msg = msgspec.json.encode({"update": update}).decode()
|
2023-10-17 19:33:31 +01:00
|
|
|
asyncio.run_coroutine_threadsafe(broadcast(msg), loop)
|
|
|
|
|
2023-10-26 15:18:59 +01:00
|
|
|
|
|
|
|
def update_internal(
|
2023-11-08 20:38:40 +00:00
|
|
|
relpath: PurePosixPath,
|
|
|
|
new: DirEntry | FileEntry | None,
|
2023-10-26 15:18:59 +01:00
|
|
|
) -> list[UpdateEntry]:
|
2023-10-17 19:33:31 +01:00
|
|
|
path = "", *relpath.parts
|
|
|
|
old = tree
|
|
|
|
elems = []
|
|
|
|
for name in path:
|
|
|
|
if name not in old:
|
|
|
|
# File or folder created
|
|
|
|
old = None
|
|
|
|
elems.append((name, None))
|
|
|
|
if len(elems) < len(path):
|
2023-10-19 18:54:33 +01:00
|
|
|
# We got a notify for an item whose parent is not in tree
|
|
|
|
print("Tree out of sync DEBUG", relpath)
|
|
|
|
print(elems)
|
|
|
|
print("Current tree:")
|
|
|
|
print(tree[""])
|
|
|
|
print("Walking all:")
|
|
|
|
print(walk(rootpath))
|
2023-10-17 19:33:31 +01:00
|
|
|
raise ValueError("Tree out of sync")
|
2023-10-14 23:29:50 +01:00
|
|
|
break
|
2023-10-17 19:33:31 +01:00
|
|
|
old = old[name]
|
|
|
|
elems.append((name, old))
|
2023-10-14 23:29:50 +01:00
|
|
|
if old == new:
|
2023-10-19 18:54:33 +01:00
|
|
|
return []
|
2023-10-17 19:33:31 +01:00
|
|
|
mt = new.mtime if new else 0
|
|
|
|
szdiff = (new.size if new else 0) - (old.size if old else 0)
|
|
|
|
# Update parents
|
|
|
|
update = []
|
|
|
|
for name, entry in elems[:-1]:
|
2023-11-08 20:38:40 +00:00
|
|
|
u = UpdateEntry(name, entry.key)
|
2023-10-17 19:33:31 +01:00
|
|
|
if szdiff:
|
|
|
|
entry.size += szdiff
|
|
|
|
u.size = entry.size
|
|
|
|
if mt > entry.mtime:
|
|
|
|
u.mtime = entry.mtime = mt
|
|
|
|
update.append(u)
|
|
|
|
# The last element is the one that changed
|
|
|
|
name, entry = elems[-1]
|
|
|
|
parent = elems[-2][1] if len(elems) > 1 else tree
|
2023-11-08 20:38:40 +00:00
|
|
|
u = UpdateEntry(name, new.key if new else entry.key)
|
2023-10-17 19:33:31 +01:00
|
|
|
if new:
|
|
|
|
parent[name] = new
|
2023-10-26 15:18:59 +01:00
|
|
|
if u.size != new.size:
|
|
|
|
u.size = new.size
|
|
|
|
if u.mtime != new.mtime:
|
|
|
|
u.mtime = new.mtime
|
2023-11-08 20:38:40 +00:00
|
|
|
if isinstance(new, DirEntry) and u.dir != new.dir:
|
|
|
|
u.dir = new.dir
|
2023-10-17 19:33:31 +01:00
|
|
|
else:
|
|
|
|
del parent[name]
|
|
|
|
u.deleted = True
|
|
|
|
update.append(u)
|
2023-10-19 18:54:33 +01:00
|
|
|
return update
|
2023-10-17 19:33:31 +01:00
|
|
|
|
2023-10-26 15:18:59 +01:00
|
|
|
|
2023-10-17 19:33:31 +01:00
|
|
|
async def broadcast(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-08 20:38:40 +00:00
|
|
|
app.ctx.watcher = threading.Thread(
|
|
|
|
target=watcher_thread if sys.platform == "linux" else watcher_thread_poll,
|
|
|
|
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()
|