Initial commit: headless Common Lisp Nextcloud sync client and Waybar widget
This commit is contained in:
commit
e5c0f60122
25 files changed
+4293
No files matched your search
@@ -0,0 +1,8 @@
|
||||
/nextcloud-niri
|
||||
*.fasl
|
||||
*.lx64fsl
|
||||
*.dx64fsl
|
||||
*.tmp
|
||||
*~
|
||||
.#*
|
||||
#*#
|
||||
@@ -0,0 +1,42 @@
|
||||
SBCL ?= sbcl
|
||||
PREFIX ?= $(HOME)/.local
|
||||
BINDIR ?= $(PREFIX)/bin
|
||||
SYSTEMD_USER_DIR ?= $(HOME)/.config/systemd/user
|
||||
BIN := nextcloud-niri
|
||||
|
||||
.PHONY: all build test install uninstall clean
|
||||
|
||||
all: build
|
||||
|
||||
build: $(BIN)
|
||||
|
||||
$(BIN): nextcloud-niri.asd build.lisp src/*.lisp
|
||||
$(SBCL) --non-interactive \
|
||||
--load build.lisp \
|
||||
--eval '(ql:quickload :nextcloud-niri :silent t)' \
|
||||
--eval '(sb-ext:save-lisp-and-die "$(BIN)" :toplevel (function nextcloud-niri:main) :executable t :compression t)'
|
||||
|
||||
test:
|
||||
$(SBCL) --non-interactive \
|
||||
--load build.lisp \
|
||||
--eval '(ql:quickload :nextcloud-niri/tests :silent t)' \
|
||||
--eval '(unless (nextcloud-niri.tests:run-all-tests) (sb-ext:exit :code 1))'
|
||||
|
||||
install: build
|
||||
install -d "$(BINDIR)"
|
||||
install -m 755 "$(BIN)" "$(BINDIR)/$(BIN)"
|
||||
install -d "$(SYSTEMD_USER_DIR)"
|
||||
install -m 644 systemd/nextcloud-niri.service "$(SYSTEMD_USER_DIR)/nextcloud-niri.service"
|
||||
@echo ""
|
||||
@echo "Installed $(BINDIR)/$(BIN) and $(SYSTEMD_USER_DIR)/nextcloud-niri.service"
|
||||
@echo "Next steps:"
|
||||
@echo " 1. nextcloud-niri login https://your-nextcloud.example.com"
|
||||
@echo " 2. nextcloud-niri add ~/Documents/Notes Documents/Notes"
|
||||
@echo " 3. systemctl --user daemon-reload && systemctl --user enable --now nextcloud-niri.service"
|
||||
@echo " 4. Add waybar/config.snippet.jsonc and waybar/style.snippet.css to ~/.config/waybar/"
|
||||
|
||||
uninstall:
|
||||
rm -f "$(BINDIR)/$(BIN)" "$(SYSTEMD_USER_DIR)/nextcloud-niri.service"
|
||||
|
||||
clean:
|
||||
rm -f "$(BIN)"
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#+TITLE: nextcloud-niri
|
||||
#+AUTHOR: venomade
|
||||
#+OPTIONS: toc:nil
|
||||
|
||||
A lightweight, headless Common Lisp (SBCL) Nextcloud bidirectional sync client and Waybar text widget for *niri* — zero Qt, zero GUI bloat.
|
||||
|
||||
* Features
|
||||
|
||||
- *Real 3-way bidirectional WebDAV sync*:
|
||||
- Uploads local edits (with =X-OC-Mtime=), downloads remote edits (preserving timestamps atomically), and propagates deletions in both directions.
|
||||
- *Nextcloud =oc:etag= pruning*: periodic remote polls issue a single =PROPFIND Depth: 0= when nothing changed on the server, and prune unchanged subdirectories during scans.
|
||||
- *Conflict-safe*: concurrent edits to the same file never lose data — local changes are preserved as =<name> (conflicted copy YYYY-MM-DD HHMMSS)<ext>= and synced alongside the remote version.
|
||||
- *SHA-256 content verification*: touching a file's mtime without modifying bytes won't trigger redundant uploads.
|
||||
- *Nextcloud Chunked Upload v2*: files larger than =:chunk-size-mb= (default 10 MB) are uploaded in chunks to avoid reverse-proxy size limits.
|
||||
- *Missing-folder safety guard*: if a synced local directory disappears (e.g., unmounted drive), sync stops with an error instead of deleting remote files.
|
||||
- *Instant local watching*: pure SBCL =sb-alien= Linux =inotify= recursive watcher (automatically tracks new subdirectories, debounces rapid editor saves).
|
||||
- *Nextcloud Login Flow v2*: authenticate in your browser (supports 2FA/SSO) and receive a dedicated Nextcloud app password stored with =0600= permissions — or use =:password-cmd= (e.g., =pass=, =secret-tool=).
|
||||
- *Waybar native text widget*:
|
||||
- Instant updates via Waybar =SIGRTMIN+7= (no polling lag).
|
||||
- Clean lowercase text states:
|
||||
- =nc= — synced
|
||||
- =nc *= / =nc *3= — unsynced (local changes pending)
|
||||
- =nc ...= / =nc 2/5= — actively syncing
|
||||
- =nc != — problem syncing (hover tooltip shows exact error)
|
||||
- =nc paused= — paused
|
||||
- =nc off= — daemon stopped
|
||||
- Left-click to sync immediately, right-click to pause/resume.
|
||||
|
||||
* Build & Install
|
||||
|
||||
Requires SBCL and Quicklisp.
|
||||
|
||||
#+begin_src bash
|
||||
./build.sh test # run full end-to-end test suite (69 assertions)
|
||||
./build.sh build # compile standalone native binary ./nextcloud-niri
|
||||
./build.sh install # install to ~/.local/bin/nextcloud-niri + systemd user unit
|
||||
#+end_src
|
||||
|
||||
A =Makefile= with identical targets is also included.
|
||||
|
||||
* Quick Start
|
||||
|
||||
1. *Authenticate* with your Nextcloud server (opens browser via Login Flow v2; pass =--manual= to enter username & app password directly):
|
||||
#+begin_src bash
|
||||
nextcloud-niri login https://cloud.example.com
|
||||
#+end_src
|
||||
|
||||
2. *Add synced folder pairs*:
|
||||
#+begin_src bash
|
||||
nextcloud-niri add ~/Documents/Notes Documents/Notes
|
||||
#+end_src
|
||||
Or edit =~/.config/nextcloud-niri/config.sexp= directly (see [[file:config.example.sexp][config.example.sexp]]).
|
||||
|
||||
3. *Start the background daemon* (starts automatically with =niri.service=):
|
||||
#+begin_src bash
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user enable --now nextcloud-niri.service
|
||||
#+end_src
|
||||
|
||||
4. *Add the Waybar widget*:
|
||||
- Copy [[file:waybar/config.snippet.jsonc][waybar/config.snippet.jsonc]] into =~/.config/waybar/config= and add ="custom/nextcloud"= to ="modules-right"=.
|
||||
- Append [[file:waybar/style.snippet.css][waybar/style.snippet.css]] to =~/.config/waybar/style.css=.
|
||||
- Reload Waybar (=pkill -SIGUSR2 waybar=).
|
||||
|
||||
* CLI Reference
|
||||
|
||||
#+begin_example
|
||||
nextcloud-niri waybar # Print Waybar JSON status
|
||||
nextcloud-niri daemon # Run background sync daemon
|
||||
nextcloud-niri sync [--full] # Trigger sync (or one-shot if daemon stopped)
|
||||
nextcloud-niri status # Show status in terminal
|
||||
nextcloud-niri pause | resume | toggle # Pause/resume background daemon
|
||||
nextcloud-niri reload # Reload config.sexp in running daemon
|
||||
nextcloud-niri login <url> [--manual] # Authenticate via Login Flow v2
|
||||
nextcloud-niri add <local> <remote> [--name N] # Add synced folder pair
|
||||
nextcloud-niri remove <name> # Remove synced folder pair
|
||||
nextcloud-niri list # List configured folder pairs
|
||||
#+end_example
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
;;;; Helper loader for building and testing nextcloud-niri on Guix/Ubuntu/Linux
|
||||
;;;; Ensures CFFI can locate OpenSSL 3 libraries before cl+ssl / dexador loads.
|
||||
|
||||
(ql:quickload :cffi :silent t)
|
||||
|
||||
(defun %find-openssl3-dir ()
|
||||
(let ((candidates
|
||||
(append
|
||||
(list (merge-pathnames ".guix-home/profile/lib/" (user-homedir-pathname))
|
||||
#P"/run/current-system/profile/lib/"
|
||||
#P"/usr/lib/x86_64-linux-gnu/"
|
||||
#P"/usr/lib64/"
|
||||
#P"/usr/lib/")
|
||||
(sort (directory #P"/gnu/store/*-openssl-3.*/lib/")
|
||||
#'string> :key #'namestring))))
|
||||
(dolist (dir candidates)
|
||||
(when (and dir
|
||||
(probe-file (merge-pathnames "libcrypto.so.3" dir))
|
||||
(probe-file (merge-pathnames "libssl.so.3" dir)))
|
||||
(return dir)))))
|
||||
|
||||
(let ((ssl-dir (%find-openssl3-dir)))
|
||||
(when ssl-dir
|
||||
(pushnew ssl-dir cffi:*foreign-library-directories* :test #'equal)))
|
||||
|
||||
(pushnew (truename *default-pathname-defaults*)
|
||||
asdf:*central-registry*
|
||||
:test #'equal)
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
SBCL="${SBCL:-sbcl}"
|
||||
PREFIX="${PREFIX:-$HOME/.local}"
|
||||
BINDIR="${BINDIR:-$PREFIX/bin}"
|
||||
SYSTEMD_USER_DIR="${SYSTEMD_USER_DIR:-$HOME/.config/systemd/user}"
|
||||
BIN="nextcloud-niri"
|
||||
|
||||
cmd="${1:-build}"
|
||||
|
||||
case "$cmd" in
|
||||
build)
|
||||
"$SBCL" --non-interactive \
|
||||
--load build.lisp \
|
||||
--eval '(ql:quickload :nextcloud-niri :silent t)' \
|
||||
--eval "(sb-ext:save-lisp-and-die \"$BIN\" :toplevel (function nextcloud-niri:main) :executable t :compression t)"
|
||||
echo "Built ./$BIN"
|
||||
;;
|
||||
test)
|
||||
"$SBCL" --non-interactive \
|
||||
--load build.lisp \
|
||||
--eval '(ql:quickload :nextcloud-niri/tests :silent t)' \
|
||||
--eval '(unless (nextcloud-niri.tests:run-all-tests) (sb-ext:exit :code 1))'
|
||||
;;
|
||||
install)
|
||||
"$0" build
|
||||
install -d "$BINDIR"
|
||||
install -m 755 "$BIN" "$BINDIR/$BIN"
|
||||
install -d "$SYSTEMD_USER_DIR"
|
||||
install -m 644 systemd/nextcloud-niri.service "$SYSTEMD_USER_DIR/nextcloud-niri.service"
|
||||
echo ""
|
||||
echo "Installed $BINDIR/$BIN and $SYSTEMD_USER_DIR/nextcloud-niri.service"
|
||||
echo "Next steps:"
|
||||
echo " 1. nextcloud-niri login https://your-nextcloud.example.com"
|
||||
echo " 2. nextcloud-niri add ~/Documents/Notes Documents/Notes"
|
||||
echo " 3. systemctl --user daemon-reload && systemctl --user enable --now nextcloud-niri.service"
|
||||
echo " 4. Add waybar/config.snippet.jsonc and waybar/style.snippet.css to ~/.config/waybar/"
|
||||
;;
|
||||
uninstall)
|
||||
rm -f "$BINDIR/$BIN" "$SYSTEMD_USER_DIR/nextcloud-niri.service"
|
||||
echo "Uninstalled $BINDIR/$BIN and systemd unit."
|
||||
;;
|
||||
clean)
|
||||
rm -f "$BIN"
|
||||
;;
|
||||
*)
|
||||
echo "Usage: $0 {build|test|install|uninstall|clean}" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,41 @@
|
||||
;; nextcloud-niri configuration (~/.config/nextcloud-niri/config.sexp)
|
||||
;;
|
||||
;; Run `nextcloud-niri login https://your-nextcloud.example.com` to authenticate
|
||||
;; via Nextcloud Login Flow v2, and `nextcloud-niri add <local> <remote>` to add
|
||||
;; synced folder pairs.
|
||||
|
||||
(:server
|
||||
(:url "https://cloud.example.com"
|
||||
:username "your-username"
|
||||
;; Optional command whose stdout provides the app password, e.g.:
|
||||
;; "pass show nextcloud"
|
||||
;; "secret-tool lookup service nextcloud"
|
||||
;; When nil, credentials are read from ~/.config/nextcloud-niri/credentials.sexp
|
||||
:password-cmd nil
|
||||
:verify-ssl t)
|
||||
|
||||
:sync
|
||||
(:poll-interval 30
|
||||
:debounce-seconds 2.0
|
||||
:chunk-size-mb 10
|
||||
:create-remote-if-missing t
|
||||
:notify-on-error t
|
||||
:ignore (".git"
|
||||
".DS_Store"
|
||||
"Thumbs.db"
|
||||
"*.tmp"
|
||||
"*.part"
|
||||
"*.swp"
|
||||
"*.swo"
|
||||
"*~"
|
||||
".~lock.*"
|
||||
"#*#"))
|
||||
|
||||
:waybar
|
||||
(:signal 7
|
||||
:label "nc")
|
||||
|
||||
:folders
|
||||
((:name "Notes"
|
||||
:local "~/Documents/Notes"
|
||||
:remote "Documents/Notes")))
|
||||
@@ -0,0 +1,47 @@
|
||||
(asdf:defsystem "nextcloud-niri"
|
||||
:description "Lightweight non-Qt Nextcloud bidirectional sync client and Waybar widget"
|
||||
:version "0.1.0"
|
||||
:author "venomade"
|
||||
:license "MIT"
|
||||
:depends-on ("alexandria"
|
||||
"babel"
|
||||
"bordeaux-threads"
|
||||
"cffi"
|
||||
"cl-base64"
|
||||
"cl-ppcre"
|
||||
"com.inuoe.jzon"
|
||||
"dexador"
|
||||
"flexi-streams"
|
||||
"ironclad"
|
||||
"local-time"
|
||||
"plump"
|
||||
"quri"
|
||||
"uiop")
|
||||
:serial t
|
||||
:components ((:module "src"
|
||||
:components ((:file "package")
|
||||
(:file "ssl-setup")
|
||||
(:file "config")
|
||||
(:file "journal")
|
||||
(:file "webdav")
|
||||
(:file "sync")
|
||||
(:file "inotify")
|
||||
(:file "status")
|
||||
(:file "ipc")
|
||||
(:file "daemon")
|
||||
(:file "waybar")
|
||||
(:file "cli"))))
|
||||
:in-order-to ((asdf:test-op (asdf:test-op "nextcloud-niri/tests"))))
|
||||
|
||||
(asdf:defsystem "nextcloud-niri/tests"
|
||||
:description "Test suite for nextcloud-niri"
|
||||
:depends-on ("nextcloud-niri")
|
||||
:serial t
|
||||
:components ((:module "tests"
|
||||
:components ((:file "package")
|
||||
(:file "mock-webdav")
|
||||
(:file "tests"))))
|
||||
:perform (asdf:test-op (op c)
|
||||
(declare (ignore op c))
|
||||
(unless (uiop:symbol-call :nextcloud-niri.tests :run-all-tests)
|
||||
(error "nextcloud-niri test suite failed."))))
|
||||
+289
@@ -0,0 +1,289 @@
|
||||
(in-package #:nextcloud-niri)
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Command-Line Interface
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun %print-help ()
|
||||
(format t "~
|
||||
nextcloud-niri - Lightweight non-Qt Nextcloud sync client & Waybar widget
|
||||
|
||||
Usage:
|
||||
nextcloud-niri <command> [args...]
|
||||
|
||||
Commands:
|
||||
waybar Print Waybar JSON status (fast, single-shot)
|
||||
daemon Run the background sync daemon
|
||||
sync [--full] Trigger immediate sync (via daemon, or one-shot)
|
||||
status Print human-readable sync status
|
||||
pause | resume | toggle Control background daemon syncing
|
||||
reload Reload config.sexp in running daemon
|
||||
|
||||
login <server-url> [--manual] Authenticate via Login Flow v2 (or --manual)
|
||||
init Create a starter config.sexp if missing
|
||||
add <local> <remote> [--name N] Add a local <-> remote synced folder pair
|
||||
remove <name> Remove a synced folder pair by name
|
||||
list List configured synced folder pairs
|
||||
help Show this help message
|
||||
|
||||
Paths:
|
||||
Config: ~a
|
||||
Credentials: ~a
|
||||
State: ~a
|
||||
Runtime: ~a
|
||||
"
|
||||
(config-path) (credentials-path) (state-dir) (runtime-dir)))
|
||||
|
||||
(defun %cmd-init ()
|
||||
(let ((p (config-path)))
|
||||
(if (probe-file (uiop:parse-native-namestring p))
|
||||
(format t "Config already exists: ~a~%" p)
|
||||
(progn
|
||||
(save-config (make-app-config) p)
|
||||
(format t "Created starter config: ~a~%" p)))))
|
||||
|
||||
(defun %prompt (label &key secret)
|
||||
(format t "~a" label)
|
||||
(finish-output)
|
||||
(if secret
|
||||
(progn
|
||||
(ignore-errors (uiop:run-program '("stty" "-echo") :input :interactive :ignore-error-status t))
|
||||
(unwind-protect
|
||||
(prog1 (or (read-line *standard-input* nil "") "")
|
||||
(terpri))
|
||||
(ignore-errors (uiop:run-program '("stty" "echo") :input :interactive :ignore-error-status t))))
|
||||
(string-trim '(#\Space #\Tab #\Return #\Newline)
|
||||
(or (read-line *standard-input* nil "") ""))))
|
||||
|
||||
(defun %cmd-login (args)
|
||||
(let* ((manual (member "--manual" args :test #'string=))
|
||||
(insecure (member "--insecure" args :test #'string=))
|
||||
(positional (remove-if (lambda (a) (alex:starts-with-subseq "--" a)) args))
|
||||
(url (first positional)))
|
||||
(unless (and url (> (length url) 0))
|
||||
(format *error-output* "Usage: nextcloud-niri login <https://your-nextcloud.example.com> [--manual]~%")
|
||||
(return-from %cmd-login 1))
|
||||
(setf url (string-right-trim "/" url))
|
||||
(unless (or (alex:starts-with-subseq "https://" url)
|
||||
(alex:starts-with-subseq "http://" url))
|
||||
(setf url (concatenate 'string "https://" url)))
|
||||
(let ((verify-ssl (not insecure))
|
||||
(final-url url)
|
||||
(username "")
|
||||
(password ""))
|
||||
(if manual
|
||||
(progn
|
||||
(setf username (%prompt "Username: ")
|
||||
password (%prompt "App Password: " :secret t)))
|
||||
(progn
|
||||
(format t "Starting Nextcloud Login Flow v2 for ~a...~%" url)
|
||||
(multiple-value-bind (login-url poll-endpoint poll-token)
|
||||
(nextcloud-login-flow-start url :verify-ssl verify-ssl)
|
||||
(format t "~%Open this URL in your browser to authorize nextcloud-niri:~% ~a~%~%" login-url)
|
||||
(ignore-errors
|
||||
(uiop:launch-program (list "xdg-open" login-url)
|
||||
:output nil :error-output nil))
|
||||
(format t "Waiting for authorization...")
|
||||
(finish-output)
|
||||
(loop for attempt from 1 to 150
|
||||
do (sleep 2)
|
||||
(multiple-value-bind (srv user pw)
|
||||
(nextcloud-login-flow-poll poll-endpoint poll-token :verify-ssl verify-ssl)
|
||||
(when srv
|
||||
(setf final-url (string-right-trim "/" srv)
|
||||
username user
|
||||
password pw)
|
||||
(format t " authorized!~%")
|
||||
(return)))
|
||||
(write-char #\.)
|
||||
(finish-output)
|
||||
finally (progn
|
||||
(format *error-output* "~%Timed out waiting for login.~%")
|
||||
(return-from %cmd-login 1))))))
|
||||
|
||||
;; Verify credentials with a lightweight PROPFIND Depth 0 on root
|
||||
(format t "Verifying WebDAV access for ~a @ ~a...~%" username final-url)
|
||||
(let ((client (make-webdav-client :url final-url
|
||||
:username username
|
||||
:password password
|
||||
:verify-ssl verify-ssl)))
|
||||
(webdav-propfind client "" :depth 0))
|
||||
|
||||
(save-credentials :url final-url :username username :password password)
|
||||
(let ((cfg (load-config)))
|
||||
(setf (server-url (config-server cfg)) final-url
|
||||
(server-username (config-server cfg)) username
|
||||
(server-verify-ssl (config-server cfg)) verify-ssl)
|
||||
(save-config cfg))
|
||||
(format t "Saved credentials (chmod 600): ~a~%" (credentials-path))
|
||||
(format t "Updated config: ~a~%" (config-path))
|
||||
(ipc-send-command "reload")
|
||||
0)))
|
||||
|
||||
(defun %cmd-add (args)
|
||||
(let ((name nil)
|
||||
(pos '()))
|
||||
(loop while args
|
||||
for a = (pop args)
|
||||
do (cond
|
||||
((or (string= a "--name") (string= a "-n"))
|
||||
(setf name (pop args)))
|
||||
(t (push a pos))))
|
||||
(setf pos (nreverse pos))
|
||||
(unless (= (length pos) 2)
|
||||
(format *error-output* "Usage: nextcloud-niri add <local-path> <remote-path> [--name <name>]~%")
|
||||
(return-from %cmd-add 1))
|
||||
(let* ((local-abs (expand-user-path (first pos)))
|
||||
(remote (string-trim "/" (second pos)))
|
||||
(slash (position #\/ local-abs :from-end t))
|
||||
(folder-name (or name (if slash (subseq local-abs (1+ slash)) local-abs)))
|
||||
(cfg (load-config)))
|
||||
(when (find folder-name (config-folders cfg) :key #'folder-name :test #'string=)
|
||||
(format *error-output* "A folder named ~s already exists in config.~%" folder-name)
|
||||
(return-from %cmd-add 1))
|
||||
(setf (config-folders cfg)
|
||||
(append (config-folders cfg)
|
||||
(list (make-folder-config :name folder-name
|
||||
:local local-abs
|
||||
:remote remote))))
|
||||
(save-config cfg)
|
||||
(format t "Added folder ~s: ~a <-> ~a~%"
|
||||
folder-name (collapse-home-path local-abs) remote)
|
||||
(when (ipc-send-command "reload")
|
||||
(format t "Reloaded running daemon.~%"))
|
||||
0)))
|
||||
|
||||
(defun %cmd-remove (args)
|
||||
(let ((name (first args)))
|
||||
(unless (and name (> (length name) 0))
|
||||
(format *error-output* "Usage: nextcloud-niri remove <name>~%")
|
||||
(return-from %cmd-remove 1))
|
||||
(let* ((cfg (load-config))
|
||||
(before (length (config-folders cfg)))
|
||||
(after (remove name (config-folders cfg) :key #'folder-name :test #'string=)))
|
||||
(if (= before (length after))
|
||||
(progn
|
||||
(format *error-output* "No folder named ~s found.~%" name)
|
||||
1)
|
||||
(progn
|
||||
(setf (config-folders cfg) after)
|
||||
(save-config cfg)
|
||||
(format t "Removed folder ~s.~%" name)
|
||||
(when (ipc-send-command "reload")
|
||||
(format t "Reloaded running daemon.~%"))
|
||||
0)))))
|
||||
|
||||
(defun %cmd-list ()
|
||||
(let ((cfg (load-config)))
|
||||
(if (null (config-folders cfg))
|
||||
(format t "No synced folders configured. Add one with:~% nextcloud-niri add ~/Documents/Notes Documents/Notes~%")
|
||||
(dolist (f (config-folders cfg))
|
||||
(format t "~a: ~a <-> ~a~%"
|
||||
(folder-name f)
|
||||
(collapse-home-path (folder-local f))
|
||||
(folder-remote f))))
|
||||
0))
|
||||
|
||||
(defun %cmd-sync (args)
|
||||
(let ((resp (ipc-send-command "sync" :args args)))
|
||||
(if resp
|
||||
(progn
|
||||
(format t "~a~%" (or (gethash "message" resp) "Sync triggered"))
|
||||
0)
|
||||
;; Daemon not running -> run direct one-shot sync!
|
||||
(let* ((cfg (load-config))
|
||||
(full (member "--full" args :test #'string=))
|
||||
(results (sync-all-folders cfg :force-full-scan full))
|
||||
(had-err nil))
|
||||
(dolist (res results)
|
||||
(format t "~a: ↑~d ↓~d -local:~d -remote:~d conflicts:~d errors:~d~%"
|
||||
(sync-result-folder-name res)
|
||||
(sync-result-uploaded res)
|
||||
(sync-result-downloaded res)
|
||||
(sync-result-deleted-local res)
|
||||
(sync-result-deleted-remote res)
|
||||
(length (sync-result-conflicts res))
|
||||
(length (sync-result-errors res)))
|
||||
(dolist (e (sync-result-errors res))
|
||||
(setf had-err t)
|
||||
(format *error-output* " ERROR: ~a~%" e)))
|
||||
(if had-err 1 0)))))
|
||||
|
||||
(defun %cmd-status ()
|
||||
(let* ((st (read-status))
|
||||
(pid (when st (gethash "pid" st)))
|
||||
(alive (pid-alive-p pid)))
|
||||
(cond
|
||||
((and st alive)
|
||||
(format t "State: ~a (pid ~d)~%" (gethash "state" st) pid)
|
||||
(format t "Server: ~a~%" (gethash "server_url" st))
|
||||
(format t "Last sync: ~a~%" (%format-age (gethash "last_sync" st)))
|
||||
(let ((err (gethash "error" st)))
|
||||
(when (and (stringp err) (> (length err) 0))
|
||||
(format t "Error: ~a~%" err)))
|
||||
(let ((folders (gethash "folders" st)))
|
||||
(when (and (vectorp folders) (> (length folders) 0))
|
||||
(format t "Folders:~%")
|
||||
(loop for f across folders
|
||||
do (format t " - ~a [~a]: ~a <-> ~a (~d files)~%"
|
||||
(gethash "name" f)
|
||||
(gethash "state" f)
|
||||
(gethash "local" f)
|
||||
(gethash "remote" f)
|
||||
(gethash "files" f))))))
|
||||
(t
|
||||
(format t "State: stopped (daemon not running)~%")))
|
||||
0))
|
||||
|
||||
(defun %cmd-ipc-simple (cmd)
|
||||
(let ((resp (ipc-send-command cmd)))
|
||||
(if resp
|
||||
(progn
|
||||
(format t "~a~%" (or (gethash "message" resp) "OK"))
|
||||
0)
|
||||
(progn
|
||||
(format *error-output* "Daemon is not running.~%")
|
||||
1))))
|
||||
|
||||
(defun main (&optional argv)
|
||||
"Top-level CLI entry point for nextcloud-niri."
|
||||
(let* ((args (or argv (uiop:command-line-arguments)))
|
||||
(cmd (or (first args) "help"))
|
||||
(rest-args (rest args)))
|
||||
(handler-case
|
||||
(let ((code
|
||||
(cond
|
||||
((string= cmd "waybar")
|
||||
(write-line (render-waybar-json))
|
||||
0)
|
||||
((string= cmd "daemon")
|
||||
(run-daemon (load-config))
|
||||
0)
|
||||
((string= cmd "sync")
|
||||
(%cmd-sync rest-args))
|
||||
((string= cmd "status")
|
||||
(%cmd-status))
|
||||
((member cmd '("pause" "resume" "toggle" "reload" "stop") :test #'string=)
|
||||
(%cmd-ipc-simple cmd))
|
||||
((string= cmd "login")
|
||||
(%cmd-login rest-args))
|
||||
((string= cmd "init")
|
||||
(%cmd-init)
|
||||
0)
|
||||
((string= cmd "add")
|
||||
(%cmd-add rest-args))
|
||||
((string= cmd "remove")
|
||||
(%cmd-remove rest-args))
|
||||
((string= cmd "list")
|
||||
(%cmd-list))
|
||||
((member cmd '("help" "-h" "--help") :test #'string=)
|
||||
(%print-help)
|
||||
0)
|
||||
(t
|
||||
(format *error-output* "Unknown command: ~a~%~%" cmd)
|
||||
(%print-help)
|
||||
1))))
|
||||
(uiop:quit code))
|
||||
(error (e)
|
||||
(format *error-output* "Error: ~a~%" e)
|
||||
(uiop:quit 1)))))
|
||||
+391
@@ -0,0 +1,391 @@
|
||||
(in-package #:nextcloud-niri)
|
||||
|
||||
(eval-when (:compile-toplevel :load-toplevel :execute)
|
||||
(require :sb-posix))
|
||||
|
||||
(defparameter *default-ignores*
|
||||
'(".git"
|
||||
".DS_Store"
|
||||
"Thumbs.db"
|
||||
"*.tmp"
|
||||
"*.part"
|
||||
"*.swp"
|
||||
"*.swo"
|
||||
"*~"
|
||||
".~lock.*"
|
||||
"#*#"
|
||||
".nextcloud-niri.tmp.*"))
|
||||
|
||||
(defvar *config-path-override* nil)
|
||||
(defvar *credentials-path-override* nil)
|
||||
(defvar *state-dir-override* nil)
|
||||
(defvar *runtime-dir-override* nil)
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; XDG Paths
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun %env-or (var fallback)
|
||||
(let ((val (uiop:getenv var)))
|
||||
(if (and val (> (length val) 0))
|
||||
val
|
||||
fallback)))
|
||||
|
||||
(defun %join-path (&rest parts)
|
||||
(let ((res ""))
|
||||
(dolist (p parts res)
|
||||
(let ((s (etypecase p
|
||||
(pathname (uiop:native-namestring p))
|
||||
(string p))))
|
||||
(cond
|
||||
((zerop (length res))
|
||||
(setf res (string-right-trim "/" s)))
|
||||
(t
|
||||
(setf res (concatenate 'string
|
||||
(string-right-trim "/" res)
|
||||
"/"
|
||||
(string-left-trim "/" s)))))))))
|
||||
|
||||
(defun expand-user-path (path-str)
|
||||
"Expand leading ~ and trailing slashes to a normalized absolute native path string."
|
||||
(let* ((trimmed (string-trim '(#\Space #\Tab #\Newline #\Return) path-str))
|
||||
(expanded
|
||||
(cond
|
||||
((string= trimmed "~")
|
||||
(string-right-trim "/" (uiop:native-namestring (user-homedir-pathname))))
|
||||
((and (>= (length trimmed) 2) (string= (subseq trimmed 0 2) "~/"))
|
||||
(%join-path (user-homedir-pathname) (subseq trimmed 2)))
|
||||
((and (> (length trimmed) 0) (char= (char trimmed 0) #\/))
|
||||
trimmed)
|
||||
(t
|
||||
(%join-path (uiop:getcwd) trimmed)))))
|
||||
(let ((clean (string-right-trim "/" expanded)))
|
||||
(if (zerop (length clean)) "/" clean))))
|
||||
|
||||
(defun collapse-home-path (path-str)
|
||||
"Replace $HOME prefix with ~ for clean config serialization."
|
||||
(let ((home (string-right-trim "/" (uiop:native-namestring (user-homedir-pathname)))))
|
||||
(cond
|
||||
((string= path-str home) "~")
|
||||
((and (> (length path-str) (length home))
|
||||
(string= path-str home :end1 (length home))
|
||||
(char= (char path-str (length home)) #\/))
|
||||
(concatenate 'string "~" (subseq path-str (length home))))
|
||||
(t path-str))))
|
||||
|
||||
(defun xdg-config-home ()
|
||||
(%env-or "XDG_CONFIG_HOME" (%join-path (user-homedir-pathname) ".config")))
|
||||
|
||||
(defun xdg-state-home ()
|
||||
(%env-or "XDG_STATE_HOME" (%join-path (user-homedir-pathname) ".local" "state")))
|
||||
|
||||
(defun xdg-runtime-dir ()
|
||||
(%env-or "XDG_RUNTIME_DIR" (format nil "/tmp/nextcloud-niri-~d" (sb-posix:getuid))))
|
||||
|
||||
(defun config-dir ()
|
||||
(%join-path (xdg-config-home) "nextcloud-niri"))
|
||||
|
||||
(defun config-path ()
|
||||
(or *config-path-override*
|
||||
(let ((env (uiop:getenv "NEXTCLOUD_NIRI_CONFIG")))
|
||||
(if (and env (> (length env) 0))
|
||||
(expand-user-path env)
|
||||
(%join-path (config-dir) "config.sexp")))))
|
||||
|
||||
(defun credentials-path ()
|
||||
(or *credentials-path-override*
|
||||
(let ((env (uiop:getenv "NEXTCLOUD_NIRI_CREDENTIALS")))
|
||||
(if (and env (> (length env) 0))
|
||||
(expand-user-path env)
|
||||
(%join-path (config-dir) "credentials.sexp")))))
|
||||
|
||||
(defun state-dir ()
|
||||
(or *state-dir-override*
|
||||
(let ((env (uiop:getenv "NEXTCLOUD_NIRI_STATE_DIR")))
|
||||
(if (and env (> (length env) 0))
|
||||
(expand-user-path env)
|
||||
(%join-path (xdg-state-home) "nextcloud-niri")))))
|
||||
|
||||
(defun runtime-dir ()
|
||||
(or *runtime-dir-override*
|
||||
(let ((env (uiop:getenv "NEXTCLOUD_NIRI_RUNTIME_DIR")))
|
||||
(if (and env (> (length env) 0))
|
||||
(expand-user-path env)
|
||||
(%join-path (xdg-runtime-dir) "nextcloud-niri")))))
|
||||
|
||||
(defun status-path ()
|
||||
(%join-path (runtime-dir) "status.json"))
|
||||
|
||||
(defun socket-path ()
|
||||
(%join-path (runtime-dir) "daemon.sock"))
|
||||
|
||||
(defun ensure-directory (dir-str)
|
||||
"Create DIR-STR and all parents if they do not exist."
|
||||
(ensure-directories-exist
|
||||
(uiop:parse-native-namestring
|
||||
(concatenate 'string (string-right-trim "/" dir-str) "/")))
|
||||
dir-str)
|
||||
|
||||
(defun sha256-hex-string (str)
|
||||
(ironclad:byte-array-to-hex-string
|
||||
(ironclad:digest-sequence :sha256 (babel:string-to-octets str :encoding :utf-8))))
|
||||
|
||||
(defun journal-path-for-folder (folder)
|
||||
(let* ((id (folder-id folder))
|
||||
(slug (subseq (sha256-hex-string id) 0 16)))
|
||||
(%join-path (state-dir) "journals" (format nil "~a.sexp" slug))))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Data Structures
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defstruct (server-config (:conc-name server-))
|
||||
(url "" :type string)
|
||||
(username "" :type string)
|
||||
(password "" :type string)
|
||||
(password-cmd nil)
|
||||
(verify-ssl t :type boolean))
|
||||
|
||||
(defstruct (sync-config (:conc-name sync-))
|
||||
(poll-interval 30 :type integer)
|
||||
(debounce-seconds 2.0 :type real)
|
||||
(chunk-size-mb 10 :type integer)
|
||||
(create-remote-if-missing t :type boolean)
|
||||
(notify-on-error t :type boolean)
|
||||
(ignore (copy-list *default-ignores*) :type list))
|
||||
|
||||
(defstruct (waybar-config (:conc-name waybar-))
|
||||
(signal 7 :type integer)
|
||||
(label "nc" :type string))
|
||||
|
||||
(defstruct (folder-config (:conc-name folder-))
|
||||
(name "" :type string)
|
||||
(local "" :type string)
|
||||
(remote "" :type string))
|
||||
|
||||
(defun folder-id (folder)
|
||||
(format nil "~a:~a" (folder-name folder) (string-trim "/" (folder-remote folder))))
|
||||
|
||||
(defstruct (app-config (:conc-name config-))
|
||||
(server (make-server-config))
|
||||
(sync (make-sync-config))
|
||||
(waybar (make-waybar-config))
|
||||
(folders nil :type list)
|
||||
(source-path nil))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Safe S-Expression I/O
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun read-sexp-file (path-str)
|
||||
"Safely read a single S-expression from PATH-STR with *read-eval* disabled."
|
||||
(let ((pn (uiop:parse-native-namestring path-str)))
|
||||
(when (probe-file pn)
|
||||
(with-open-file (in pn :direction :input :external-format :utf-8)
|
||||
(let ((*read-eval* nil))
|
||||
(read in nil nil))))))
|
||||
|
||||
(defun write-string-atomic (path-str content &key mode)
|
||||
"Atomically write CONTENT to PATH-STR using a sibling temp file + POSIX rename."
|
||||
(let* ((dir (subseq path-str 0 (or (position #\/ path-str :from-end t) 0)))
|
||||
(tmp (format nil "~a.tmp.~d.~d" path-str (sb-posix:getpid) (get-universal-time))))
|
||||
(when (> (length dir) 0)
|
||||
(ensure-directory dir))
|
||||
(unwind-protect
|
||||
(progn
|
||||
(with-open-file (out (uiop:parse-native-namestring tmp)
|
||||
:direction :output
|
||||
:if-exists :supersede
|
||||
:if-does-not-exist :create
|
||||
:external-format :utf-8)
|
||||
(write-string content out))
|
||||
(when mode
|
||||
(sb-posix:chmod tmp mode))
|
||||
(sb-posix:rename tmp path-str))
|
||||
(when (probe-file (uiop:parse-native-namestring tmp))
|
||||
(ignore-errors (sb-posix:unlink tmp))))
|
||||
path-str))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Credentials & Config Load/Save
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun load-credentials (&optional path-str)
|
||||
(let ((data (read-sexp-file (or path-str (credentials-path)))))
|
||||
(if (listp data) data nil)))
|
||||
|
||||
(defun save-credentials (&key url username password path)
|
||||
(let* ((target (or path (credentials-path)))
|
||||
(content
|
||||
(with-output-to-string (out)
|
||||
(format out ";; Auto-generated by nextcloud-niri login (chmod 600)~%")
|
||||
(let ((*print-pretty* t)
|
||||
(*print-case* :downcase))
|
||||
(prin1 (list :url (string-right-trim "/" url)
|
||||
:username username
|
||||
:password password)
|
||||
out)
|
||||
(terpri out)))))
|
||||
(write-string-atomic target content :mode #o600)))
|
||||
|
||||
(defun resolve-password (cfg)
|
||||
"Resolve Nextcloud app password from env, password-cmd, inline config, or credentials.sexp."
|
||||
(let ((env-pw (uiop:getenv "NEXTCLOUD_NIRI_PASSWORD"))
|
||||
(srv (config-server cfg)))
|
||||
(cond
|
||||
((and env-pw (> (length env-pw) 0))
|
||||
env-pw)
|
||||
((and (server-password-cmd srv) (> (length (server-password-cmd srv)) 0))
|
||||
(multiple-value-bind (out err code)
|
||||
(uiop:run-program (list "/bin/sh" "-c" (server-password-cmd srv))
|
||||
:output :string
|
||||
:error-output :string
|
||||
:ignore-error-status t)
|
||||
(unless (zerop code)
|
||||
(error "password-cmd failed (exit ~d): ~a" code (string-trim '(#\Newline #\Space) err)))
|
||||
(string-trim '(#\Newline #\Return #\Space) out)))
|
||||
((and (server-password srv) (> (length (server-password srv)) 0))
|
||||
(server-password srv))
|
||||
(t
|
||||
(let ((pw (getf (load-credentials) :password)))
|
||||
(if (and (stringp pw) (> (length pw) 0))
|
||||
pw
|
||||
(error "No Nextcloud password configured. Run `nextcloud-niri login <url>` or set :password-cmd in config.sexp.")))))))
|
||||
|
||||
(defun load-config (&optional path-str)
|
||||
"Load configuration from PATH-STR (or default config path), merging defaults and credentials."
|
||||
(let* ((p (or path-str (config-path)))
|
||||
(data (or (read-sexp-file p) '()))
|
||||
(creds (load-credentials))
|
||||
(srv-pl (getf data :server))
|
||||
(sync-pl (getf data :sync))
|
||||
(wb-pl (getf data :waybar))
|
||||
(folders-raw (getf data :folders))
|
||||
(raw-ignores (getf sync-pl :ignore :missing))
|
||||
(ignores (if (eq raw-ignores :missing)
|
||||
(copy-list *default-ignores*)
|
||||
(let ((lst (mapcar #'princ-to-string raw-ignores)))
|
||||
(if (member ".nextcloud-niri.tmp.*" lst :test #'string=)
|
||||
lst
|
||||
(append lst (list ".nextcloud-niri.tmp.*"))))))
|
||||
(server (make-server-config
|
||||
:url (string-right-trim "/" (or (getf srv-pl :url) (getf creds :url) ""))
|
||||
:username (or (getf srv-pl :username) (getf creds :username) "")
|
||||
:password (or (getf srv-pl :password) "")
|
||||
:password-cmd (getf srv-pl :password-cmd)
|
||||
:verify-ssl (if (member :verify-ssl srv-pl)
|
||||
(not (null (getf srv-pl :verify-ssl)))
|
||||
t)))
|
||||
(sync (make-sync-config
|
||||
:poll-interval (max 5 (or (getf sync-pl :poll-interval) 30))
|
||||
:debounce-seconds (max 0.2 (float (or (getf sync-pl :debounce-seconds) 2.0)))
|
||||
:chunk-size-mb (max 1 (or (getf sync-pl :chunk-size-mb) 10))
|
||||
:create-remote-if-missing (if (member :create-remote-if-missing sync-pl)
|
||||
(not (null (getf sync-pl :create-remote-if-missing)))
|
||||
t)
|
||||
:notify-on-error (if (member :notify-on-error sync-pl)
|
||||
(not (null (getf sync-pl :notify-on-error)))
|
||||
t)
|
||||
:ignore ignores))
|
||||
(waybar (make-waybar-config
|
||||
:signal (or (getf wb-pl :signal) 7)
|
||||
:label (or (getf wb-pl :label) "nc")))
|
||||
(folders '())
|
||||
(seen (make-hash-table :test #'equal)))
|
||||
(loop for f in folders-raw
|
||||
for idx from 1
|
||||
do (let* ((local-raw (or (getf f :local) ""))
|
||||
(remote-raw (string-trim "/" (or (getf f :remote) ""))))
|
||||
(when (zerop (length local-raw))
|
||||
(error "Folder entry #~d is missing :local" idx))
|
||||
(let* ((local-abs (expand-user-path local-raw))
|
||||
(slash (position #\/ local-abs :from-end t))
|
||||
(fallback-name (if slash (subseq local-abs (1+ slash)) local-abs))
|
||||
(name (or (getf f :name)
|
||||
(if (> (length fallback-name) 0) fallback-name (format nil "folder-~d" idx)))))
|
||||
(when (gethash name seen)
|
||||
(error "Duplicate folder name in config: ~a" name))
|
||||
(setf (gethash name seen) t)
|
||||
(push (make-folder-config :name name :local local-abs :remote remote-raw)
|
||||
folders))))
|
||||
(make-app-config :server server
|
||||
:sync sync
|
||||
:waybar waybar
|
||||
:folders (nreverse folders)
|
||||
:source-path p)))
|
||||
|
||||
(defun save-config (cfg &optional path-str)
|
||||
"Write CFG cleanly as formatted S-expression to PATH-STR."
|
||||
(let* ((target (or path-str (config-source-path cfg) (config-path)))
|
||||
(srv (config-server cfg))
|
||||
(sync (config-sync cfg))
|
||||
(wb (config-waybar cfg))
|
||||
(user-ignores (remove ".nextcloud-niri.tmp.*" (sync-ignore sync) :test #'string=))
|
||||
(content
|
||||
(with-output-to-string (out)
|
||||
(format out ";; nextcloud-niri configuration~%~%")
|
||||
(format out "(:server~%")
|
||||
(format out " (:url ~s~%" (string-right-trim "/" (server-url srv)))
|
||||
(format out " :username ~s~%" (server-username srv))
|
||||
(when (server-password-cmd srv)
|
||||
(format out " :password-cmd ~s~%" (server-password-cmd srv)))
|
||||
(unless (server-verify-ssl srv)
|
||||
(format out " :verify-ssl nil~%"))
|
||||
(format out " )~%~%")
|
||||
(format out " :sync~%")
|
||||
(format out " (:poll-interval ~d~%" (sync-poll-interval sync))
|
||||
(format out " :debounce-seconds ~,1f~%" (sync-debounce-seconds sync))
|
||||
(format out " :chunk-size-mb ~d~%" (sync-chunk-size-mb sync))
|
||||
(format out " :create-remote-if-missing ~a~%" (if (sync-create-remote-if-missing sync) "t" "nil"))
|
||||
(format out " :notify-on-error ~a~%" (if (sync-notify-on-error sync) "t" "nil"))
|
||||
(format out " :ignore (~{~s~^~% ~}))~%~%" user-ignores)
|
||||
(format out " :waybar~%")
|
||||
(format out " (:signal ~d~%" (waybar-signal wb))
|
||||
(format out " :label ~s)~%~%" (waybar-label wb))
|
||||
(format out " :folders~%")
|
||||
(if (null (config-folders cfg))
|
||||
(format out " ())~%")
|
||||
(progn
|
||||
(format out " (")
|
||||
(loop for f in (config-folders cfg)
|
||||
for first = t then nil
|
||||
do (unless first (format out "~% "))
|
||||
(format out "(:name ~s~% :local ~s~% :remote ~s)"
|
||||
(folder-name f)
|
||||
(collapse-home-path (folder-local f))
|
||||
(string-trim "/" (folder-remote f))))
|
||||
(format out "))~%"))))))
|
||||
(write-string-atomic target content)))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Ignore Pattern Matching (glob -> regex)
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun %glob-to-regex (pattern)
|
||||
(with-output-to-string (out)
|
||||
(write-string "^" out)
|
||||
(loop for ch across pattern
|
||||
do (case ch
|
||||
(#\* (write-string "[^/]*" out))
|
||||
(#\? (write-string "[^/]" out))
|
||||
((#\. #\+ #\( #\) #\[ #\] #\{ #\} #\^ #\$ #\| #\\)
|
||||
(write-char #\\ out)
|
||||
(write-char ch out))
|
||||
(t (write-char ch out))))
|
||||
(write-string "$" out)))
|
||||
|
||||
(defun %split-rel-path (rel-path)
|
||||
(remove-if (lambda (s) (zerop (length s)))
|
||||
(uiop:split-string rel-path :separator "/")))
|
||||
|
||||
(defun path-ignored-p (rel-path patterns)
|
||||
"Return T if REL-PATH or any of its path segments matches any glob in PATTERNS."
|
||||
(let ((segments (%split-rel-path rel-path)))
|
||||
(dolist (pat patterns nil)
|
||||
(let ((rx (%glob-to-regex pat)))
|
||||
(if (position #\/ pat)
|
||||
(when (cl-ppcre:scan rx rel-path)
|
||||
(return t))
|
||||
(dolist (seg segments)
|
||||
(when (cl-ppcre:scan rx seg)
|
||||
(return-from path-ignored-p t))))))))
|
||||
+431
@@ -0,0 +1,431 @@
|
||||
(in-package #:nextcloud-niri)
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Background Sync Daemon (inotify + debounce + ETag polling + IPC + backoff)
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defstruct (daemon-instance (:constructor %make-daemon))
|
||||
(config nil)
|
||||
(lock (bt:make-lock "nextcloud-niri-daemon"))
|
||||
(sync-lock (bt:make-lock "nextcloud-niri-sync"))
|
||||
(running nil :type boolean)
|
||||
(paused nil :type boolean)
|
||||
(state :starting)
|
||||
(last-sync 0 :type integer)
|
||||
(last-poll 0 :type integer)
|
||||
(pending-count 0 :type integer)
|
||||
(debounce-deadline nil)
|
||||
(sync-requested nil :type boolean)
|
||||
(force-full-next nil :type boolean)
|
||||
(reload-requested nil :type boolean)
|
||||
(backoff-seconds 0 :type integer)
|
||||
(next-retry-time 0 :type integer)
|
||||
(last-error "" :type string)
|
||||
(last-notified-error "" :type string)
|
||||
(folder-statuses nil :type list)
|
||||
(self-writes (make-hash-table :test #'equal))
|
||||
(watcher nil)
|
||||
(ipc-socket nil)
|
||||
(threads nil :type list))
|
||||
|
||||
(defun make-daemon (cfg)
|
||||
(%make-daemon
|
||||
:config cfg
|
||||
:folder-statuses
|
||||
(loop for f in (config-folders cfg)
|
||||
collect (list :name (folder-name f)
|
||||
:local (collapse-home-path (folder-local f))
|
||||
:remote (folder-remote f)
|
||||
:state :unsynced
|
||||
:files 0
|
||||
:error ""
|
||||
:conflicts nil))))
|
||||
|
||||
(defun %daemon-log (fmt &rest args)
|
||||
(multiple-value-bind (sec min hr) (get-decoded-time)
|
||||
(format *error-output* "~&[~2,'0d:~2,'0d:~2,'0d] ~?~%" hr min sec fmt args)
|
||||
(finish-output *error-output*)))
|
||||
|
||||
(defun %daemon-record-self-write (daemon abs-path)
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(setf (gethash abs-path (daemon-instance-self-writes daemon))
|
||||
(+ (get-internal-real-time) (* 3 internal-time-units-per-second)))))
|
||||
|
||||
(defun %daemon-self-write-p (daemon abs-path)
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(let* ((now (get-internal-real-time))
|
||||
(exp (gethash abs-path (daemon-instance-self-writes daemon))))
|
||||
;; Prune expired entries occasionally
|
||||
(when (> (hash-table-count (daemon-instance-self-writes daemon)) 64)
|
||||
(let ((stale '()))
|
||||
(maphash (lambda (k v) (when (< v now) (push k stale)))
|
||||
(daemon-instance-self-writes daemon))
|
||||
(dolist (k stale) (remhash k (daemon-instance-self-writes daemon)))))
|
||||
(and exp (>= exp now)))))
|
||||
|
||||
(defun %daemon-publish-status (daemon &key (progress-done 0) (progress-total 0) (progress-detail ""))
|
||||
(let (st srv-url last-sync pending err folders sig)
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(setf st (daemon-instance-state daemon)
|
||||
srv-url (server-url (config-server (daemon-instance-config daemon)))
|
||||
last-sync (daemon-instance-last-sync daemon)
|
||||
pending (daemon-instance-pending-count daemon)
|
||||
err (daemon-instance-last-error daemon)
|
||||
folders (copy-tree (daemon-instance-folder-statuses daemon))
|
||||
sig (waybar-signal (config-waybar (daemon-instance-config daemon)))))
|
||||
(write-status :state st
|
||||
:server-url srv-url
|
||||
:last-sync last-sync
|
||||
:pending pending
|
||||
:progress-done progress-done
|
||||
:progress-total progress-total
|
||||
:progress-detail progress-detail
|
||||
:error-msg err
|
||||
:folders folders
|
||||
:signal-num sig)))
|
||||
|
||||
(defun %daemon-setup-watcher (daemon)
|
||||
(let ((old (daemon-instance-watcher daemon)))
|
||||
(when old (watcher-close old)))
|
||||
(let* ((cfg (daemon-instance-config daemon))
|
||||
(w (make-inotify-watcher :ignores (sync-ignore (config-sync cfg)))))
|
||||
(dolist (f (config-folders cfg))
|
||||
(let ((loc (folder-local f)))
|
||||
(when (%safe-lstat loc)
|
||||
(watcher-add-tree w loc :register-root t))))
|
||||
(setf (daemon-instance-watcher daemon) w)
|
||||
w))
|
||||
|
||||
(defun %daemon-mark-local-dirty (daemon)
|
||||
(let ((debounce-ms (round (* 1000 (sync-debounce-seconds (config-sync (daemon-instance-config daemon))))))
|
||||
(changed-state nil))
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(setf (daemon-instance-debounce-deadline daemon)
|
||||
(+ (get-internal-real-time)
|
||||
(round (* debounce-ms internal-time-units-per-second) 1000)))
|
||||
(incf (daemon-instance-pending-count daemon))
|
||||
(unless (or (daemon-instance-paused daemon)
|
||||
(eq (daemon-instance-state daemon) :syncing))
|
||||
(unless (eq (daemon-instance-state daemon) :unsynced)
|
||||
(setf (daemon-instance-state daemon) :unsynced
|
||||
changed-state t))))
|
||||
(when changed-state
|
||||
(%daemon-publish-status daemon))))
|
||||
|
||||
(defun %daemon-watcher-loop (daemon)
|
||||
(loop while (daemon-instance-running daemon)
|
||||
do (let ((w (daemon-instance-watcher daemon)))
|
||||
(if w
|
||||
(handler-case
|
||||
(let ((events (watcher-poll-events w :timeout-ms 250)))
|
||||
(when events
|
||||
(let ((has-real-event nil))
|
||||
(dolist (ev events)
|
||||
(unless (%daemon-self-write-p daemon (ievent-path ev))
|
||||
(setf has-real-event t)))
|
||||
(when has-real-event
|
||||
(%daemon-mark-local-dirty daemon)))))
|
||||
(error (e)
|
||||
(%daemon-log "Watcher error: ~a" e)
|
||||
(sleep 1)))
|
||||
(sleep 0.25)))))
|
||||
|
||||
(defun %daemon-handle-ipc (daemon cmd args)
|
||||
(let ((resp (make-hash-table :test #'equal)))
|
||||
(setf (gethash "ok" resp) t)
|
||||
(cond
|
||||
((string= cmd "sync")
|
||||
(let ((full (member "--full" args :test #'string=)))
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(setf (daemon-instance-sync-requested daemon) t
|
||||
(daemon-instance-next-retry-time daemon) 0
|
||||
(daemon-instance-backoff-seconds daemon) 0)
|
||||
(when full (setf (daemon-instance-force-full-next daemon) t)))
|
||||
(setf (gethash "message" resp) "Sync triggered")))
|
||||
((string= cmd "pause")
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(setf (daemon-instance-paused daemon) t
|
||||
(daemon-instance-state daemon) :paused))
|
||||
(%daemon-publish-status daemon)
|
||||
(setf (gethash "message" resp) "Paused"))
|
||||
((string= cmd "resume")
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(setf (daemon-instance-paused daemon) nil
|
||||
(daemon-instance-sync-requested daemon) t
|
||||
(daemon-instance-state daemon) :unsynced))
|
||||
(%daemon-publish-status daemon)
|
||||
(setf (gethash "message" resp) "Resumed"))
|
||||
((string= cmd "toggle")
|
||||
(let ((now-paused nil))
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(setf now-paused (not (daemon-instance-paused daemon))
|
||||
(daemon-instance-paused daemon) now-paused
|
||||
(daemon-instance-state daemon) (if now-paused :paused :unsynced))
|
||||
(unless now-paused
|
||||
(setf (daemon-instance-sync-requested daemon) t)))
|
||||
(%daemon-publish-status daemon)
|
||||
(setf (gethash "paused" resp) now-paused
|
||||
(gethash "message" resp) (if now-paused "Paused" "Resumed"))))
|
||||
((string= cmd "reload")
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(setf (daemon-instance-reload-requested daemon) t))
|
||||
(setf (gethash "message" resp) "Reload scheduled"))
|
||||
((string= cmd "status")
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(setf (gethash "state" resp) (string-downcase (string (daemon-instance-state daemon)))
|
||||
(gethash "paused" resp) (daemon-instance-paused daemon)
|
||||
(gethash "last_sync" resp) (daemon-instance-last-sync daemon)
|
||||
(gethash "error" resp) (daemon-instance-last-error daemon))))
|
||||
((string= cmd "stop")
|
||||
(setf (daemon-instance-running daemon) nil
|
||||
(gethash "message" resp) "Stopping"))
|
||||
(t
|
||||
(setf (gethash "ok" resp) nil
|
||||
(gethash "error" resp) (format nil "Unknown command: ~a" cmd))))
|
||||
resp))
|
||||
|
||||
(defun %daemon-ipc-loop (daemon)
|
||||
(loop while (daemon-instance-running daemon)
|
||||
do (let ((sock (daemon-instance-ipc-socket daemon)))
|
||||
(if sock
|
||||
(ipc-server-accept-once
|
||||
sock
|
||||
(lambda (cmd args) (%daemon-handle-ipc daemon cmd args))
|
||||
:timeout-ms 250)
|
||||
(sleep 0.25)))))
|
||||
|
||||
(defun %daemon-run-sync (daemon &key force-full)
|
||||
(bt:with-lock-held ((daemon-instance-sync-lock daemon))
|
||||
(let* ((cfg (daemon-instance-config daemon))
|
||||
(srv (config-server cfg))
|
||||
(folders (config-folders cfg)))
|
||||
(when (or (zerop (length (server-url srv)))
|
||||
(zerop (length (server-username srv))))
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(setf (daemon-instance-state daemon) :error
|
||||
(daemon-instance-last-error daemon) "Server URL or username not configured"))
|
||||
(%daemon-publish-status daemon)
|
||||
(return-from %daemon-run-sync))
|
||||
|
||||
(when (null folders)
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(setf (daemon-instance-state daemon) :synced
|
||||
(daemon-instance-last-error daemon) ""
|
||||
(daemon-instance-last-sync daemon) (unix-now)
|
||||
(daemon-instance-pending-count daemon) 0
|
||||
(daemon-instance-folder-statuses daemon) nil))
|
||||
(%daemon-publish-status daemon)
|
||||
(return-from %daemon-run-sync))
|
||||
|
||||
;; Mark syncing
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(setf (daemon-instance-state daemon) :syncing
|
||||
(daemon-instance-debounce-deadline daemon) nil
|
||||
(daemon-instance-sync-requested daemon) nil))
|
||||
(%daemon-publish-status daemon)
|
||||
|
||||
(let ((all-errors '())
|
||||
(all-conflicts '())
|
||||
(folder-summaries '()))
|
||||
(handler-case
|
||||
(let* ((results (sync-all-folders
|
||||
cfg
|
||||
:force-full-scan force-full
|
||||
:on-local-write (lambda (p) (%daemon-record-self-write daemon p))
|
||||
:on-progress (lambda (done total detail)
|
||||
(%daemon-publish-status daemon
|
||||
:progress-done done
|
||||
:progress-total total
|
||||
:progress-detail detail)))))
|
||||
(dolist (res results)
|
||||
(let ((errs (sync-result-errors res))
|
||||
(confs (sync-result-conflicts res)))
|
||||
(dolist (e errs)
|
||||
(push (format nil "~a: ~a" (sync-result-folder-name res) e) all-errors))
|
||||
(dolist (c confs)
|
||||
(push (format nil "~a/~a" (sync-result-folder-name res) c) all-conflicts))
|
||||
(push (list :name (sync-result-folder-name res)
|
||||
:local (collapse-home-path (sync-result-local-path res))
|
||||
:remote (sync-result-remote-path res)
|
||||
:state (if errs :error :synced)
|
||||
:files (sync-result-file-count res)
|
||||
:error (if errs (first errs) "")
|
||||
:conflicts confs)
|
||||
folder-summaries)
|
||||
(unless (sync-result-skipped-p res)
|
||||
(%daemon-log "Synced ~a: ↑~d ↓~d -L:~d -R:~d conflicts:~d errors:~d"
|
||||
(sync-result-folder-name res)
|
||||
(sync-result-uploaded res)
|
||||
(sync-result-downloaded res)
|
||||
(sync-result-deleted-local res)
|
||||
(sync-result-deleted-remote res)
|
||||
(length confs)
|
||||
(length errs))))))
|
||||
(error (e)
|
||||
(push (format nil "~a" e) all-errors)))
|
||||
|
||||
(setf all-errors (nreverse all-errors)
|
||||
all-conflicts (nreverse all-conflicts)
|
||||
folder-summaries (nreverse folder-summaries))
|
||||
|
||||
(let ((should-notify nil)
|
||||
(notify-msg ""))
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(setf (daemon-instance-last-poll daemon) (unix-now))
|
||||
(when folder-summaries
|
||||
(setf (daemon-instance-folder-statuses daemon) folder-summaries))
|
||||
(cond
|
||||
((daemon-instance-paused daemon)
|
||||
(setf (daemon-instance-state daemon) :paused))
|
||||
(all-errors
|
||||
(let* ((err-summary (first all-errors))
|
||||
(next-backoff (min 120 (max 15 (* 2 (max 7 (daemon-instance-backoff-seconds daemon)))))))
|
||||
(setf (daemon-instance-state daemon) :error
|
||||
(daemon-instance-last-error daemon) err-summary
|
||||
(daemon-instance-backoff-seconds daemon) next-backoff
|
||||
(daemon-instance-next-retry-time daemon) (+ (unix-now) next-backoff))
|
||||
(when (and (sync-notify-on-error (config-sync cfg))
|
||||
(not (string= err-summary (daemon-instance-last-notified-error daemon))))
|
||||
(setf (daemon-instance-last-notified-error daemon) err-summary
|
||||
should-notify t
|
||||
notify-msg err-summary))))
|
||||
(t
|
||||
(setf (daemon-instance-last-sync daemon) (unix-now)
|
||||
(daemon-instance-last-error daemon) ""
|
||||
(daemon-instance-last-notified-error daemon) ""
|
||||
(daemon-instance-backoff-seconds daemon) 0
|
||||
(daemon-instance-next-retry-time daemon) 0)
|
||||
;; If new local edits arrived while syncing, stay unsynced for another pass
|
||||
(if (or (daemon-instance-debounce-deadline daemon)
|
||||
(daemon-instance-sync-requested daemon))
|
||||
(setf (daemon-instance-state daemon) :unsynced)
|
||||
(setf (daemon-instance-state daemon) :synced
|
||||
(daemon-instance-pending-count daemon) 0)))))
|
||||
(%daemon-publish-status daemon)
|
||||
(when should-notify
|
||||
(notify-desktop "Nextcloud sync error" notify-msg :urgency "critical"))
|
||||
(when (and all-conflicts (sync-notify-on-error (config-sync cfg)))
|
||||
(notify-desktop "Nextcloud sync conflict"
|
||||
(format nil "Created conflicted copy for: ~{~a~^, ~}" all-conflicts)
|
||||
:urgency "normal")))))))
|
||||
|
||||
(defun %daemon-maybe-reload (daemon)
|
||||
(let ((do-reload nil))
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(when (daemon-instance-reload-requested daemon)
|
||||
(setf (daemon-instance-reload-requested daemon) nil
|
||||
do-reload t)))
|
||||
(when do-reload
|
||||
(handler-case
|
||||
(let ((new-cfg (load-config (config-source-path (daemon-instance-config daemon)))))
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(setf (daemon-instance-config daemon) new-cfg
|
||||
(daemon-instance-sync-requested daemon) t))
|
||||
(%daemon-setup-watcher daemon)
|
||||
(%daemon-log "Reloaded configuration (~d folders)" (length (config-folders new-cfg))))
|
||||
(error (e)
|
||||
(%daemon-log "Config reload failed: ~a" e))))))
|
||||
|
||||
(defun %daemon-scheduler-step (daemon)
|
||||
(%daemon-maybe-reload daemon)
|
||||
(let ((should-sync nil)
|
||||
(force-full nil)
|
||||
(now-unix (unix-now))
|
||||
(now-rt (get-internal-real-time)))
|
||||
(bt:with-lock-held ((daemon-instance-lock daemon))
|
||||
(unless (daemon-instance-paused daemon)
|
||||
(let ((poll-sec (sync-poll-interval (config-sync (daemon-instance-config daemon))))
|
||||
(deadline (daemon-instance-debounce-deadline daemon))
|
||||
(retry-at (daemon-instance-next-retry-time daemon)))
|
||||
(cond
|
||||
((daemon-instance-sync-requested daemon)
|
||||
(setf should-sync t
|
||||
force-full (daemon-instance-force-full-next daemon)
|
||||
(daemon-instance-force-full-next daemon) nil))
|
||||
((and deadline (>= now-rt deadline))
|
||||
(setf should-sync t))
|
||||
((and (> retry-at 0) (>= now-unix retry-at))
|
||||
(setf should-sync t))
|
||||
((and (zerop retry-at)
|
||||
(>= (- now-unix (daemon-instance-last-poll daemon)) poll-sec))
|
||||
(setf should-sync t))))))
|
||||
(when should-sync
|
||||
(%daemon-run-sync daemon :force-full force-full))))
|
||||
|
||||
(defun daemon-start (daemon &key (initial-sync t))
|
||||
"Start the daemon background threads (inotify watcher + IPC server + scheduler)."
|
||||
(setf (daemon-instance-running daemon) t
|
||||
(daemon-instance-state daemon) :unsynced
|
||||
(daemon-instance-sync-requested daemon) initial-sync)
|
||||
(ensure-directory (runtime-dir))
|
||||
(%daemon-setup-watcher daemon)
|
||||
(setf (daemon-instance-ipc-socket daemon) (make-ipc-server-socket))
|
||||
(%daemon-publish-status daemon)
|
||||
(let* ((cfg-ov *config-path-override*)
|
||||
(cred-ov *credentials-path-override*)
|
||||
(state-ov *state-dir-override*)
|
||||
(rt-ov *runtime-dir-override*)
|
||||
(bindings `((*config-path-override* . ,cfg-ov)
|
||||
(*credentials-path-override* . ,cred-ov)
|
||||
(*state-dir-override* . ,state-ov)
|
||||
(*runtime-dir-override* . ,rt-ov)))
|
||||
(t-watch (bt:make-thread (lambda () (%daemon-watcher-loop daemon))
|
||||
:name "nextcloud-niri-inotify"
|
||||
:initial-bindings bindings))
|
||||
(t-ipc (bt:make-thread (lambda () (%daemon-ipc-loop daemon))
|
||||
:name "nextcloud-niri-ipc"
|
||||
:initial-bindings bindings))
|
||||
(t-sched (bt:make-thread (lambda ()
|
||||
(loop while (daemon-instance-running daemon)
|
||||
do (%daemon-scheduler-step daemon)
|
||||
(sleep 0.25)))
|
||||
:name "nextcloud-niri-scheduler"
|
||||
:initial-bindings bindings)))
|
||||
(setf (daemon-instance-threads daemon) (list t-watch t-ipc t-sched)))
|
||||
daemon)
|
||||
|
||||
(defun daemon-stop (daemon)
|
||||
"Gracefully stop the daemon and clean up socket/status."
|
||||
(setf (daemon-instance-running daemon) nil)
|
||||
(dolist (th (daemon-instance-threads daemon))
|
||||
(ignore-errors (bt:join-thread th)))
|
||||
(setf (daemon-instance-threads daemon) nil)
|
||||
(when (daemon-instance-watcher daemon)
|
||||
(watcher-close (daemon-instance-watcher daemon))
|
||||
(setf (daemon-instance-watcher daemon) nil))
|
||||
(when (daemon-instance-ipc-socket daemon)
|
||||
(ignore-errors (sb-bsd-sockets:socket-close (daemon-instance-ipc-socket daemon)))
|
||||
(setf (daemon-instance-ipc-socket daemon) nil))
|
||||
(ignore-errors (sb-posix:unlink (socket-path)))
|
||||
(let ((sig (waybar-signal (config-waybar (daemon-instance-config daemon)))))
|
||||
(write-status :state :off
|
||||
:pid 0
|
||||
:server-url (server-url (config-server (daemon-instance-config daemon)))
|
||||
:signal-num sig)))
|
||||
|
||||
(defun run-daemon (cfg)
|
||||
"Run the Nextcloud sync daemon in the foreground until SIGINT/SIGTERM or IPC stop."
|
||||
(let ((daemon (make-daemon cfg)))
|
||||
;; Handle SIGTERM / SIGINT / SIGHUP cleanly
|
||||
(sb-sys:enable-interrupt sb-unix:sigterm
|
||||
(lambda (sig info ctx)
|
||||
(declare (ignore sig info ctx))
|
||||
(setf (daemon-instance-running daemon) nil)))
|
||||
(sb-sys:enable-interrupt sb-unix:sigint
|
||||
(lambda (sig info ctx)
|
||||
(declare (ignore sig info ctx))
|
||||
(setf (daemon-instance-running daemon) nil)))
|
||||
(sb-sys:enable-interrupt sb-unix:sighup
|
||||
(lambda (sig info ctx)
|
||||
(declare (ignore sig info ctx))
|
||||
(setf (daemon-instance-reload-requested daemon) t)))
|
||||
(%daemon-log "Starting nextcloud-niri daemon (~d folder~:p, poll ~ds, signal ~d)"
|
||||
(length (config-folders cfg))
|
||||
(sync-poll-interval (config-sync cfg))
|
||||
(waybar-signal (config-waybar cfg)))
|
||||
(daemon-start daemon :initial-sync t)
|
||||
(unwind-protect
|
||||
(loop while (daemon-instance-running daemon)
|
||||
do (sleep 0.25))
|
||||
(%daemon-log "Shutting down nextcloud-niri daemon")
|
||||
(daemon-stop daemon))))
|
||||
@@ -0,0 +1,198 @@
|
||||
(in-package #:nextcloud-niri)
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Pure SBCL sb-alien Linux inotify recursive directory watcher (no gcc/grovel)
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defconstant +in-modify+ #x00000002)
|
||||
(defconstant +in-close-write+ #x00000008)
|
||||
(defconstant +in-moved-from+ #x00000040)
|
||||
(defconstant +in-moved-to+ #x00000080)
|
||||
(defconstant +in-create+ #x00000100)
|
||||
(defconstant +in-delete+ #x00000200)
|
||||
(defconstant +in-delete-self+ #x00000400)
|
||||
(defconstant +in-move-self+ #x00000800)
|
||||
(defconstant +in-q-overflow+ #x00004000)
|
||||
(defconstant +in-ignored+ #x00008000)
|
||||
(defconstant +in-isdir+ #x40000000)
|
||||
|
||||
(defconstant +in-nonblock+ #x00000800)
|
||||
(defconstant +in-cloexec+ #x00080000)
|
||||
|
||||
(defconstant +pollin+ #x0001)
|
||||
|
||||
(defconstant +watch-mask+
|
||||
(logior +in-close-write+ +in-moved-from+ +in-moved-to+
|
||||
+in-create+ +in-delete+ +in-delete-self+ +in-move-self+))
|
||||
|
||||
(sb-alien:define-alien-type nil
|
||||
(sb-alien:struct pollfd
|
||||
(fd sb-alien:int)
|
||||
(events sb-alien:short)
|
||||
(revents sb-alien:short)))
|
||||
|
||||
(sb-alien:define-alien-routine ("inotify_init1" %inotify-init1) sb-alien:int
|
||||
(flags sb-alien:int))
|
||||
|
||||
(sb-alien:define-alien-routine ("inotify_add_watch" %inotify-add-watch) sb-alien:int
|
||||
(fd sb-alien:int)
|
||||
(pathname sb-alien:c-string)
|
||||
(mask sb-alien:unsigned-int))
|
||||
|
||||
(sb-alien:define-alien-routine ("inotify_rm_watch" %inotify-rm-watch) sb-alien:int
|
||||
(fd sb-alien:int)
|
||||
(wd sb-alien:int))
|
||||
|
||||
(sb-alien:define-alien-routine ("poll" %c-poll) sb-alien:int
|
||||
(fds (* (sb-alien:struct pollfd)))
|
||||
(nfds sb-alien:unsigned-long)
|
||||
(timeout sb-alien:int))
|
||||
|
||||
(sb-alien:define-alien-routine ("read" %c-read) sb-alien:long
|
||||
(fd sb-alien:int)
|
||||
(buf sb-alien:system-area-pointer)
|
||||
(count sb-alien:unsigned-long))
|
||||
|
||||
(defun poll-fd-readable-p (fd timeout-ms)
|
||||
"Wait up to TIMEOUT-MS milliseconds for FD to become readable."
|
||||
(sb-alien:with-alien ((pfd (sb-alien:struct pollfd)))
|
||||
(setf (sb-alien:slot pfd 'fd) fd
|
||||
(sb-alien:slot pfd 'events) +pollin+
|
||||
(sb-alien:slot pfd 'revents) 0)
|
||||
(let ((rc (%c-poll (sb-alien:addr pfd) 1 timeout-ms)))
|
||||
(and (> rc 0)
|
||||
(not (zerop (logand (sb-alien:slot pfd 'revents) +pollin+)))))))
|
||||
|
||||
(defstruct (inotify-event (:conc-name ievent-))
|
||||
(wd 0 :type integer)
|
||||
(mask 0 :type integer)
|
||||
(path "" :type string)
|
||||
(name "" :type string))
|
||||
|
||||
(defstruct (inotify-watcher (:constructor %make-inotify-watcher))
|
||||
(fd -1 :type integer)
|
||||
(wd-to-dir (make-hash-table :test #'eql) :type hash-table)
|
||||
(dir-to-wd (make-hash-table :test #'equal) :type hash-table)
|
||||
(ignores nil :type list)
|
||||
(root-dirs nil :type list)
|
||||
(buf (make-array 16384 :element-type '(unsigned-byte 8))))
|
||||
|
||||
(defun make-inotify-watcher (&key ignores)
|
||||
(let ((fd (%inotify-init1 (logior +in-nonblock+ +in-cloexec+))))
|
||||
(when (< fd 0)
|
||||
(error "inotify_init1 failed"))
|
||||
(%make-inotify-watcher :fd fd :ignores ignores)))
|
||||
|
||||
(defun watcher-close (watcher)
|
||||
(when (and watcher (>= (inotify-watcher-fd watcher) 0))
|
||||
(ignore-errors (sb-posix:close (inotify-watcher-fd watcher)))
|
||||
(setf (inotify-watcher-fd watcher) -1)
|
||||
(clrhash (inotify-watcher-wd-to-dir watcher))
|
||||
(clrhash (inotify-watcher-dir-to-wd watcher))))
|
||||
|
||||
(defun %relative-to-roots (watcher abs-path)
|
||||
(dolist (root (inotify-watcher-root-dirs watcher) abs-path)
|
||||
(let ((r (string-right-trim "/" root)))
|
||||
(cond
|
||||
((string= abs-path r) (return ""))
|
||||
((and (> (length abs-path) (length r))
|
||||
(string= abs-path r :end1 (length r))
|
||||
(char= (char abs-path (length r)) #\/))
|
||||
(return (subseq abs-path (1+ (length r)))))))))
|
||||
|
||||
(defun %watcher-add-dir (watcher dir-str)
|
||||
(let ((clean (string-right-trim "/" dir-str)))
|
||||
(unless (gethash clean (inotify-watcher-dir-to-wd watcher))
|
||||
(let ((wd (%inotify-add-watch (inotify-watcher-fd watcher) clean +watch-mask+)))
|
||||
(when (>= wd 0)
|
||||
(setf (gethash wd (inotify-watcher-wd-to-dir watcher)) clean
|
||||
(gethash clean (inotify-watcher-dir-to-wd watcher)) wd)
|
||||
wd)))))
|
||||
|
||||
(defun watcher-add-tree (watcher root-dir &key register-root)
|
||||
"Recursively add inotify watches on ROOT-DIR and all non-ignored subdirectories."
|
||||
(let ((clean (string-right-trim "/" root-dir)))
|
||||
(when register-root
|
||||
(pushnew clean (inotify-watcher-root-dirs watcher) :test #'string=))
|
||||
(let ((st (%safe-lstat clean)))
|
||||
(when (and st (sb-posix:s-isdir (sb-posix:stat-mode st)))
|
||||
(%watcher-add-dir watcher clean)
|
||||
(labels ((walk (dir)
|
||||
(handler-case
|
||||
(dolist (name (%list-dir-names dir))
|
||||
(let* ((child (format nil "~a/~a" dir name))
|
||||
(rel (%relative-to-roots watcher child)))
|
||||
(unless (path-ignored-p rel (inotify-watcher-ignores watcher))
|
||||
(let ((cst (%safe-lstat child)))
|
||||
(when (and cst
|
||||
(not (sb-posix:s-islnk (sb-posix:stat-mode cst)))
|
||||
(sb-posix:s-isdir (sb-posix:stat-mode cst)))
|
||||
(%watcher-add-dir watcher child)
|
||||
(walk child))))))
|
||||
(error () nil))))
|
||||
(walk clean))))))
|
||||
|
||||
(defun %u32-le (buf offset)
|
||||
(logior (aref buf offset)
|
||||
(ash (aref buf (+ offset 1)) 8)
|
||||
(ash (aref buf (+ offset 2)) 16)
|
||||
(ash (aref buf (+ offset 3)) 24)))
|
||||
|
||||
(defun %s32-le (buf offset)
|
||||
(let ((u (%u32-le buf offset)))
|
||||
(if (>= u #x80000000) (- u #x100000000) u)))
|
||||
|
||||
(defun watcher-poll-events (watcher &key (timeout-ms 250))
|
||||
"Wait up to TIMEOUT-MS for inotify events. Returns a list of INOTIFY-EVENT structs
|
||||
for non-ignored paths, automatically adding watches for newly created subdirectories."
|
||||
(let ((fd (inotify-watcher-fd watcher)))
|
||||
(when (< fd 0)
|
||||
(return-from watcher-poll-events nil))
|
||||
(unless (poll-fd-readable-p fd timeout-ms)
|
||||
(return-from watcher-poll-events nil))
|
||||
(let ((buf (inotify-watcher-buf watcher))
|
||||
(events '()))
|
||||
(loop
|
||||
(let ((n (sb-sys:with-pinned-objects (buf)
|
||||
(%c-read fd (sb-sys:vector-sap buf) (length buf)))))
|
||||
(when (<= n 0) (return))
|
||||
(let ((off 0))
|
||||
(loop while (<= (+ off 16) n)
|
||||
do (let* ((wd (%s32-le buf off))
|
||||
(mask (%u32-le buf (+ off 4)))
|
||||
(name-len (%u32-le buf (+ off 12)))
|
||||
(name-start (+ off 16))
|
||||
(name-end (min n (+ name-start name-len)))
|
||||
(nul-pos (position 0 buf :start name-start :end name-end))
|
||||
(actual-end (or nul-pos name-end))
|
||||
(name (if (> actual-end name-start)
|
||||
(handler-case
|
||||
(babel:octets-to-string buf
|
||||
:start name-start
|
||||
:end actual-end
|
||||
:encoding :utf-8)
|
||||
(error () ""))
|
||||
""))
|
||||
(dir (gethash wd (inotify-watcher-wd-to-dir watcher))))
|
||||
(incf off (+ 16 name-len))
|
||||
(cond
|
||||
((not (zerop (logand mask +in-ignored+)))
|
||||
(when dir
|
||||
(remhash wd (inotify-watcher-wd-to-dir watcher))
|
||||
(remhash dir (inotify-watcher-dir-to-wd watcher))))
|
||||
((not (zerop (logand mask +in-q-overflow+)))
|
||||
(push (make-inotify-event :wd wd :mask mask :path "" :name "") events))
|
||||
(dir
|
||||
(let* ((full-path (if (> (length name) 0)
|
||||
(format nil "~a/~a" dir name)
|
||||
dir))
|
||||
(rel (%relative-to-roots watcher full-path)))
|
||||
(unless (and (> (length rel) 0)
|
||||
(path-ignored-p rel (inotify-watcher-ignores watcher)))
|
||||
;; Auto-watch newly created or moved-in directories
|
||||
(when (and (not (zerop (logand mask +in-isdir+)))
|
||||
(not (zerop (logand mask (logior +in-create+ +in-moved-to+)))))
|
||||
(watcher-add-tree watcher full-path))
|
||||
(push (make-inotify-event :wd wd :mask mask :path full-path :name name)
|
||||
events))))))))))
|
||||
(nreverse events))))
|
||||
@@ -0,0 +1,79 @@
|
||||
(in-package #:nextcloud-niri)
|
||||
|
||||
(eval-when (:compile-toplevel :load-toplevel :execute)
|
||||
(require :sb-bsd-sockets))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Unix Domain Socket IPC (Client & Server)
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun ipc-send-command (cmd &key args (timeout-sec 3))
|
||||
"Send a JSON command to the running daemon over its Unix domain socket.
|
||||
Returns parsed JSON hash-table response, or NIL if daemon is not reachable."
|
||||
(declare (ignore timeout-sec))
|
||||
(let ((sock-file (socket-path)))
|
||||
(unless (probe-file (uiop:parse-native-namestring sock-file))
|
||||
(return-from ipc-send-command nil))
|
||||
(let ((sock (make-instance 'sb-bsd-sockets:local-socket :type :stream)))
|
||||
(handler-case
|
||||
(unwind-protect
|
||||
(progn
|
||||
(sb-bsd-sockets:socket-connect sock sock-file)
|
||||
(let ((stream (sb-bsd-sockets:socket-make-stream
|
||||
sock
|
||||
:input t
|
||||
:output t
|
||||
:element-type 'character
|
||||
:external-format :utf-8
|
||||
:buffering :line))
|
||||
(req (make-hash-table :test #'equal)))
|
||||
(setf (gethash "cmd" req) (string-downcase (string cmd)))
|
||||
(when args
|
||||
(setf (gethash "args" req) (coerce args 'vector)))
|
||||
(write-line (jzon:stringify req) stream)
|
||||
(finish-output stream)
|
||||
(let ((line (read-line stream nil nil)))
|
||||
(when (and line (> (length line) 0))
|
||||
(jzon:parse line)))))
|
||||
(ignore-errors (sb-bsd-sockets:socket-close sock)))
|
||||
(error () nil)))))
|
||||
|
||||
(defun make-ipc-server-socket ()
|
||||
"Create and bind the daemon Unix domain socket at (socket-path)."
|
||||
(let ((sock-file (socket-path)))
|
||||
(ensure-directory (runtime-dir))
|
||||
(when (probe-file (uiop:parse-native-namestring sock-file))
|
||||
(ignore-errors (sb-posix:unlink sock-file)))
|
||||
(let ((sock (make-instance 'sb-bsd-sockets:local-socket :type :stream)))
|
||||
(sb-bsd-sockets:socket-bind sock sock-file)
|
||||
(sb-bsd-sockets:socket-listen sock 8)
|
||||
(ignore-errors (sb-posix:chmod sock-file #o600))
|
||||
sock)))
|
||||
|
||||
(defun ipc-server-accept-once (server-sock handler-fn &key (timeout-ms 250))
|
||||
"Poll SERVER-SOCK for a client connection; if one arrives, read one JSON line,
|
||||
call (HANDLER-FN cmd args), write JSON response, and close."
|
||||
(let ((fd (sb-bsd-sockets:socket-file-descriptor server-sock)))
|
||||
(when (poll-fd-readable-p fd timeout-ms)
|
||||
(let ((client (ignore-errors (sb-bsd-sockets:socket-accept server-sock))))
|
||||
(when client
|
||||
(unwind-protect
|
||||
(handler-case
|
||||
(let* ((stream (sb-bsd-sockets:socket-make-stream
|
||||
client
|
||||
:input t
|
||||
:output t
|
||||
:element-type 'character
|
||||
:external-format :utf-8
|
||||
:buffering :line))
|
||||
(line (read-line stream nil nil)))
|
||||
(when (and line (> (length line) 0))
|
||||
(let* ((req (jzon:parse line))
|
||||
(cmd (gethash "cmd" req))
|
||||
(args (let ((a (gethash "args" req)))
|
||||
(if (vectorp a) (coerce a 'list) nil)))
|
||||
(resp (funcall handler-fn cmd args)))
|
||||
(write-line (jzon:stringify resp) stream)
|
||||
(finish-output stream))))
|
||||
(error () nil))
|
||||
(ignore-errors (sb-bsd-sockets:socket-close client))))))))
|
||||
@@ -0,0 +1,99 @@
|
||||
(in-package #:nextcloud-niri)
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Per-folder 3-way sync journal (persisted atomically as S-expressions)
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defstruct (journal-entry (:conc-name entry-))
|
||||
(rel-path "" :type string)
|
||||
(is-dir nil :type boolean)
|
||||
(local-mtime 0 :type integer)
|
||||
(local-size 0 :type integer)
|
||||
(local-sha256 nil)
|
||||
(remote-etag "" :type string)
|
||||
(remote-mtime 0 :type integer)
|
||||
(remote-size 0 :type integer)
|
||||
(remote-id "" :type string)
|
||||
(synced-at 0 :type integer))
|
||||
|
||||
(defstruct (journal (:conc-name journal-))
|
||||
(version 1 :type integer)
|
||||
(folder-id "" :type string)
|
||||
(root-etag "" :type string)
|
||||
(last-full-sync-ok nil :type boolean)
|
||||
(last-sync-time 0 :type integer)
|
||||
(entries (make-hash-table :test #'equal) :type hash-table))
|
||||
|
||||
(defun unix-now ()
|
||||
"Current Unix epoch timestamp in integer seconds."
|
||||
(- (get-universal-time) 2208988800))
|
||||
|
||||
(defun load-journal (path-str folder-id)
|
||||
"Load journal from PATH-STR, returning an empty journal if missing."
|
||||
(let ((data (read-sexp-file path-str))
|
||||
(j (make-journal :folder-id folder-id)))
|
||||
(when (and (listp data) (eql (getf data :version) 1))
|
||||
(setf (journal-root-etag j) (or (getf data :root-etag) ""))
|
||||
(setf (journal-last-full-sync-ok j) (not (null (getf data :last-full-sync-ok))))
|
||||
(setf (journal-last-sync-time j) (or (getf data :last-sync-time) 0))
|
||||
(let ((tbl (journal-entries j)))
|
||||
(dolist (e (getf data :entries))
|
||||
(let ((rel (getf e :rel-path)))
|
||||
(when (and (stringp rel) (> (length rel) 0))
|
||||
(setf (gethash rel tbl)
|
||||
(make-journal-entry
|
||||
:rel-path rel
|
||||
:is-dir (not (null (getf e :is-dir)))
|
||||
:local-mtime (or (getf e :local-mtime) 0)
|
||||
:local-size (or (getf e :local-size) 0)
|
||||
:local-sha256 (getf e :local-sha256)
|
||||
:remote-etag (or (getf e :remote-etag) "")
|
||||
:remote-mtime (or (getf e :remote-mtime) 0)
|
||||
:remote-size (or (getf e :remote-size) 0)
|
||||
:remote-id (or (getf e :remote-id) "")
|
||||
:synced-at (or (getf e :synced-at) 0))))))))
|
||||
j))
|
||||
|
||||
(defun save-journal (j path-str)
|
||||
"Atomically persist journal J to PATH-STR."
|
||||
(let* ((keys (sort (alex:hash-table-keys (journal-entries j)) #'string<))
|
||||
(entries-list
|
||||
(loop for k in keys
|
||||
for e = (gethash k (journal-entries j))
|
||||
collect (list :rel-path (entry-rel-path e)
|
||||
:is-dir (entry-is-dir e)
|
||||
:local-mtime (entry-local-mtime e)
|
||||
:local-size (entry-local-size e)
|
||||
:local-sha256 (entry-local-sha256 e)
|
||||
:remote-etag (entry-remote-etag e)
|
||||
:remote-mtime (entry-remote-mtime e)
|
||||
:remote-size (entry-remote-size e)
|
||||
:remote-id (entry-remote-id e)
|
||||
:synced-at (entry-synced-at e))))
|
||||
(payload (list :version 1
|
||||
:folder-id (journal-folder-id j)
|
||||
:root-etag (journal-root-etag j)
|
||||
:last-full-sync-ok (journal-last-full-sync-ok j)
|
||||
:last-sync-time (journal-last-sync-time j)
|
||||
:entries entries-list))
|
||||
(content
|
||||
(with-output-to-string (out)
|
||||
(let ((*print-pretty* nil)
|
||||
(*print-case* :downcase)
|
||||
(*print-readably* nil))
|
||||
(prin1 payload out)
|
||||
(terpri out)))))
|
||||
(write-string-atomic path-str content)))
|
||||
|
||||
(defun journal-subtree-entries (j dir-rel-path)
|
||||
"Return all journal entries strictly under DIR-REL-PATH (relative prefix)."
|
||||
(let ((prefix (if (zerop (length dir-rel-path))
|
||||
""
|
||||
(concatenate 'string (string-right-trim "/" dir-rel-path) "/")))
|
||||
(result '()))
|
||||
(maphash (lambda (k v)
|
||||
(when (and (> (length k) (length prefix))
|
||||
(string= k prefix :end1 (length prefix)))
|
||||
(push v result)))
|
||||
(journal-entries j))
|
||||
result))
|
||||
@@ -0,0 +1,126 @@
|
||||
(defpackage #:nextcloud-niri
|
||||
(:use #:cl)
|
||||
(:local-nicknames (#:jzon #:com.inuoe.jzon)
|
||||
(#:bt #:bordeaux-threads)
|
||||
(#:alex #:alexandria))
|
||||
(:export
|
||||
;; CLI entry point
|
||||
#:main
|
||||
;; SSL setup
|
||||
#:ensure-ssl-libraries
|
||||
;; Config
|
||||
#:*config-path-override*
|
||||
#:*credentials-path-override*
|
||||
#:*state-dir-override*
|
||||
#:*runtime-dir-override*
|
||||
#:app-config
|
||||
#:server-config
|
||||
#:sync-config
|
||||
#:waybar-config
|
||||
#:folder-config
|
||||
#:config-server
|
||||
#:config-sync
|
||||
#:config-waybar
|
||||
#:config-folders
|
||||
#:server-url
|
||||
#:server-username
|
||||
#:server-password
|
||||
#:server-password-cmd
|
||||
#:server-verify-ssl
|
||||
#:sync-poll-interval
|
||||
#:sync-debounce-seconds
|
||||
#:sync-chunk-size-mb
|
||||
#:sync-create-remote-if-missing
|
||||
#:sync-notify-on-error
|
||||
#:sync-ignore
|
||||
#:waybar-signal
|
||||
#:waybar-label
|
||||
#:folder-name
|
||||
#:folder-local
|
||||
#:folder-remote
|
||||
#:folder-id
|
||||
#:load-config
|
||||
#:save-config
|
||||
#:load-credentials
|
||||
#:save-credentials
|
||||
#:resolve-password
|
||||
#:config-path
|
||||
#:credentials-path
|
||||
#:state-dir
|
||||
#:runtime-dir
|
||||
#:status-path
|
||||
#:socket-path
|
||||
#:journal-path-for-folder
|
||||
#:path-ignored-p
|
||||
;; Journal
|
||||
#:journal
|
||||
#:journal-entry
|
||||
#:load-journal
|
||||
#:save-journal
|
||||
#:journal-root-etag
|
||||
#:journal-last-full-sync-ok
|
||||
#:journal-entries
|
||||
#:make-journal-entry
|
||||
#:entry-rel-path
|
||||
#:entry-is-dir
|
||||
#:entry-local-mtime
|
||||
#:entry-local-size
|
||||
#:entry-local-sha256
|
||||
#:entry-remote-etag
|
||||
#:entry-remote-mtime
|
||||
#:entry-remote-size
|
||||
#:entry-remote-id
|
||||
;; WebDAV
|
||||
#:webdav-error
|
||||
#:webdav-auth-error
|
||||
#:webdav-not-found-error
|
||||
#:webdav-client
|
||||
#:make-webdav-client
|
||||
#:remote-item
|
||||
#:remote-item-rel-path
|
||||
#:remote-item-is-dir
|
||||
#:remote-item-etag
|
||||
#:remote-item-size
|
||||
#:remote-item-mtime
|
||||
#:remote-item-file-id
|
||||
#:remote-item-checksum
|
||||
#:webdav-propfind
|
||||
#:webdav-mkcol
|
||||
#:webdav-ensure-dir
|
||||
#:webdav-download-file
|
||||
#:webdav-upload-file
|
||||
#:webdav-delete
|
||||
#:nextcloud-login-flow-start
|
||||
#:nextcloud-login-flow-poll
|
||||
;; Sync engine
|
||||
#:sync-result
|
||||
#:sync-result-folder-name
|
||||
#:sync-result-uploaded
|
||||
#:sync-result-downloaded
|
||||
#:sync-result-deleted-local
|
||||
#:sync-result-deleted-remote
|
||||
#:sync-result-conflicts
|
||||
#:sync-result-errors
|
||||
#:sync-result-file-count
|
||||
#:sync-result-skipped-p
|
||||
#:sync-folder
|
||||
#:sync-all-folders
|
||||
#:count-local-unsynced
|
||||
;; Inotify
|
||||
#:inotify-watcher
|
||||
#:make-inotify-watcher
|
||||
#:watcher-add-tree
|
||||
#:watcher-poll-events
|
||||
#:watcher-close
|
||||
;; Status & Waybar
|
||||
#:write-status
|
||||
#:read-status
|
||||
#:signal-waybar
|
||||
#:render-waybar-json
|
||||
;; IPC & Daemon
|
||||
#:ipc-send-command
|
||||
#:daemon-instance
|
||||
#:make-daemon
|
||||
#:daemon-start
|
||||
#:daemon-stop
|
||||
#:run-daemon))
|
||||
@@ -0,0 +1,34 @@
|
||||
(in-package #:nextcloud-niri)
|
||||
|
||||
(defvar *ssl-initialized* nil)
|
||||
|
||||
(defun find-openssl3-dir ()
|
||||
"Locate a directory containing OpenSSL 3 shared libraries (libcrypto.so.3 & libssl.so.3)."
|
||||
(let ((candidates
|
||||
(append
|
||||
(list (merge-pathnames ".guix-home/profile/lib/" (user-homedir-pathname))
|
||||
#P"/run/current-system/profile/lib/"
|
||||
#P"/usr/lib/x86_64-linux-gnu/"
|
||||
#P"/usr/lib64/"
|
||||
#P"/usr/lib/")
|
||||
(ignore-errors
|
||||
(sort (directory #P"/gnu/store/*-openssl-3.*/lib/")
|
||||
#'string> :key #'namestring)))))
|
||||
(dolist (dir candidates)
|
||||
(when (and dir
|
||||
(probe-file (merge-pathnames "libcrypto.so.3" dir))
|
||||
(probe-file (merge-pathnames "libssl.so.3" dir)))
|
||||
(return dir)))))
|
||||
|
||||
(defun ensure-ssl-libraries ()
|
||||
"Ensure CFFI can locate and load OpenSSL 3 libraries (important for saved SBCL images on Guix/Ubuntu)."
|
||||
(unless *ssl-initialized*
|
||||
(let ((dir (find-openssl3-dir)))
|
||||
(when dir
|
||||
(pushnew dir cffi:*foreign-library-directories* :test #'equal)))
|
||||
(ignore-errors
|
||||
(let ((reload (find-symbol "RELOAD" :cl+ssl)))
|
||||
(when (and reload (fboundp reload))
|
||||
(funcall reload))))
|
||||
(setf *ssl-initialized* t))
|
||||
t)
|
||||
@@ -0,0 +1,81 @@
|
||||
(in-package #:nextcloud-niri)
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Atomic Status Persistence, Waybar Signal & Optional Desktop Notifications
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun pid-alive-p (pid)
|
||||
"Return T if process PID exists and is alive."
|
||||
(and (integerp pid)
|
||||
(> pid 0)
|
||||
(handler-case
|
||||
(progn (sb-posix:kill pid 0) t)
|
||||
(sb-posix:syscall-error (e)
|
||||
;; EPERM (1) means process exists but owned by another user
|
||||
(eql (sb-posix:syscall-errno e) 1)))))
|
||||
|
||||
(defun signal-waybar (sig-num)
|
||||
"Notify Waybar via SIGRTMIN+SIG-NUM so the module refreshes immediately."
|
||||
(when (and (integerp sig-num) (> sig-num 0))
|
||||
(ignore-errors
|
||||
(uiop:run-program (list "pkill" (format nil "-SIGRTMIN+~d" sig-num) "waybar")
|
||||
:ignore-error-status t
|
||||
:output nil
|
||||
:error-output nil))))
|
||||
|
||||
(defun notify-desktop (title body &key (urgency "normal"))
|
||||
"Send a best-effort desktop notification via notify-send (e.g. mako)."
|
||||
(ignore-errors
|
||||
(uiop:run-program (list "notify-send" "-a" "nextcloud-niri" "-u" urgency title body)
|
||||
:ignore-error-status t
|
||||
:output nil
|
||||
:error-output nil)))
|
||||
|
||||
(defun write-status (&key state
|
||||
(pid (sb-posix:getpid))
|
||||
(server-url "")
|
||||
(last-sync 0)
|
||||
(pending 0)
|
||||
(progress-done 0)
|
||||
(progress-total 0)
|
||||
(progress-detail "")
|
||||
(error-msg "")
|
||||
(folders nil)
|
||||
(signal-num nil))
|
||||
"Atomically write runtime status.json and optionally signal Waybar."
|
||||
(let ((obj (make-hash-table :test #'equal))
|
||||
(folder-vec (make-array (length folders))))
|
||||
(setf (gethash "state" obj) (string-downcase (string state))
|
||||
(gethash "pid" obj) pid
|
||||
(gethash "updated_at" obj) (unix-now)
|
||||
(gethash "server_url" obj) (or server-url "")
|
||||
(gethash "last_sync" obj) (or last-sync 0)
|
||||
(gethash "pending" obj) (or pending 0)
|
||||
(gethash "progress_done" obj) (or progress-done 0)
|
||||
(gethash "progress_total" obj) (or progress-total 0)
|
||||
(gethash "progress_detail" obj) (or progress-detail "")
|
||||
(gethash "error" obj) (or error-msg ""))
|
||||
(loop for f in folders
|
||||
for i from 0
|
||||
do (let ((fh (make-hash-table :test #'equal)))
|
||||
(setf (gethash "name" fh) (getf f :name "")
|
||||
(gethash "local" fh) (getf f :local "")
|
||||
(gethash "remote" fh) (getf f :remote "")
|
||||
(gethash "state" fh) (string-downcase (string (or (getf f :state) :synced)))
|
||||
(gethash "files" fh) (or (getf f :files) 0)
|
||||
(gethash "error" fh) (or (getf f :error) "")
|
||||
(gethash "conflicts" fh) (coerce (or (getf f :conflicts) '()) 'vector))
|
||||
(setf (aref folder-vec i) fh)))
|
||||
(setf (gethash "folders" obj) folder-vec)
|
||||
(write-string-atomic (status-path) (jzon:stringify obj))
|
||||
(when signal-num
|
||||
(signal-waybar signal-num))
|
||||
obj))
|
||||
|
||||
(defun read-status ()
|
||||
"Read runtime status.json as a hash table, or NIL if missing/unreadable."
|
||||
(let ((p (uiop:parse-native-namestring (status-path))))
|
||||
(when (probe-file p)
|
||||
(handler-case
|
||||
(jzon:parse p)
|
||||
(error () nil)))))
|
||||
+753
@@ -0,0 +1,753 @@
|
||||
(in-package #:nextcloud-niri)
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; 3-Way Bidirectional Sync Engine
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defstruct (local-item (:conc-name local-item-))
|
||||
(rel-path "" :type string)
|
||||
(abs-path "" :type string)
|
||||
(is-dir nil :type boolean)
|
||||
(mtime 0 :type integer)
|
||||
(size 0 :type integer))
|
||||
|
||||
(defstruct (sync-result (:conc-name sync-result-))
|
||||
(folder-name "" :type string)
|
||||
(local-path "" :type string)
|
||||
(remote-path "" :type string)
|
||||
(uploaded 0 :type integer)
|
||||
(downloaded 0 :type integer)
|
||||
(deleted-local 0 :type integer)
|
||||
(deleted-remote 0 :type integer)
|
||||
(conflicts nil :type list)
|
||||
(errors nil :type list)
|
||||
(file-count 0 :type integer)
|
||||
(skipped-p nil :type boolean))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Wildcard-Safe POSIX Local Filesystem Helpers
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun file-sha256-hex (path-str)
|
||||
"Compute SHA-256 hex digest of file at PATH-STR in streaming 64KB chunks."
|
||||
(let ((digester (ironclad:make-digest :sha256))
|
||||
(buf (make-array 65536 :element-type '(unsigned-byte 8))))
|
||||
(with-open-file (in (uiop:parse-native-namestring path-str)
|
||||
:direction :input
|
||||
:element-type '(unsigned-byte 8))
|
||||
(loop for n = (read-sequence buf in)
|
||||
while (> n 0)
|
||||
do (ironclad:update-digest digester buf :start 0 :end n)))
|
||||
(ironclad:byte-array-to-hex-string (ironclad:produce-digest digester))))
|
||||
|
||||
(defun %safe-lstat (path-str)
|
||||
(handler-case (sb-posix:lstat path-str)
|
||||
(sb-posix:syscall-error () nil)))
|
||||
|
||||
(defun %list-dir-names (dir-str)
|
||||
"List entry names in DIR-STR via POSIX opendir/readdir (immune to CL pathname wildcards)."
|
||||
(let ((dir-handle (sb-posix:opendir dir-str))
|
||||
(names '()))
|
||||
(unwind-protect
|
||||
(loop for dirent = (sb-posix:readdir dir-handle)
|
||||
until (sb-alien:null-alien dirent)
|
||||
do (let ((name (sb-posix:dirent-name dirent)))
|
||||
(unless (or (string= name ".") (string= name ".."))
|
||||
(push name names))))
|
||||
(sb-posix:closedir dir-handle))
|
||||
(sort names #'string<)))
|
||||
|
||||
(defun scan-local-tree (local-root ignores)
|
||||
"Recursively scan LOCAL-ROOT, returning a hash table rel-path -> LOCAL-ITEM.
|
||||
Skips symlinks and paths matching IGNORES."
|
||||
(let ((table (make-hash-table :test #'equal))
|
||||
(root (string-right-trim "/" local-root)))
|
||||
(labels ((walk (abs-dir rel-prefix)
|
||||
(dolist (name (%list-dir-names abs-dir))
|
||||
(let ((rel (if (zerop (length rel-prefix))
|
||||
name
|
||||
(format nil "~a/~a" rel-prefix name)))
|
||||
(abs (format nil "~a/~a" abs-dir name)))
|
||||
(unless (path-ignored-p rel ignores)
|
||||
(let ((st (%safe-lstat abs)))
|
||||
(when st
|
||||
(let ((mode (sb-posix:stat-mode st)))
|
||||
(cond
|
||||
((sb-posix:s-islnk mode)
|
||||
;; Skip symlinks like official Nextcloud Desktop client
|
||||
nil)
|
||||
((sb-posix:s-isdir mode)
|
||||
(setf (gethash rel table)
|
||||
(make-local-item
|
||||
:rel-path rel
|
||||
:abs-path abs
|
||||
:is-dir t
|
||||
:mtime (sb-posix:stat-mtime st)
|
||||
:size 0))
|
||||
(walk abs rel))
|
||||
((sb-posix:s-isreg mode)
|
||||
(setf (gethash rel table)
|
||||
(make-local-item
|
||||
:rel-path rel
|
||||
:abs-path abs
|
||||
:is-dir nil
|
||||
:mtime (sb-posix:stat-mtime st)
|
||||
:size (sb-posix:stat-size st)))))))))))))
|
||||
(walk root ""))
|
||||
table))
|
||||
|
||||
(defun %local-changed-p (local-item journal-entry)
|
||||
"Return (values changed-p computed-sha256) comparing LOCAL-ITEM to JOURNAL-ENTRY."
|
||||
(cond
|
||||
((null journal-entry) (values t nil))
|
||||
((not (eq (local-item-is-dir local-item) (entry-is-dir journal-entry)))
|
||||
(values t nil))
|
||||
((local-item-is-dir local-item)
|
||||
(values nil nil))
|
||||
((and (= (local-item-mtime local-item) (entry-local-mtime journal-entry))
|
||||
(= (local-item-size local-item) (entry-local-size journal-entry)))
|
||||
(values nil (entry-local-sha256 journal-entry)))
|
||||
;; Size unchanged + we have a stored hash -> verify content before flagging modified
|
||||
((and (= (local-item-size local-item) (entry-local-size journal-entry))
|
||||
(entry-local-sha256 journal-entry))
|
||||
(let ((h (file-sha256-hex (local-item-abs-path local-item))))
|
||||
(if (string= h (entry-local-sha256 journal-entry))
|
||||
(values nil h)
|
||||
(values t h))))
|
||||
(t (values t nil))))
|
||||
|
||||
(defun count-local-unsynced (folder ignores)
|
||||
"Quick local-vs-journal check returning the number of locally changed/new/deleted entries."
|
||||
(let ((local-root (folder-local folder)))
|
||||
(let ((st (%safe-lstat local-root)))
|
||||
(unless (and st (sb-posix:s-isdir (sb-posix:stat-mode st)))
|
||||
(return-from count-local-unsynced 0)))
|
||||
(let* ((j (load-journal (journal-path-for-folder folder) (folder-id folder)))
|
||||
(local-map (scan-local-tree local-root ignores))
|
||||
(j-map (journal-entries j))
|
||||
(count 0))
|
||||
(maphash (lambda (rel loc)
|
||||
(let ((je (gethash rel j-map)))
|
||||
(when (nth-value 0 (%local-changed-p loc je))
|
||||
(incf count))))
|
||||
local-map)
|
||||
(maphash (lambda (rel je)
|
||||
(declare (ignore je))
|
||||
(unless (gethash rel local-map)
|
||||
(incf count)))
|
||||
j-map)
|
||||
count)))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Remote Tree Scanning with Nextcloud oc:etag Directory Pruning
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun %remote-join (base rel)
|
||||
(let ((b (string-trim "/" base))
|
||||
(r (string-trim "/" rel)))
|
||||
(cond
|
||||
((zerop (length b)) r)
|
||||
((zerop (length r)) b)
|
||||
(t (format nil "~a/~a" b r)))))
|
||||
|
||||
(defun %scan-remote-tree (client remote-root journal ignores &key force-full-scan)
|
||||
"Scan REMOTE-ROOT recursively with Depth: 1, pruning unchanged subdirectories via oc:etag.
|
||||
Returns (values remote-table root-etag)."
|
||||
(let ((table (make-hash-table :test #'equal))
|
||||
(j-map (journal-entries journal))
|
||||
(can-prune (and (not force-full-scan)
|
||||
(journal-last-full-sync-ok journal)))
|
||||
(root-etag ""))
|
||||
(labels ((walk (rel-dir)
|
||||
(let ((full-remote (%remote-join remote-root rel-dir)))
|
||||
(multiple-value-bind (self children)
|
||||
(webdav-propfind client full-remote :depth 1 :base-remote-path remote-root)
|
||||
(when (and (zerop (length rel-dir)) self)
|
||||
(setf root-etag (remote-item-etag self)))
|
||||
(dolist (item children)
|
||||
(let ((rel (remote-item-rel-path item)))
|
||||
(when (and (> (length rel) 0)
|
||||
(not (path-ignored-p rel ignores)))
|
||||
(setf (gethash rel table) item)
|
||||
(when (remote-item-is-dir item)
|
||||
(let ((je (gethash rel j-map)))
|
||||
(if (and can-prune
|
||||
je
|
||||
(entry-is-dir je)
|
||||
(> (length (remote-item-etag item)) 0)
|
||||
(string= (remote-item-etag item) (entry-remote-etag je)))
|
||||
;; Unchanged remote directory subtree -> hydrate from journal!
|
||||
(dolist (sub (journal-subtree-entries journal rel))
|
||||
(setf (gethash (entry-rel-path sub) table)
|
||||
(make-remote-item
|
||||
:rel-path (entry-rel-path sub)
|
||||
:is-dir (entry-is-dir sub)
|
||||
:etag (entry-remote-etag sub)
|
||||
:size (entry-remote-size sub)
|
||||
:mtime (entry-remote-mtime sub)
|
||||
:file-id (entry-remote-id sub))))
|
||||
(walk rel)))))))))))
|
||||
(walk ""))
|
||||
(values table root-etag)))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Conflict Naming & Safe File Removal
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun %conflict-path-for (abs-path)
|
||||
"Generate a Nextcloud-style conflict copy path beside ABS-PATH."
|
||||
(multiple-value-bind (sec min hr day mon yr) (get-decoded-time)
|
||||
(let* ((stamp (format nil "~4,'0d-~2,'0d-~2,'0d ~2,'0d~2,'0d~2,'0d" yr mon day hr min sec))
|
||||
(slash (position #\/ abs-path :from-end t))
|
||||
(dir (if slash (subseq abs-path 0 slash) "."))
|
||||
(base (if slash (subseq abs-path (1+ slash)) abs-path))
|
||||
(dot (position #\. base :from-end t))
|
||||
(has-ext (and dot (> dot 0)))
|
||||
(stem (if has-ext (subseq base 0 dot) base))
|
||||
(ext (if has-ext (subseq base dot) "")))
|
||||
(loop for n from 0
|
||||
for suffix = (if (zerop n) "" (format nil " (~d)" n))
|
||||
for candidate = (format nil "~a/~a (conflicted copy ~a~a)~a"
|
||||
dir stem stamp suffix ext)
|
||||
unless (%safe-lstat candidate)
|
||||
do (return candidate)))))
|
||||
|
||||
(defun %delete-local-path (abs-path is-dir)
|
||||
(let ((st (%safe-lstat abs-path)))
|
||||
(when st
|
||||
(if is-dir
|
||||
(ignore-errors (sb-posix:rmdir abs-path))
|
||||
(sb-posix:unlink abs-path)))))
|
||||
|
||||
(defun %ensure-local-dir (abs-path)
|
||||
(let ((st (%safe-lstat abs-path)))
|
||||
(unless st
|
||||
(ensure-directory abs-path))))
|
||||
|
||||
(defun %path-depth (rel-path)
|
||||
(count #\/ rel-path))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Main Folder Synchronization
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun %remote-changed-p (rem je)
|
||||
(cond
|
||||
((null je) t)
|
||||
((not (eq (remote-item-is-dir rem) (entry-is-dir je))) t)
|
||||
((and (> (length (remote-item-etag rem)) 0)
|
||||
(> (length (entry-remote-etag je)) 0))
|
||||
(not (string= (remote-item-etag rem) (entry-remote-etag je))))
|
||||
(t (or (/= (remote-item-size rem) (entry-remote-size je))
|
||||
(/= (remote-item-mtime rem) (entry-remote-mtime je))))))
|
||||
|
||||
(defun %maybe-record-self-write (fn path)
|
||||
(when fn (funcall fn path)))
|
||||
|
||||
(defun %report-progress (fn done total detail)
|
||||
(when fn (funcall fn done total detail)))
|
||||
|
||||
(defun sync-folder (client folder sync-cfg &key force-full-scan on-progress on-local-write)
|
||||
"Bidirectionally synchronize FOLDER using 3-way reconciliation.
|
||||
Returns a SYNC-RESULT struct."
|
||||
(let* ((local-root (string-right-trim "/" (folder-local folder)))
|
||||
(remote-root (string-trim "/" (folder-remote folder)))
|
||||
(ignores (sync-ignore sync-cfg))
|
||||
(j-path (journal-path-for-folder folder))
|
||||
(journal (load-journal j-path (folder-id folder)))
|
||||
(result (make-sync-result
|
||||
:folder-name (folder-name folder)
|
||||
:local-path local-root
|
||||
:remote-path remote-root)))
|
||||
|
||||
;; Safety Guard: refuse to wipe remote if the local root directory disappeared!
|
||||
(let ((root-st (%safe-lstat local-root)))
|
||||
(cond
|
||||
((null root-st)
|
||||
(if (zerop (hash-table-count (journal-entries journal)))
|
||||
;; Brand-new folder never synced before -> create local root
|
||||
(ensure-directory local-root)
|
||||
(progn
|
||||
(push (format nil "Local folder missing (refusing to delete remote): ~a" local-root)
|
||||
(sync-result-errors result))
|
||||
(return-from sync-folder result))))
|
||||
((not (sb-posix:s-isdir (sb-posix:stat-mode root-st)))
|
||||
(push (format nil "Local path is not a directory: ~a" local-root)
|
||||
(sync-result-errors result))
|
||||
(return-from sync-folder result))))
|
||||
|
||||
;; Step 1: Lightweight root ETag check on remote
|
||||
(let ((remote-root-item nil))
|
||||
(handler-case
|
||||
(setf remote-root-item (webdav-propfind client remote-root :depth 0))
|
||||
(webdav-not-found-error ()
|
||||
(if (sync-create-remote-if-missing sync-cfg)
|
||||
(progn
|
||||
(webdav-ensure-dir client remote-root)
|
||||
(setf remote-root-item (webdav-propfind client remote-root :depth 0)))
|
||||
(progn
|
||||
(push (format nil "Remote folder does not exist: ~a" remote-root)
|
||||
(sync-result-errors result))
|
||||
(return-from sync-folder result))))
|
||||
(error (e)
|
||||
(push (format nil "~a" e) (sync-result-errors result))
|
||||
(return-from sync-folder result)))
|
||||
|
||||
;; Step 2: Scan local filesystem
|
||||
(let* ((local-map (scan-local-tree local-root ignores))
|
||||
(j-map (journal-entries journal))
|
||||
(current-root-etag (if remote-root-item (remote-item-etag remote-root-item) ""))
|
||||
(remote-unchanged-p (and (not force-full-scan)
|
||||
(journal-last-full-sync-ok journal)
|
||||
(> (length current-root-etag) 0)
|
||||
(string= current-root-etag (journal-root-etag journal))))
|
||||
(local-has-changes nil))
|
||||
|
||||
;; Check if local differs from journal
|
||||
(maphash (lambda (rel loc)
|
||||
(when (nth-value 0 (%local-changed-p loc (gethash rel j-map)))
|
||||
(setf local-has-changes t)))
|
||||
local-map)
|
||||
(unless local-has-changes
|
||||
(maphash (lambda (rel je)
|
||||
(declare (ignore je))
|
||||
(unless (gethash rel local-map)
|
||||
(setf local-has-changes t)))
|
||||
j-map))
|
||||
|
||||
;; Fast-path short-circuit when BOTH sides are unchanged!
|
||||
(when (and remote-unchanged-p (not local-has-changes))
|
||||
(setf (sync-result-skipped-p result) t)
|
||||
(setf (sync-result-file-count result)
|
||||
(loop for loc being the hash-values of local-map
|
||||
count (not (local-item-is-dir loc))))
|
||||
(return-from sync-folder result))
|
||||
|
||||
;; Step 3: Build remote map (either directly from journal if root ETag matched, or via ETag-pruned PROPFIND)
|
||||
(let ((remote-map (make-hash-table :test #'equal))
|
||||
(scanned-root-etag current-root-etag))
|
||||
(if remote-unchanged-p
|
||||
(maphash (lambda (rel je)
|
||||
(setf (gethash rel remote-map)
|
||||
(make-remote-item
|
||||
:rel-path rel
|
||||
:is-dir (entry-is-dir je)
|
||||
:etag (entry-remote-etag je)
|
||||
:size (entry-remote-size je)
|
||||
:mtime (entry-remote-mtime je)
|
||||
:file-id (entry-remote-id je))))
|
||||
j-map)
|
||||
(handler-case
|
||||
(multiple-value-bind (rmap retag)
|
||||
(%scan-remote-tree client remote-root journal ignores
|
||||
:force-full-scan force-full-scan)
|
||||
(setf remote-map rmap
|
||||
scanned-root-etag retag))
|
||||
(error (e)
|
||||
(push (format nil "Remote scan failed: ~a" e) (sync-result-errors result))
|
||||
(return-from sync-folder result))))
|
||||
|
||||
;; Step 4: Plan actions across union of Local ∪ Remote ∪ Journal
|
||||
(let ((all-paths (make-hash-table :test #'equal))
|
||||
(mkdir-local '())
|
||||
(mkdir-remote '())
|
||||
(uploads '())
|
||||
(downloads '())
|
||||
(conflicts '())
|
||||
(delete-local '())
|
||||
(delete-remote '())
|
||||
(journal-updates '())
|
||||
(journal-removals '()))
|
||||
(maphash (lambda (k v) (declare (ignore v)) (setf (gethash k all-paths) t)) local-map)
|
||||
(maphash (lambda (k v) (declare (ignore v)) (setf (gethash k all-paths) t)) remote-map)
|
||||
(maphash (lambda (k v) (declare (ignore v)) (setf (gethash k all-paths) t)) j-map)
|
||||
|
||||
(maphash
|
||||
(lambda (rel _)
|
||||
(declare (ignore _))
|
||||
(let ((loc (gethash rel local-map))
|
||||
(rem (gethash rel remote-map))
|
||||
(je (gethash rel j-map)))
|
||||
(cond
|
||||
;; Case A: In Journal, Local, and Remote
|
||||
((and je loc rem)
|
||||
(multiple-value-bind (loc-mod loc-hash) (%local-changed-p loc je)
|
||||
(let ((rem-mod (%remote-changed-p rem je)))
|
||||
(cond
|
||||
((and (not loc-mod) (not rem-mod))
|
||||
;; Update mtime in journal if touched without content change
|
||||
(when (and (not (local-item-is-dir loc))
|
||||
(/= (local-item-mtime loc) (entry-local-mtime je)))
|
||||
(push (list rel loc rem loc-hash) journal-updates)))
|
||||
((and (local-item-is-dir loc) (remote-item-is-dir rem))
|
||||
(push (list rel loc rem nil) journal-updates))
|
||||
((and loc-mod (not rem-mod))
|
||||
(if (local-item-is-dir loc)
|
||||
(push rel mkdir-remote)
|
||||
(push (list rel loc loc-hash) uploads)))
|
||||
((and (not loc-mod) rem-mod)
|
||||
(if (remote-item-is-dir rem)
|
||||
(push (list rel rem) mkdir-local)
|
||||
(push (list rel rem) downloads)))
|
||||
(t
|
||||
;; Both modified!
|
||||
(push (list rel loc rem loc-hash) conflicts))))))
|
||||
|
||||
;; Case B: In Journal and Remote, deleted Locally
|
||||
((and je (null loc) rem)
|
||||
(if (%remote-changed-p rem je)
|
||||
;; Remote was modified -> keep remote (re-download)
|
||||
(if (remote-item-is-dir rem)
|
||||
(push (list rel rem) mkdir-local)
|
||||
(push (list rel rem) downloads))
|
||||
;; Remote unchanged -> propagate local deletion to remote
|
||||
(push (list rel (remote-item-is-dir rem)) delete-remote)))
|
||||
|
||||
;; Case C: In Journal and Local, deleted Remotely
|
||||
((and je loc (null rem))
|
||||
(multiple-value-bind (loc-mod loc-hash) (%local-changed-p loc je)
|
||||
(if (and loc-mod (not (local-item-is-dir loc)))
|
||||
;; Local modified -> keep local (re-upload)
|
||||
(push (list rel loc loc-hash) uploads)
|
||||
;; Local unchanged -> propagate remote deletion to local
|
||||
(push (list rel (local-item-is-dir loc)) delete-local))))
|
||||
|
||||
;; Case D: In Journal only (deleted on both sides)
|
||||
((and je (null loc) (null rem))
|
||||
(push rel journal-removals))
|
||||
|
||||
;; Case E: New Local only
|
||||
((and (null je) loc (null rem))
|
||||
(if (local-item-is-dir loc)
|
||||
(push rel mkdir-remote)
|
||||
(push (list rel loc nil) uploads)))
|
||||
|
||||
;; Case F: New Remote only
|
||||
((and (null je) (null loc) rem)
|
||||
(if (remote-item-is-dir rem)
|
||||
(push (list rel rem) mkdir-local)
|
||||
(push (list rel rem) downloads)))
|
||||
|
||||
;; Case G: New on BOTH sides (initial sync or simultaneous creation)
|
||||
((and (null je) loc rem)
|
||||
(cond
|
||||
((and (local-item-is-dir loc) (remote-item-is-dir rem))
|
||||
(push (list rel loc rem nil) journal-updates))
|
||||
(t
|
||||
(push (list rel loc rem nil) conflicts)))))))
|
||||
all-paths)
|
||||
|
||||
;; Sort operations: creates top-down, deletes bottom-up
|
||||
(setf mkdir-local (sort mkdir-local #'< :key (lambda (x) (%path-depth (first x))))
|
||||
mkdir-remote (sort mkdir-remote #'< :key #'%path-depth)
|
||||
uploads (sort uploads #'string< :key #'first)
|
||||
downloads (sort downloads #'string< :key #'first)
|
||||
conflicts (sort conflicts #'string< :key #'first)
|
||||
delete-local (sort delete-local #'> :key (lambda (x) (%path-depth (first x))))
|
||||
delete-remote (sort delete-remote #'> :key (lambda (x) (%path-depth (first x)))))
|
||||
|
||||
(let* ((total-ops (+ (length uploads) (length downloads) (length conflicts)
|
||||
(length delete-local) (length delete-remote)))
|
||||
(done-ops 0)
|
||||
(now (unix-now))
|
||||
(mutated-remote nil))
|
||||
|
||||
;; 1. Apply metadata-only journal updates & removals
|
||||
(dolist (rel journal-removals)
|
||||
(remhash rel j-map))
|
||||
(dolist (upd journal-updates)
|
||||
(destructuring-bind (rel loc rem loc-hash) upd
|
||||
(setf (gethash rel j-map)
|
||||
(make-journal-entry
|
||||
:rel-path rel
|
||||
:is-dir (local-item-is-dir loc)
|
||||
:local-mtime (local-item-mtime loc)
|
||||
:local-size (local-item-size loc)
|
||||
:local-sha256 (or loc-hash
|
||||
(when (gethash rel j-map)
|
||||
(entry-local-sha256 (gethash rel j-map))))
|
||||
:remote-etag (remote-item-etag rem)
|
||||
:remote-mtime (remote-item-mtime rem)
|
||||
:remote-size (remote-item-size rem)
|
||||
:remote-id (remote-item-file-id rem)
|
||||
:synced-at now))))
|
||||
|
||||
;; 2. Create local directories (top-down)
|
||||
(dolist (entry mkdir-local)
|
||||
(destructuring-bind (rel rem) entry
|
||||
(let ((abs (format nil "~a/~a" local-root rel)))
|
||||
(handler-case
|
||||
(progn
|
||||
(%maybe-record-self-write on-local-write abs)
|
||||
(%ensure-local-dir abs)
|
||||
(let ((st (%safe-lstat abs)))
|
||||
(setf (gethash rel j-map)
|
||||
(make-journal-entry
|
||||
:rel-path rel
|
||||
:is-dir t
|
||||
:local-mtime (if st (sb-posix:stat-mtime st) now)
|
||||
:local-size 0
|
||||
:remote-etag (remote-item-etag rem)
|
||||
:remote-mtime (remote-item-mtime rem)
|
||||
:remote-size 0
|
||||
:remote-id (remote-item-file-id rem)
|
||||
:synced-at now))))
|
||||
(error (e)
|
||||
(push (format nil "mkdir local ~a: ~a" rel e) (sync-result-errors result)))))))
|
||||
|
||||
;; 3. Create remote directories (top-down)
|
||||
(dolist (rel mkdir-remote)
|
||||
(let ((full-remote (%remote-join remote-root rel))
|
||||
(loc (gethash rel local-map)))
|
||||
(handler-case
|
||||
(progn
|
||||
(webdav-mkcol client full-remote)
|
||||
(setf mutated-remote t)
|
||||
(let ((ritem (ignore-errors (webdav-propfind client full-remote :depth 0))))
|
||||
(setf (gethash rel j-map)
|
||||
(make-journal-entry
|
||||
:rel-path rel
|
||||
:is-dir t
|
||||
:local-mtime (if loc (local-item-mtime loc) now)
|
||||
:local-size 0
|
||||
:remote-etag (if ritem (remote-item-etag ritem) "")
|
||||
:remote-mtime (if ritem (remote-item-mtime ritem) now)
|
||||
:remote-size 0
|
||||
:remote-id (if ritem (remote-item-file-id ritem) "")
|
||||
:synced-at now))))
|
||||
(error (e)
|
||||
(push (format nil "mkdir remote ~a: ~a" rel e) (sync-result-errors result))))))
|
||||
|
||||
;; 4. Download remote files
|
||||
(dolist (entry downloads)
|
||||
(destructuring-bind (rel rem) entry
|
||||
(incf done-ops)
|
||||
(%report-progress on-progress done-ops total-ops (format nil "↓ ~a" rel))
|
||||
(let ((abs (format nil "~a/~a" local-root rel))
|
||||
(full-remote (%remote-join remote-root rel)))
|
||||
(handler-case
|
||||
(progn
|
||||
(%maybe-record-self-write on-local-write abs)
|
||||
(multiple-value-bind (sha bytes dl-etag)
|
||||
(webdav-download-file client full-remote abs
|
||||
:remote-mtime (remote-item-mtime rem))
|
||||
(let ((st (%safe-lstat abs)))
|
||||
(setf (gethash rel j-map)
|
||||
(make-journal-entry
|
||||
:rel-path rel
|
||||
:is-dir nil
|
||||
:local-mtime (if st (sb-posix:stat-mtime st) (remote-item-mtime rem))
|
||||
:local-size (if st (sb-posix:stat-size st) bytes)
|
||||
:local-sha256 sha
|
||||
:remote-etag (if (> (length (remote-item-etag rem)) 0)
|
||||
(remote-item-etag rem)
|
||||
dl-etag)
|
||||
:remote-mtime (remote-item-mtime rem)
|
||||
:remote-size bytes
|
||||
:remote-id (remote-item-file-id rem)
|
||||
:synced-at now))
|
||||
(incf (sync-result-downloaded result)))))
|
||||
(error (e)
|
||||
(push (format nil "download ~a: ~a" rel e) (sync-result-errors result)))))))
|
||||
|
||||
;; 5. Upload local files
|
||||
(dolist (entry uploads)
|
||||
(destructuring-bind (rel loc loc-hash) entry
|
||||
(incf done-ops)
|
||||
(%report-progress on-progress done-ops total-ops (format nil "↑ ~a" rel))
|
||||
(let ((abs (local-item-abs-path loc))
|
||||
(full-remote (%remote-join remote-root rel)))
|
||||
(handler-case
|
||||
(let ((sha (or loc-hash (file-sha256-hex abs))))
|
||||
(multiple-value-bind (etag fid)
|
||||
(webdav-upload-file client abs full-remote :mtime (local-item-mtime loc))
|
||||
(setf mutated-remote t)
|
||||
(setf (gethash rel j-map)
|
||||
(make-journal-entry
|
||||
:rel-path rel
|
||||
:is-dir nil
|
||||
:local-mtime (local-item-mtime loc)
|
||||
:local-size (local-item-size loc)
|
||||
:local-sha256 sha
|
||||
:remote-etag etag
|
||||
:remote-mtime (local-item-mtime loc)
|
||||
:remote-size (local-item-size loc)
|
||||
:remote-id fid
|
||||
:synced-at now))
|
||||
(incf (sync-result-uploaded result))))
|
||||
(error (e)
|
||||
(push (format nil "upload ~a: ~a" rel e) (sync-result-errors result)))))))
|
||||
|
||||
;; 6. Resolve conflicts safely (never lose local data!)
|
||||
(dolist (entry conflicts)
|
||||
(destructuring-bind (rel loc rem loc-hash) entry
|
||||
(incf done-ops)
|
||||
(%report-progress on-progress done-ops total-ops (format nil "! ~a" rel))
|
||||
(let ((abs (local-item-abs-path loc))
|
||||
(full-remote (%remote-join remote-root rel)))
|
||||
(handler-case
|
||||
(cond
|
||||
;; Both are files -> check if content is actually identical first
|
||||
((and (not (local-item-is-dir loc)) (not (remote-item-is-dir rem)))
|
||||
(let* ((local-sha (or loc-hash (file-sha256-hex abs)))
|
||||
(tmp-check (format nil "~a/.nextcloud-niri.tmp.cmp.~d"
|
||||
local-root (sb-posix:getpid))))
|
||||
(unwind-protect
|
||||
(multiple-value-bind (rem-sha rem-bytes dl-etag)
|
||||
(webdav-download-file client full-remote tmp-check
|
||||
:remote-mtime (remote-item-mtime rem))
|
||||
(if (string= local-sha rem-sha)
|
||||
;; Identical bytes! Just record in journal, no conflict.
|
||||
(setf (gethash rel j-map)
|
||||
(make-journal-entry
|
||||
:rel-path rel
|
||||
:is-dir nil
|
||||
:local-mtime (local-item-mtime loc)
|
||||
:local-size (local-item-size loc)
|
||||
:local-sha256 local-sha
|
||||
:remote-etag (if (> (length (remote-item-etag rem)) 0)
|
||||
(remote-item-etag rem)
|
||||
dl-etag)
|
||||
:remote-mtime (remote-item-mtime rem)
|
||||
:remote-size rem-bytes
|
||||
:remote-id (remote-item-file-id rem)
|
||||
:synced-at now))
|
||||
;; True conflict: preserve local as conflicted copy, place remote at original
|
||||
(let ((conflict-abs (%conflict-path-for abs)))
|
||||
(%maybe-record-self-write on-local-write abs)
|
||||
(%maybe-record-self-write on-local-write conflict-abs)
|
||||
(sb-posix:rename abs conflict-abs)
|
||||
(sb-posix:rename tmp-check abs)
|
||||
(let ((st (%safe-lstat abs)))
|
||||
(setf (gethash rel j-map)
|
||||
(make-journal-entry
|
||||
:rel-path rel
|
||||
:is-dir nil
|
||||
:local-mtime (if st (sb-posix:stat-mtime st) (remote-item-mtime rem))
|
||||
:local-size (if st (sb-posix:stat-size st) rem-bytes)
|
||||
:local-sha256 rem-sha
|
||||
:remote-etag (if (> (length (remote-item-etag rem)) 0)
|
||||
(remote-item-etag rem)
|
||||
dl-etag)
|
||||
:remote-mtime (remote-item-mtime rem)
|
||||
:remote-size rem-bytes
|
||||
:remote-id (remote-item-file-id rem)
|
||||
:synced-at now)))
|
||||
;; Also upload the conflicted copy so both versions exist everywhere
|
||||
(let* ((conflict-rel (subseq conflict-abs (1+ (length local-root))))
|
||||
(conflict-st (%safe-lstat conflict-abs)))
|
||||
(when conflict-st
|
||||
(multiple-value-bind (c-etag c-fid)
|
||||
(webdav-upload-file client conflict-abs
|
||||
(%remote-join remote-root conflict-rel)
|
||||
:mtime (sb-posix:stat-mtime conflict-st))
|
||||
(setf mutated-remote t)
|
||||
(setf (gethash conflict-rel j-map)
|
||||
(make-journal-entry
|
||||
:rel-path conflict-rel
|
||||
:is-dir nil
|
||||
:local-mtime (sb-posix:stat-mtime conflict-st)
|
||||
:local-size (sb-posix:stat-size conflict-st)
|
||||
:local-sha256 local-sha
|
||||
:remote-etag c-etag
|
||||
:remote-mtime (sb-posix:stat-mtime conflict-st)
|
||||
:remote-size (sb-posix:stat-size conflict-st)
|
||||
:remote-id c-fid
|
||||
:synced-at now)))))
|
||||
(incf (sync-result-downloaded result))
|
||||
(push rel (sync-result-conflicts result)))))
|
||||
(when (%safe-lstat tmp-check)
|
||||
(ignore-errors (sb-posix:unlink tmp-check))))))
|
||||
;; Type mismatch (file vs dir): preserve local as conflicted copy, take remote
|
||||
(t
|
||||
(let ((conflict-abs (%conflict-path-for abs)))
|
||||
(%maybe-record-self-write on-local-write abs)
|
||||
(%maybe-record-self-write on-local-write conflict-abs)
|
||||
(sb-posix:rename abs conflict-abs)
|
||||
(if (remote-item-is-dir rem)
|
||||
(%ensure-local-dir abs)
|
||||
(webdav-download-file client full-remote abs
|
||||
:remote-mtime (remote-item-mtime rem)))
|
||||
(push rel (sync-result-conflicts result)))))
|
||||
(error (e)
|
||||
(push (format nil "conflict ~a: ~a" rel e) (sync-result-errors result)))))))
|
||||
|
||||
;; 7. Delete local files/dirs (bottom-up)
|
||||
(dolist (entry delete-local)
|
||||
(destructuring-bind (rel is-dir) entry
|
||||
(incf done-ops)
|
||||
(%report-progress on-progress done-ops total-ops (format nil "× ~a" rel))
|
||||
(let ((abs (format nil "~a/~a" local-root rel)))
|
||||
(handler-case
|
||||
(progn
|
||||
(%maybe-record-self-write on-local-write abs)
|
||||
(%delete-local-path abs is-dir)
|
||||
(remhash rel j-map)
|
||||
(incf (sync-result-deleted-local result)))
|
||||
(error (e)
|
||||
(push (format nil "delete local ~a: ~a" rel e) (sync-result-errors result)))))))
|
||||
|
||||
;; 8. Delete remote files/dirs (bottom-up)
|
||||
(dolist (entry delete-remote)
|
||||
(destructuring-bind (rel is-dir) entry
|
||||
(declare (ignore is-dir))
|
||||
(incf done-ops)
|
||||
(%report-progress on-progress done-ops total-ops (format nil "× ~a" rel))
|
||||
(let ((full-remote (%remote-join remote-root rel)))
|
||||
(handler-case
|
||||
(progn
|
||||
(webdav-delete client full-remote)
|
||||
(setf mutated-remote t)
|
||||
(remhash rel j-map)
|
||||
(incf (sync-result-deleted-remote result)))
|
||||
(error (e)
|
||||
(push (format nil "delete remote ~a: ~a" rel e) (sync-result-errors result)))))))
|
||||
|
||||
;; 9. Refresh directory ETags & root ETag after remote mutations so future pruning stays exact
|
||||
(let ((had-errors (not (null (sync-result-errors result)))))
|
||||
(when (and mutated-remote (not had-errors))
|
||||
(handler-case
|
||||
(progn
|
||||
;; Refresh root ETag and directory ETags
|
||||
(let ((new-root (webdav-propfind client remote-root :depth 0)))
|
||||
(when new-root
|
||||
(setf scanned-root-etag (remote-item-etag new-root))))
|
||||
;; Update ETags for tracked directories
|
||||
(let ((dir-paths '()))
|
||||
(maphash (lambda (rel je)
|
||||
(when (entry-is-dir je) (push rel dir-paths)))
|
||||
j-map)
|
||||
(dolist (rel dir-paths)
|
||||
(let ((ritem (ignore-errors
|
||||
(webdav-propfind client (%remote-join remote-root rel) :depth 0))))
|
||||
(when ritem
|
||||
(setf (entry-remote-etag (gethash rel j-map))
|
||||
(remote-item-etag ritem)))))))
|
||||
(error () nil)))
|
||||
|
||||
(setf (journal-root-etag journal) scanned-root-etag
|
||||
(journal-last-full-sync-ok journal) (not had-errors)
|
||||
(journal-last-sync-time journal) (unix-now))
|
||||
(save-journal journal j-path)
|
||||
|
||||
(setf (sync-result-file-count result)
|
||||
(loop for je being the hash-values of j-map
|
||||
count (not (entry-is-dir je)))))
|
||||
|
||||
result)))))))
|
||||
|
||||
(defun sync-all-folders (cfg &key force-full-scan on-progress on-local-write)
|
||||
"Sync every configured folder in CFG. Returns a list of SYNC-RESULT structs."
|
||||
(let* ((srv (config-server cfg))
|
||||
(password (resolve-password cfg))
|
||||
(client (make-webdav-client
|
||||
:url (server-url srv)
|
||||
:username (server-username srv)
|
||||
:password password
|
||||
:verify-ssl (server-verify-ssl srv)
|
||||
:chunk-size-mb (sync-chunk-size-mb (config-sync cfg)))))
|
||||
(loop for folder in (config-folders cfg)
|
||||
collect (sync-folder client folder (config-sync cfg)
|
||||
:force-full-scan force-full-scan
|
||||
:on-progress on-progress
|
||||
:on-local-write on-local-write))))
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
(in-package #:nextcloud-niri)
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Waybar JSON Widget Renderer (matches olivtsi dwm-style text widgets)
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defparameter *wb-accent* "#7a806f")
|
||||
(defparameter *wb-green* "#b5bd68")
|
||||
(defparameter *wb-yellow* "#de9d5f")
|
||||
(defparameter *wb-red* "#cc7066")
|
||||
|
||||
(defun %pango-escape (str)
|
||||
(let ((s (or str "")))
|
||||
(setf s (cl-ppcre:regex-replace-all "&" s "&"))
|
||||
(setf s (cl-ppcre:regex-replace-all "<" s "<"))
|
||||
(setf s (cl-ppcre:regex-replace-all ">" s ">"))
|
||||
s))
|
||||
|
||||
(defun %format-age (unix-ts)
|
||||
(if (or (null unix-ts) (<= unix-ts 0))
|
||||
"never"
|
||||
(let ((delta (max 0 (- (unix-now) unix-ts))))
|
||||
(cond
|
||||
((< delta 5) "just now")
|
||||
((< delta 60) (format nil "~ds ago" delta))
|
||||
((< delta 3600) (format nil "~dm ago" (floor delta 60)))
|
||||
((< delta 86400) (format nil "~dh ago" (floor delta 3600)))
|
||||
(t (format nil "~dd ago" (floor delta 86400)))))))
|
||||
|
||||
(defun render-waybar-json (&optional cfg)
|
||||
"Build Waybar JSON string {text, tooltip, class} from runtime status.json."
|
||||
(let* ((conf (or cfg (ignore-errors (load-config)) (make-app-config)))
|
||||
(label (%pango-escape (waybar-label (config-waybar conf))))
|
||||
(status (read-status))
|
||||
(pid (when status (gethash "pid" status)))
|
||||
(alive (pid-alive-p pid))
|
||||
(raw-state (if (and status alive)
|
||||
(or (gethash "state" status) "off")
|
||||
"off"))
|
||||
(pending (if status (or (gethash "pending" status) 0) 0))
|
||||
(prog-done (if status (or (gethash "progress_done" status) 0) 0))
|
||||
(prog-total (if status (or (gethash "progress_total" status) 0) 0))
|
||||
(prog-detail (if status (or (gethash "progress_detail" status) "") ""))
|
||||
(last-sync (if status (or (gethash "last_sync" status) 0) 0))
|
||||
(err-msg (if status (or (gethash "error" status) "") ""))
|
||||
(folders (if status (gethash "folders" status) nil))
|
||||
(text "")
|
||||
(cls "")
|
||||
(tip-lines '()))
|
||||
|
||||
(cond
|
||||
((string= raw-state "synced")
|
||||
(setf text (format nil "~a" label)
|
||||
cls "synced")
|
||||
(push (format nil "Nextcloud: synced (~a)" (%format-age last-sync)) tip-lines))
|
||||
((string= raw-state "unsynced")
|
||||
(setf text (if (> pending 1)
|
||||
(format nil "~a <span color='~a'>*~d</span>" label *wb-yellow* pending)
|
||||
(format nil "~a <span color='~a'>*</span>" label *wb-yellow*))
|
||||
cls "unsynced")
|
||||
(push (format nil "Nextcloud: unsynced (~d pending change~:p)" (max 1 pending)) tip-lines))
|
||||
((string= raw-state "syncing")
|
||||
(setf text (if (> prog-total 0)
|
||||
(format nil "~a <span color='~a'>~d/~d</span>" label *wb-yellow* prog-done prog-total)
|
||||
(format nil "~a <span color='~a'>...</span>" label *wb-yellow*))
|
||||
cls "syncing")
|
||||
(push (if (> (length prog-detail) 0)
|
||||
(format nil "Nextcloud: syncing (~a)" prog-detail)
|
||||
"Nextcloud: syncing...")
|
||||
tip-lines))
|
||||
((string= raw-state "error")
|
||||
(setf text (format nil "~a <span color='~a'>!</span>" label *wb-red*)
|
||||
cls "error")
|
||||
(push "Nextcloud: problem syncing" tip-lines)
|
||||
(when (> (length err-msg) 0)
|
||||
(push (format nil "Error: ~a" err-msg) tip-lines)))
|
||||
((string= raw-state "paused")
|
||||
(setf text (format nil "~a <span color='~a'>paused</span>" label *wb-accent*)
|
||||
cls "paused")
|
||||
(push (format nil "Nextcloud: paused (last sync ~a)" (%format-age last-sync)) tip-lines))
|
||||
(t
|
||||
(setf text (format nil "~a <span color='~a'>off</span>" label *wb-accent*)
|
||||
cls "off")
|
||||
(push "Nextcloud: daemon not running" tip-lines)
|
||||
(push "Start with: systemctl --user start nextcloud-niri" tip-lines)))
|
||||
|
||||
(when (and status alive (vectorp folders) (> (length folders) 0))
|
||||
(push "" tip-lines)
|
||||
(loop for f across folders
|
||||
do (let ((name (gethash "name" f))
|
||||
(loc (gethash "local" f))
|
||||
(rem (gethash "remote" f))
|
||||
(files (gethash "files" f))
|
||||
(ferr (gethash "error" f))
|
||||
(confs (gethash "conflicts" f)))
|
||||
(push (format nil "~a: ~a <-> ~a (~d files)" name loc rem files) tip-lines)
|
||||
(when (and (stringp ferr) (> (length ferr) 0))
|
||||
(push (format nil " ! ~a" ferr) tip-lines))
|
||||
(when (and (vectorp confs) (> (length confs) 0))
|
||||
(push (format nil " conflicts: ~d" (length confs)) tip-lines)))))
|
||||
|
||||
(when alive
|
||||
(push "" tip-lines)
|
||||
(push "Left-click: sync now | Right-click: pause/resume" tip-lines))
|
||||
|
||||
(let ((out (make-hash-table :test #'equal)))
|
||||
(setf (gethash "text" out) text
|
||||
(gethash "tooltip" out) (format nil "~{~a~^~%~}" (nreverse tip-lines))
|
||||
(gethash "class" out) cls)
|
||||
(jzon:stringify out))))
|
||||
+531
@@ -0,0 +1,531 @@
|
||||
(in-package #:nextcloud-niri)
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Nextcloud WebDAV & Login Flow v2 Client
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(define-condition webdav-error (error)
|
||||
((status :initarg :status :initform nil :reader webdav-error-status)
|
||||
(message :initarg :message :initform "" :reader webdav-error-message))
|
||||
(:report (lambda (c s)
|
||||
(if (webdav-error-status c)
|
||||
(format s "WebDAV error (HTTP ~a): ~a"
|
||||
(webdav-error-status c) (webdav-error-message c))
|
||||
(format s "WebDAV error: ~a" (webdav-error-message c))))))
|
||||
|
||||
(define-condition webdav-auth-error (webdav-error) ())
|
||||
(define-condition webdav-not-found-error (webdav-error) ())
|
||||
|
||||
(defstruct (webdav-client (:constructor %make-webdav-client))
|
||||
(base-url "" :type string)
|
||||
(base-path "" :type string)
|
||||
(username "" :type string)
|
||||
(password "" :type string)
|
||||
(verify-ssl t :type boolean)
|
||||
(chunk-size-bytes (* 10 1024 1024) :type integer)
|
||||
(timeout 60 :type integer))
|
||||
|
||||
(defun make-webdav-client (&key url username password (verify-ssl t) (chunk-size-mb 10) (timeout 60))
|
||||
(let* ((clean-url (string-right-trim "/" url))
|
||||
(uri (quri:uri clean-url))
|
||||
(path (string-right-trim "/" (or (quri:uri-path uri) ""))))
|
||||
(%make-webdav-client
|
||||
:base-url clean-url
|
||||
:base-path path
|
||||
:username username
|
||||
:password password
|
||||
:verify-ssl verify-ssl
|
||||
:chunk-size-bytes (* (max 1 chunk-size-mb) 1024 1024)
|
||||
:timeout timeout)))
|
||||
|
||||
(defstruct (remote-item (:conc-name remote-item-))
|
||||
(rel-path "" :type string)
|
||||
(is-dir nil :type boolean)
|
||||
(etag "" :type string)
|
||||
(size 0 :type integer)
|
||||
(mtime 0 :type integer)
|
||||
(file-id "" :type string)
|
||||
(checksum nil))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; URL & Header Helpers
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defparameter *user-agent* "nextcloud-niri/0.1.0")
|
||||
|
||||
(defun %encode-dav-path (rel-path)
|
||||
"Percent-encode each segment of REL-PATH, preserving slashes."
|
||||
(let ((trimmed (string-trim "/" rel-path)))
|
||||
(if (zerop (length trimmed))
|
||||
""
|
||||
(format nil "~{~a~^/~}"
|
||||
(mapcar (lambda (seg) (quri:url-encode seg))
|
||||
(uiop:split-string trimmed :separator "/"))))))
|
||||
|
||||
(defun %dav-files-prefix-path (client)
|
||||
(format nil "~a/remote.php/dav/files/~a"
|
||||
(webdav-client-base-path client)
|
||||
(quri:url-encode (webdav-client-username client))))
|
||||
|
||||
(defun %dav-file-url (client remote-path)
|
||||
(let ((encoded (%encode-dav-path remote-path)))
|
||||
(if (zerop (length encoded))
|
||||
(format nil "~a/remote.php/dav/files/~a/"
|
||||
(webdav-client-base-url client)
|
||||
(quri:url-encode (webdav-client-username client)))
|
||||
(format nil "~a/remote.php/dav/files/~a/~a"
|
||||
(webdav-client-base-url client)
|
||||
(quri:url-encode (webdav-client-username client))
|
||||
encoded))))
|
||||
|
||||
(defun %dav-upload-url (client upload-id &optional part)
|
||||
(if part
|
||||
(format nil "~a/remote.php/dav/uploads/~a/~a/~a"
|
||||
(webdav-client-base-url client)
|
||||
(quri:url-encode (webdav-client-username client))
|
||||
(quri:url-encode upload-id)
|
||||
(quri:url-encode part))
|
||||
(format nil "~a/remote.php/dav/uploads/~a/~a"
|
||||
(webdav-client-base-url client)
|
||||
(quri:url-encode (webdav-client-username client))
|
||||
(quri:url-encode upload-id))))
|
||||
|
||||
(defun %normalize-etag (raw)
|
||||
(if (not (stringp raw))
|
||||
""
|
||||
(let ((s (string-trim '(#\Space #\Tab #\Newline #\Return) raw)))
|
||||
(when (and (>= (length s) 2) (string-equal (subseq s 0 2) "W/"))
|
||||
(setf s (subseq s 2)))
|
||||
(string-trim '(#\" #\') s))))
|
||||
|
||||
(defun %get-header (headers name)
|
||||
(when (hash-table-p headers)
|
||||
(or (gethash (string-downcase name) headers)
|
||||
(gethash name headers))))
|
||||
|
||||
(defun %auth-headers (client &optional extra)
|
||||
(let* ((cred (format nil "~a:~a" (webdav-client-username client) (webdav-client-password client)))
|
||||
(b64 (cl-base64:string-to-base64-string cred))
|
||||
(base (list (cons "Authorization" (format nil "Basic ~a" b64))
|
||||
(cons "User-Agent" *user-agent*))))
|
||||
(append base extra)))
|
||||
|
||||
(defun %dex-request (client method url &key headers content want-stream force-binary (retries 2))
|
||||
"Execute an HTTP/WebDAV request with retry on transient network/5xx errors."
|
||||
(ensure-ssl-libraries)
|
||||
(loop for attempt from 0 to retries
|
||||
do (handler-case
|
||||
(return
|
||||
(dex:request url
|
||||
:method method
|
||||
:headers (%auth-headers client headers)
|
||||
:content content
|
||||
:want-stream want-stream
|
||||
:force-binary force-binary
|
||||
:insecure (not (webdav-client-verify-ssl client))
|
||||
:connect-timeout 15
|
||||
:read-timeout (webdav-client-timeout client)
|
||||
:keep-alive nil
|
||||
:use-connection-pool nil))
|
||||
(dex:http-request-failed (e)
|
||||
(let ((status (dex:response-status e)))
|
||||
(cond
|
||||
((member status '(401 403))
|
||||
(error 'webdav-auth-error
|
||||
:status status
|
||||
:message (format nil "Authentication failed for ~a" url)))
|
||||
((eql status 404)
|
||||
(error 'webdav-not-found-error
|
||||
:status status
|
||||
:message (format nil "Not found: ~a" url)))
|
||||
((and (integerp status) (>= status 500) (< attempt retries))
|
||||
(sleep (+ 0.5 (* attempt 1.0))))
|
||||
(t
|
||||
(error 'webdav-error
|
||||
:status status
|
||||
:message (format nil "~a ~a failed (HTTP ~a)" method url status))))))
|
||||
(error (e)
|
||||
(if (< attempt retries)
|
||||
(sleep (+ 0.5 (* attempt 1.0)))
|
||||
(error 'webdav-error
|
||||
:message (format nil "~a ~a failed: ~a" method url e)))))))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; HTTP Date (RFC 7231 / RFC 1123) -> Unix Epoch Seconds
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defparameter *http-months*
|
||||
'(("jan" . 1) ("feb" . 2) ("mar" . 3) ("apr" . 4)
|
||||
("may" . 5) ("jun" . 6) ("jul" . 7) ("aug" . 8)
|
||||
("sep" . 9) ("oct" . 10) ("nov" . 11) ("dec" . 12)))
|
||||
|
||||
(defun parse-http-date (date-str)
|
||||
"Parse an HTTP-date (e.g. 'Mon, 23 Nov 2026 01:05:00 GMT') to Unix epoch seconds."
|
||||
(when (and (stringp date-str) (> (length date-str) 0))
|
||||
(or (cl-ppcre:register-groups-bind (day mon year hour min sec)
|
||||
("(\\d{1,2})\\s+([A-Za-z]{3})\\s+(\\d{4})\\s+(\\d{2}):(\\d{2}):(\\d{2})" date-str)
|
||||
(let ((month-num (cdr (assoc (string-downcase mon) *http-months* :test #'string=))))
|
||||
(when month-num
|
||||
(- (encode-universal-time
|
||||
(parse-integer sec)
|
||||
(parse-integer min)
|
||||
(parse-integer hour)
|
||||
(parse-integer day)
|
||||
month-num
|
||||
(parse-integer year)
|
||||
0)
|
||||
2208988800))))
|
||||
(ignore-errors
|
||||
(local-time:timestamp-to-unix (local-time:parse-timestring date-str)))
|
||||
0)))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; PROPFIND XML Parsing (namespace-prefix agnostic)
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defparameter *propfind-body*
|
||||
"<?xml version=\"1.0\" encoding=\"utf-8\"?>
|
||||
<d:propfind xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\" xmlns:nc=\"http://nextcloud.org/ns\">
|
||||
<d:prop>
|
||||
<d:getlastmodified/>
|
||||
<d:getcontentlength/>
|
||||
<d:getetag/>
|
||||
<d:resourcetype/>
|
||||
<oc:id/>
|
||||
<oc:size/>
|
||||
<oc:checksums/>
|
||||
</d:prop>
|
||||
</d:propfind>")
|
||||
|
||||
(defun %xml-local-name (node)
|
||||
(when (plump:element-p node)
|
||||
(let* ((tag (plump:tag-name node))
|
||||
(colon (position #\: tag)))
|
||||
(string-downcase (if colon (subseq tag (1+ colon)) tag)))))
|
||||
|
||||
(defun %xml-children-by-name (node local-name)
|
||||
(let ((res '()))
|
||||
(when (plump:nesting-node-p node)
|
||||
(loop for child across (plump:children node)
|
||||
when (and (plump:element-p child)
|
||||
(string= (%xml-local-name child) local-name))
|
||||
do (push child res)))
|
||||
(nreverse res)))
|
||||
|
||||
(defun %xml-first-child (node local-name)
|
||||
(first (%xml-children-by-name node local-name)))
|
||||
|
||||
(defun %xml-text (node)
|
||||
(if node
|
||||
(string-trim '(#\Space #\Tab #\Newline #\Return) (plump:text node))
|
||||
""))
|
||||
|
||||
(defun %href-to-remote-path (client href)
|
||||
"Convert a WebDAV response <d:href> into a decoded remote path relative to the user's DAV files root."
|
||||
(let* ((raw-path (if (or (alex:starts-with-subseq "http://" href)
|
||||
(alex:starts-with-subseq "https://" href))
|
||||
(or (quri:uri-path (quri:uri href)) "")
|
||||
href))
|
||||
(decoded (quri:url-decode raw-path :lenient t))
|
||||
(prefix (quri:url-decode (%dav-files-prefix-path client) :lenient t)))
|
||||
(let ((stripped
|
||||
(cond
|
||||
((alex:starts-with-subseq prefix decoded)
|
||||
(subseq decoded (length prefix)))
|
||||
(t decoded))))
|
||||
(string-trim "/" stripped))))
|
||||
|
||||
(defun %strip-base-remote (full-remote base-remote)
|
||||
(let ((full (string-trim "/" full-remote))
|
||||
(base (string-trim "/" base-remote)))
|
||||
(cond
|
||||
((zerop (length base)) full)
|
||||
((string= full base) "")
|
||||
((and (> (length full) (length base))
|
||||
(string= full base :end1 (length base))
|
||||
(char= (char full (length base)) #\/))
|
||||
(subseq full (1+ (length base))))
|
||||
(t full))))
|
||||
|
||||
(defun %parse-propfind-xml (client xml-string base-remote-path)
|
||||
"Parse a WebDAV 207 Multi-Status XML response into a list of REMOTE-ITEM structs."
|
||||
(let ((doc (plump:parse xml-string))
|
||||
(items '()))
|
||||
(labels ((walk (node)
|
||||
(when (plump:nesting-node-p node)
|
||||
(loop for child across (plump:children node)
|
||||
do (cond
|
||||
((and (plump:element-p child)
|
||||
(string= (%xml-local-name child) "response"))
|
||||
(let ((item (%parse-response-node client child base-remote-path)))
|
||||
(when item (push item items))))
|
||||
(t (walk child)))))))
|
||||
(walk doc))
|
||||
(nreverse items)))
|
||||
|
||||
(defun %parse-response-node (client resp-node base-remote-path)
|
||||
(let* ((href-node (%xml-first-child resp-node "href"))
|
||||
(href (%xml-text href-node)))
|
||||
(when (zerop (length href))
|
||||
(return-from %parse-response-node nil))
|
||||
(let ((ok-prop nil))
|
||||
(dolist (ps (%xml-children-by-name resp-node "propstat"))
|
||||
(let ((st (%xml-text (%xml-first-child ps "status"))))
|
||||
(when (or (zerop (length st)) (search " 200 " st))
|
||||
(setf ok-prop (%xml-first-child ps "prop"))
|
||||
(return))))
|
||||
(unless ok-prop
|
||||
(return-from %parse-response-node nil))
|
||||
(let* ((res-type (%xml-first-child ok-prop "resourcetype"))
|
||||
(is-dir (not (null (and res-type (%xml-first-child res-type "collection")))))
|
||||
(etag (%normalize-etag (%xml-text (%xml-first-child ok-prop "getetag"))))
|
||||
(len-str (%xml-text (%xml-first-child ok-prop "getcontentlength")))
|
||||
(size (or (ignore-errors (parse-integer len-str)) 0))
|
||||
(mtime-str (%xml-text (%xml-first-child ok-prop "getlastmodified")))
|
||||
(mtime (or (parse-http-date mtime-str) 0))
|
||||
(file-id (%xml-text (%xml-first-child ok-prop "id")))
|
||||
(checksums-node (%xml-first-child ok-prop "checksums"))
|
||||
(checksum-node (when checksums-node (%xml-first-child checksums-node "checksum")))
|
||||
(checksum (let ((c (%xml-text checksum-node)))
|
||||
(if (> (length c) 0) c nil)))
|
||||
(full-remote (%href-to-remote-path client href))
|
||||
(rel (%strip-base-remote full-remote base-remote-path)))
|
||||
(make-remote-item
|
||||
:rel-path rel
|
||||
:is-dir is-dir
|
||||
:etag etag
|
||||
:size size
|
||||
:mtime mtime
|
||||
:file-id file-id
|
||||
:checksum checksum)))))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; WebDAV Operations
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun webdav-propfind (client remote-path &key (depth 1) (base-remote-path remote-path))
|
||||
"Perform PROPFIND on REMOTE-PATH with DEPTH (0 or 1).
|
||||
Returns (values self-item children-items)."
|
||||
(let ((url (%dav-file-url client remote-path)))
|
||||
(multiple-value-bind (body status)
|
||||
(%dex-request client :propfind url
|
||||
:headers (list (cons "Depth" (format nil "~a" depth))
|
||||
(cons "Content-Type" "application/xml; charset=utf-8"))
|
||||
:content *propfind-body*)
|
||||
(declare (ignore status))
|
||||
(let* ((xml-str (if (stringp body)
|
||||
body
|
||||
(babel:octets-to-string body :encoding :utf-8)))
|
||||
(all (%parse-propfind-xml client xml-str base-remote-path))
|
||||
(target-rel (%strip-base-remote remote-path base-remote-path))
|
||||
(self nil)
|
||||
(children '()))
|
||||
(dolist (it all)
|
||||
(if (string= (remote-item-rel-path it) target-rel)
|
||||
(setf self it)
|
||||
(push it children)))
|
||||
(values self (nreverse children))))))
|
||||
|
||||
(defun webdav-mkcol (client remote-path)
|
||||
"Create remote directory REMOTE-PATH. Succeeds silently if it already exists (405)."
|
||||
(let ((url (%dav-file-url client remote-path)))
|
||||
(handler-case
|
||||
(progn
|
||||
(%dex-request client :mkcol url :retries 1)
|
||||
t)
|
||||
(webdav-error (e)
|
||||
(if (eql (webdav-error-status e) 405)
|
||||
t
|
||||
(error e))))))
|
||||
|
||||
(defun webdav-ensure-dir (client remote-path)
|
||||
"Recursively ensure remote directory REMOTE-PATH exists."
|
||||
(let ((segments (remove-if (lambda (s) (zerop (length s)))
|
||||
(uiop:split-string (string-trim "/" remote-path) :separator "/")))
|
||||
(cur ""))
|
||||
(dolist (seg segments t)
|
||||
(setf cur (if (zerop (length cur)) seg (format nil "~a/~a" cur seg)))
|
||||
(handler-case
|
||||
(webdav-propfind client cur :depth 0)
|
||||
(webdav-not-found-error ()
|
||||
(webdav-mkcol client cur))))))
|
||||
|
||||
(defun webdav-download-file (client remote-path local-dest-path &key remote-mtime)
|
||||
"Stream-download REMOTE-PATH to LOCAL-DEST-PATH atomically and set mtime.
|
||||
Returns (values sha256-hex bytes-written etag)."
|
||||
(let* ((url (%dav-file-url client remote-path))
|
||||
(slash (position #\/ local-dest-path :from-end t))
|
||||
(dir (if slash (subseq local-dest-path 0 slash) "."))
|
||||
(fname (if slash (subseq local-dest-path (1+ slash)) local-dest-path))
|
||||
(tmp-path (format nil "~a/.nextcloud-niri.tmp.~d.~a" dir (sb-posix:getpid) fname)))
|
||||
(ensure-directory dir)
|
||||
(multiple-value-bind (stream status headers)
|
||||
(%dex-request client :get url :want-stream t :force-binary t)
|
||||
(declare (ignore status))
|
||||
(let ((digester (ironclad:make-digest :sha256))
|
||||
(buf (make-array 65536 :element-type '(unsigned-byte 8)))
|
||||
(total 0)
|
||||
(etag (%normalize-etag (or (%get-header headers "etag")
|
||||
(%get-header headers "oc-etag")))))
|
||||
(unwind-protect
|
||||
(progn
|
||||
(with-open-file (out (uiop:parse-native-namestring tmp-path)
|
||||
:direction :output
|
||||
:element-type '(unsigned-byte 8)
|
||||
:if-exists :supersede
|
||||
:if-does-not-exist :create)
|
||||
(loop for n = (read-sequence buf stream)
|
||||
while (> n 0)
|
||||
do (write-sequence buf out :end n)
|
||||
(ironclad:update-digest digester buf :start 0 :end n)
|
||||
(incf total n)))
|
||||
(let ((mtime (or remote-mtime
|
||||
(parse-http-date (%get-header headers "last-modified")))))
|
||||
(when (and mtime (> mtime 0))
|
||||
(ignore-errors (sb-posix:utime tmp-path mtime mtime))))
|
||||
(sb-posix:rename tmp-path local-dest-path)
|
||||
(values (ironclad:byte-array-to-hex-string (ironclad:produce-digest digester))
|
||||
total
|
||||
etag))
|
||||
(ignore-errors (close stream))
|
||||
(when (probe-file (uiop:parse-native-namestring tmp-path))
|
||||
(ignore-errors (sb-posix:unlink tmp-path))))))))
|
||||
|
||||
(defun %read-file-bytes (path-str)
|
||||
(with-open-file (in (uiop:parse-native-namestring path-str)
|
||||
:direction :input
|
||||
:element-type '(unsigned-byte 8))
|
||||
(let* ((len (file-length in))
|
||||
(buf (make-array len :element-type '(unsigned-byte 8))))
|
||||
(read-sequence buf in)
|
||||
buf)))
|
||||
|
||||
(defun %upload-chunked-v2 (client local-path remote-path file-size mtime)
|
||||
"Upload large file using Nextcloud Chunked Upload v2."
|
||||
(let* ((upload-id (format nil "ncniri-~d-~d" (sb-posix:getpid) (get-internal-real-time)))
|
||||
(upload-dir-url (%dav-upload-url client upload-id))
|
||||
(dest-url (%dav-file-url client remote-path))
|
||||
(chunk-size (webdav-client-chunk-size-bytes client))
|
||||
(completed nil))
|
||||
(%dex-request client :mkcol upload-dir-url :retries 1)
|
||||
(unwind-protect
|
||||
(progn
|
||||
(with-open-file (in (uiop:parse-native-namestring local-path)
|
||||
:direction :input
|
||||
:element-type '(unsigned-byte 8))
|
||||
(let ((chunk-idx 1)
|
||||
(remaining file-size))
|
||||
(loop while (> remaining 0)
|
||||
do (let* ((to-read (min chunk-size remaining))
|
||||
(buf (make-array to-read :element-type '(unsigned-byte 8)))
|
||||
(n (read-sequence buf in)))
|
||||
(when (zerop n) (return))
|
||||
(let ((payload (if (= n to-read) buf (subseq buf 0 n)))
|
||||
(part-name (format nil "~10,'0d" chunk-idx)))
|
||||
(%dex-request client :put (%dav-upload-url client upload-id part-name)
|
||||
:headers (list (cons "Content-Type" "application/octet-stream"))
|
||||
:content payload))
|
||||
(decf remaining n)
|
||||
(incf chunk-idx)))))
|
||||
(let ((move-headers (list (cons "Destination" dest-url)
|
||||
(cons "Overwrite" "T")
|
||||
(cons "OC-Total-Length" (format nil "~d" file-size)))))
|
||||
(when (and mtime (> mtime 0))
|
||||
(push (cons "X-OC-Mtime" (format nil "~d" mtime)) move-headers))
|
||||
(multiple-value-bind (body status headers)
|
||||
(%dex-request client :move (%dav-upload-url client upload-id ".file")
|
||||
:headers move-headers
|
||||
:retries 1)
|
||||
(declare (ignore body status))
|
||||
(setf completed t)
|
||||
(%normalize-etag (or (%get-header headers "oc-etag")
|
||||
(%get-header headers "etag"))))))
|
||||
(unless completed
|
||||
(ignore-errors (%dex-request client :delete upload-dir-url :retries 0))))))
|
||||
|
||||
(defun webdav-upload-file (client local-path remote-path &key mtime)
|
||||
"Upload LOCAL-PATH to REMOTE-PATH, preserving X-OC-Mtime and using Chunked Upload v2 for large files.
|
||||
Returns (values etag file-id)."
|
||||
(let* ((st (sb-posix:stat local-path))
|
||||
(file-size (sb-posix:stat-size st))
|
||||
(file-mtime (or mtime (sb-posix:stat-mtime st)))
|
||||
(etag ""))
|
||||
(if (> file-size (webdav-client-chunk-size-bytes client))
|
||||
(setf etag (%upload-chunked-v2 client local-path remote-path file-size file-mtime))
|
||||
(let* ((url (%dav-file-url client remote-path))
|
||||
(bytes (%read-file-bytes local-path))
|
||||
(headers (list (cons "Content-Type" "application/octet-stream"))))
|
||||
(when (> file-mtime 0)
|
||||
(push (cons "X-OC-Mtime" (format nil "~d" file-mtime)) headers))
|
||||
(multiple-value-bind (body status resp-headers)
|
||||
(%dex-request client :put url :headers headers :content bytes)
|
||||
(declare (ignore body status))
|
||||
(setf etag (%normalize-etag (or (%get-header resp-headers "oc-etag")
|
||||
(%get-header resp-headers "etag")))))))
|
||||
;; Fetch authoritative metadata (etag + oc:id) if ETag was not returned directly
|
||||
(if (> (length etag) 0)
|
||||
(values etag "")
|
||||
(handler-case
|
||||
(let ((item (webdav-propfind client remote-path :depth 0)))
|
||||
(if item
|
||||
(values (remote-item-etag item) (remote-item-file-id item))
|
||||
(values "" "")))
|
||||
(error () (values "" ""))))))
|
||||
|
||||
(defun webdav-delete (client remote-path)
|
||||
"Delete remote file or directory REMOTE-PATH. Succeeds silently if already absent (404)."
|
||||
(let ((url (%dav-file-url client remote-path)))
|
||||
(handler-case
|
||||
(progn
|
||||
(%dex-request client :delete url :retries 1)
|
||||
t)
|
||||
(webdav-not-found-error ()
|
||||
t))))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Nextcloud Login Flow v2 (Browser Auth -> Dedicated App Password)
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun nextcloud-login-flow-start (server-url &key (verify-ssl t))
|
||||
"Initiate Nextcloud Login Flow v2.
|
||||
Returns (values login-url poll-endpoint poll-token)."
|
||||
(ensure-ssl-libraries)
|
||||
(let ((endpoint (format nil "~a/index.php/login/v2" (string-right-trim "/" server-url))))
|
||||
(multiple-value-bind (body status)
|
||||
(dex:post endpoint
|
||||
:headers (list (cons "User-Agent" *user-agent*))
|
||||
:insecure (not verify-ssl)
|
||||
:connect-timeout 15
|
||||
:read-timeout 30)
|
||||
(declare (ignore status))
|
||||
(let* ((json-str (if (stringp body) body (babel:octets-to-string body :encoding :utf-8)))
|
||||
(obj (jzon:parse json-str))
|
||||
(poll (gethash "poll" obj)))
|
||||
(values (gethash "login" obj)
|
||||
(gethash "endpoint" poll)
|
||||
(gethash "token" poll))))))
|
||||
|
||||
(defun nextcloud-login-flow-poll (poll-endpoint poll-token &key (verify-ssl t))
|
||||
"Poll Login Flow v2 once. Returns NIL while waiting (HTTP 404), or
|
||||
(values server login-name app-password) when authorized."
|
||||
(ensure-ssl-libraries)
|
||||
(handler-case
|
||||
(multiple-value-bind (body status)
|
||||
(dex:post poll-endpoint
|
||||
:headers (list (cons "User-Agent" *user-agent*))
|
||||
:content (list (cons "token" poll-token))
|
||||
:insecure (not verify-ssl)
|
||||
:connect-timeout 15
|
||||
:read-timeout 30)
|
||||
(declare (ignore status))
|
||||
(let* ((json-str (if (stringp body) body (babel:octets-to-string body :encoding :utf-8)))
|
||||
(obj (jzon:parse json-str)))
|
||||
(values (gethash "server" obj)
|
||||
(gethash "loginName" obj)
|
||||
(gethash "appPassword" obj))))
|
||||
(dex:http-request-failed (e)
|
||||
(if (eql (dex:response-status e) 404)
|
||||
nil
|
||||
(error 'webdav-error
|
||||
:status (dex:response-status e)
|
||||
:message (format nil "Login poll failed (HTTP ~a)" (dex:response-status e)))))))
|
||||
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=Nextcloud headless sync daemon for niri/waybar
|
||||
After=network-online.target graphical-session.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=%h/.local/bin/nextcloud-niri daemon
|
||||
ExecReload=/bin/kill -HUP $MAINPID
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=niri.service
|
||||
@@ -0,0 +1,419 @@
|
||||
(in-package #:nextcloud-niri.tests)
|
||||
|
||||
(eval-when (:compile-toplevel :load-toplevel :execute)
|
||||
(require :sb-bsd-sockets))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; In-process Mock Nextcloud WebDAV + Login Flow v2 Server (pure sb-bsd-sockets)
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defstruct mock-node
|
||||
(is-dir nil :type boolean)
|
||||
(data (make-array 0 :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (*)))
|
||||
(mtime 0 :type integer)
|
||||
(etag "" :type string)
|
||||
(id "" :type string))
|
||||
|
||||
(defstruct mock-server
|
||||
(socket nil)
|
||||
(port 0 :type integer)
|
||||
(running nil :type boolean)
|
||||
(thread nil)
|
||||
(lock (bt:make-lock "mock-nc"))
|
||||
(username "alice" :type string)
|
||||
(password "secret-app-pw" :type string)
|
||||
(nodes (make-hash-table :test #'equal))
|
||||
(uploads (make-hash-table :test #'equal))
|
||||
(etag-seq 1 :type integer)
|
||||
(propfind-count 0 :type integer)
|
||||
(force-error-status nil)
|
||||
(login-poll-count 0 :type integer))
|
||||
|
||||
(defun mock-nodes (s) (mock-server-nodes s))
|
||||
(defun mock-propfind-count (s) (mock-server-propfind-count s))
|
||||
(defun (setf mock-propfind-count) (v s) (setf (mock-server-propfind-count s) v))
|
||||
(defun mock-force-error-status (s) (mock-server-force-error-status s))
|
||||
(defun (setf mock-force-error-status) (v s) (setf (mock-server-force-error-status s) v))
|
||||
|
||||
(defun %next-etag (server)
|
||||
(format nil "etag-~d" (incf (mock-server-etag-seq server))))
|
||||
|
||||
(defun %format-http-date (unix-ts)
|
||||
(multiple-value-bind (sec min hr day mon yr dow)
|
||||
(decode-universal-time (+ unix-ts 2208988800) 0)
|
||||
(let ((days #("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun"))
|
||||
(mons #("" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec")))
|
||||
(format nil "~a, ~2,'0d ~a ~4,'0d ~2,'0d:~2,'0d:~2,'0d GMT"
|
||||
(aref days dow) day (aref mons mon) yr hr min sec))))
|
||||
|
||||
(defun %touch-ancestors (server path)
|
||||
"Propagate ETag updates up to all parent directories (matching Nextcloud behavior)."
|
||||
(let ((nodes (mock-server-nodes server)))
|
||||
(setf (mock-node-etag (gethash "" nodes)) (%next-etag server))
|
||||
(let ((parts (remove-if (lambda (s) (zerop (length s)))
|
||||
(uiop:split-string (string-trim "/" path) :separator "/")))
|
||||
(cur ""))
|
||||
(dolist (p (butlast parts))
|
||||
(setf cur (if (zerop (length cur)) p (format nil "~a/~a" cur p)))
|
||||
(let ((n (gethash cur nodes)))
|
||||
(when n
|
||||
(setf (mock-node-etag n) (%next-etag server))))))))
|
||||
|
||||
(defun mock-put-dir (server rel-path)
|
||||
(bt:with-lock-held ((mock-server-lock server))
|
||||
(let* ((clean (string-trim "/" rel-path))
|
||||
(nodes (mock-server-nodes server)))
|
||||
(unless (gethash clean nodes)
|
||||
(setf (gethash clean nodes)
|
||||
(make-mock-node :is-dir t
|
||||
:mtime (- (get-universal-time) 2208988800)
|
||||
:etag (%next-etag server)
|
||||
:id (format nil "id-~d" (mock-server-etag-seq server))))
|
||||
(%touch-ancestors server clean)))))
|
||||
|
||||
(defun mock-put-file (server rel-path content &key mtime)
|
||||
(bt:with-lock-held ((mock-server-lock server))
|
||||
(let* ((clean (string-trim "/" rel-path))
|
||||
(bytes (if (stringp content)
|
||||
(babel:string-to-octets content :encoding :utf-8)
|
||||
(coerce content '(simple-array (unsigned-byte 8) (*)))))
|
||||
(ts (or mtime (- (get-universal-time) 2208988800)))
|
||||
(etag (%next-etag server))
|
||||
(nodes (mock-server-nodes server)))
|
||||
(let ((parts (uiop:split-string clean :separator "/"))
|
||||
(cur ""))
|
||||
(dolist (p (butlast parts))
|
||||
(setf cur (if (zerop (length cur)) p (format nil "~a/~a" cur p)))
|
||||
(unless (gethash cur nodes)
|
||||
(setf (gethash cur nodes)
|
||||
(make-mock-node :is-dir t :mtime ts :etag (%next-etag server)
|
||||
:id (format nil "id-~d" (mock-server-etag-seq server)))))))
|
||||
(setf (gethash clean nodes)
|
||||
(make-mock-node :is-dir nil :data bytes :mtime ts :etag etag
|
||||
:id (format nil "id-~d" (mock-server-etag-seq server))))
|
||||
(%touch-ancestors server clean)
|
||||
etag)))
|
||||
|
||||
(defun mock-delete-node (server rel-path)
|
||||
(bt:with-lock-held ((mock-server-lock server))
|
||||
(let* ((clean (string-trim "/" rel-path))
|
||||
(nodes (mock-server-nodes server))
|
||||
(prefix (concatenate 'string clean "/"))
|
||||
(to-del '()))
|
||||
(maphash (lambda (k v)
|
||||
(declare (ignore v))
|
||||
(when (or (string= k clean)
|
||||
(alex:starts-with-subseq prefix k))
|
||||
(push k to-del)))
|
||||
nodes)
|
||||
(dolist (k to-del)
|
||||
(remhash k nodes))
|
||||
(%touch-ancestors server clean))))
|
||||
|
||||
(defun mock-get-file-string (server rel-path)
|
||||
(bt:with-lock-held ((mock-server-lock server))
|
||||
(let ((n (gethash (string-trim "/" rel-path) (mock-server-nodes server))))
|
||||
(when (and n (not (mock-node-is-dir n)))
|
||||
(babel:octets-to-string (mock-node-data n) :encoding :utf-8)))))
|
||||
|
||||
(defun mock-node-exists-p (server rel-path)
|
||||
(bt:with-lock-held ((mock-server-lock server))
|
||||
(not (null (gethash (string-trim "/" rel-path) (mock-server-nodes server))))))
|
||||
|
||||
(defun %xml-escape (s)
|
||||
(let ((r s))
|
||||
(setf r (cl-ppcre:regex-replace-all "&" r "&"))
|
||||
(setf r (cl-ppcre:regex-replace-all "<" r "<"))
|
||||
(setf r (cl-ppcre:regex-replace-all ">" r ">"))
|
||||
r))
|
||||
|
||||
(defun %encode-href-path (user rel-path is-dir)
|
||||
(let* ((clean (string-trim "/" rel-path))
|
||||
(enc (if (zerop (length clean))
|
||||
""
|
||||
(format nil "~{~a~^/~}"
|
||||
(mapcar #'quri:url-encode
|
||||
(uiop:split-string clean :separator "/"))))))
|
||||
(format nil "/remote.php/dav/files/~a/~a~a"
|
||||
(quri:url-encode user)
|
||||
enc
|
||||
(if (and is-dir (> (length enc) 0)) "/" ""))))
|
||||
|
||||
(defun %render-propfind-response (server target-rel depth)
|
||||
(let ((nodes (mock-server-nodes server))
|
||||
(user (mock-server-username server))
|
||||
(entries '()))
|
||||
(let ((self (gethash target-rel nodes)))
|
||||
(unless self
|
||||
(return-from %render-propfind-response nil))
|
||||
(push (cons target-rel self) entries)
|
||||
(when (and (mock-node-is-dir self) (not (string= depth "0")))
|
||||
(let ((prefix (if (zerop (length target-rel))
|
||||
""
|
||||
(concatenate 'string target-rel "/"))))
|
||||
(maphash (lambda (k v)
|
||||
(when (and (> (length k) (length prefix))
|
||||
(string= k prefix :end1 (length prefix)))
|
||||
(let ((rest (subseq k (length prefix))))
|
||||
(unless (position #\/ rest)
|
||||
(push (cons k v) entries)))))
|
||||
nodes))))
|
||||
(with-output-to-string (out)
|
||||
(format out "<?xml version=\"1.0\" encoding=\"utf-8\"?>~%")
|
||||
(format out "<d:multistatus xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\">~%")
|
||||
(dolist (pair (nreverse entries))
|
||||
(destructuring-bind (rel . node) pair
|
||||
(format out " <d:response>~%")
|
||||
(format out " <d:href>~a</d:href>~%" (%xml-escape (%encode-href-path user rel (mock-node-is-dir node))))
|
||||
(format out " <d:propstat>~%")
|
||||
(format out " <d:prop>~%")
|
||||
(format out " <d:getetag>\"~a\"</d:getetag>~%" (mock-node-etag node))
|
||||
(format out " <d:getlastmodified>~a</d:getlastmodified>~%" (%format-http-date (mock-node-mtime node)))
|
||||
(format out " <oc:id>~a</oc:id>~%" (mock-node-id node))
|
||||
(if (mock-node-is-dir node)
|
||||
(format out " <d:resourcetype><d:collection/></d:resourcetype>~%")
|
||||
(progn
|
||||
(format out " <d:resourcetype/>~%")
|
||||
(format out " <d:getcontentlength>~d</d:getcontentlength>~%" (length (mock-node-data node)))))
|
||||
(format out " </d:prop>~%")
|
||||
(format out " <d:status>HTTP/1.1 200 OK</d:status>~%")
|
||||
(format out " </d:propstat>~%")
|
||||
(format out " </d:response>~%")))
|
||||
(format out "</d:multistatus>~%"))))
|
||||
|
||||
(defun %read-crlf-line (stream)
|
||||
(let ((bytes (make-array 64 :element-type '(unsigned-byte 8) :adjustable t :fill-pointer 0)))
|
||||
(loop for b = (read-byte stream nil nil)
|
||||
while b
|
||||
do (cond
|
||||
((= b 10) (return))
|
||||
((= b 13) nil)
|
||||
(t (vector-push-extend b bytes)))
|
||||
finally (when (zerop (length bytes))
|
||||
(return-from %read-crlf-line nil)))
|
||||
(babel:octets-to-string bytes :encoding :iso-8859-1)))
|
||||
|
||||
(defun %read-exact-bytes (stream n)
|
||||
(let ((buf (make-array n :element-type '(unsigned-byte 8)))
|
||||
(pos 0))
|
||||
(loop while (< pos n)
|
||||
for got = (read-sequence buf stream :start pos)
|
||||
when (= got pos) do (return)
|
||||
do (setf pos got))
|
||||
(if (= pos n) buf (subseq buf 0 pos))))
|
||||
|
||||
(defun %status-text (code)
|
||||
(case code
|
||||
(200 "OK")
|
||||
(201 "Created")
|
||||
(204 "No Content")
|
||||
(207 "Multi-Status")
|
||||
(401 "Unauthorized")
|
||||
(404 "Not Found")
|
||||
(405 "Method Not Allowed")
|
||||
(500 "Internal Server Error")
|
||||
(t "Status")))
|
||||
|
||||
(defun %write-http-response (stream status headers body)
|
||||
(let* ((body-bytes (cond
|
||||
((null body) (make-array 0 :element-type '(unsigned-byte 8)))
|
||||
((stringp body) (babel:string-to-octets body :encoding :utf-8))
|
||||
(t body)))
|
||||
(head-str
|
||||
(with-output-to-string (out)
|
||||
(format out "HTTP/1.1 ~d ~a~c~c" status (%status-text status) #\Return #\Newline)
|
||||
(dolist (kv headers)
|
||||
(format out "~a: ~a~c~c" (car kv) (cdr kv) #\Return #\Newline))
|
||||
(format out "Content-Length: ~d~c~c" (length body-bytes) #\Return #\Newline)
|
||||
(format out "Connection: close~c~c~c~c" #\Return #\Newline #\Return #\Newline))))
|
||||
(write-sequence (babel:string-to-octets head-str :encoding :iso-8859-1) stream)
|
||||
(when (> (length body-bytes) 0)
|
||||
(write-sequence body-bytes stream))
|
||||
(finish-output stream)))
|
||||
|
||||
(defun %check-basic-auth (server headers)
|
||||
(let ((auth (gethash "authorization" headers)))
|
||||
(when (and auth (alex:starts-with-subseq "Basic " auth))
|
||||
(let* ((decoded (cl-base64:base64-string-to-string (subseq auth 6)))
|
||||
(expected (format nil "~a:~a" (mock-server-username server) (mock-server-password server))))
|
||||
(string= decoded expected)))))
|
||||
|
||||
(defun %dispatch-mock-request (server method uri headers body)
|
||||
(let ((forced (mock-server-force-error-status server)))
|
||||
(when forced
|
||||
(return-from %dispatch-mock-request (values forced nil "Injected test error"))))
|
||||
|
||||
;; Login Flow v2 endpoints
|
||||
(when (string= uri "/index.php/login/v2")
|
||||
(let* ((base (format nil "http://127.0.0.1:~d" (mock-server-port server)))
|
||||
(obj (make-hash-table :test #'equal))
|
||||
(poll (make-hash-table :test #'equal)))
|
||||
(setf (gethash "token" poll) "test-poll-token"
|
||||
(gethash "endpoint" poll) (format nil "~a/index.php/login/v2/poll" base)
|
||||
(gethash "login" obj) (format nil "~a/login/v2/flow/test" base)
|
||||
(gethash "poll" obj) poll)
|
||||
(return-from %dispatch-mock-request
|
||||
(values 200 '(("Content-Type" . "application/json")) (jzon:stringify obj)))))
|
||||
|
||||
(when (string= uri "/index.php/login/v2/poll")
|
||||
(let ((n (incf (mock-server-login-poll-count server))))
|
||||
(if (< n 2)
|
||||
(return-from %dispatch-mock-request (values 404 nil ""))
|
||||
(let ((obj (make-hash-table :test #'equal)))
|
||||
(setf (gethash "server" obj) (format nil "http://127.0.0.1:~d" (mock-server-port server))
|
||||
(gethash "loginName" obj) (mock-server-username server)
|
||||
(gethash "appPassword" obj) (mock-server-password server))
|
||||
(return-from %dispatch-mock-request
|
||||
(values 200 '(("Content-Type" . "application/json")) (jzon:stringify obj)))))))
|
||||
|
||||
(unless (%check-basic-auth server headers)
|
||||
(return-from %dispatch-mock-request (values 401 nil "Unauthorized")))
|
||||
|
||||
(let* ((files-prefix (format nil "/remote.php/dav/files/~a" (quri:url-encode (mock-server-username server))))
|
||||
(uploads-prefix (format nil "/remote.php/dav/uploads/~a" (quri:url-encode (mock-server-username server)))))
|
||||
(cond
|
||||
;; Chunked Upload v2 endpoint
|
||||
((alex:starts-with-subseq uploads-prefix uri)
|
||||
(let* ((rest (string-trim "/" (quri:url-decode (subseq uri (length uploads-prefix)) :lenient t)))
|
||||
(parts (uiop:split-string rest :separator "/"))
|
||||
(upload-id (first parts))
|
||||
(part-name (second parts)))
|
||||
(cond
|
||||
((string= method "MKCOL")
|
||||
(bt:with-lock-held ((mock-server-lock server))
|
||||
(setf (gethash upload-id (mock-server-uploads server)) (make-hash-table :test #'equal)))
|
||||
(values 201 nil ""))
|
||||
((string= method "PUT")
|
||||
(bt:with-lock-held ((mock-server-lock server))
|
||||
(setf (gethash part-name (gethash upload-id (mock-server-uploads server))) body))
|
||||
(values 201 nil ""))
|
||||
((string= method "MOVE")
|
||||
(let* ((dest-hdr (gethash "destination" headers))
|
||||
(mtime-hdr (gethash "x-oc-mtime" headers))
|
||||
(mtime (when mtime-hdr (ignore-errors (parse-integer mtime-hdr))))
|
||||
(dest-path (or (quri:uri-path (quri:uri dest-hdr)) ""))
|
||||
(rel (string-trim "/" (quri:url-decode (subseq dest-path (length files-prefix)) :lenient t)))
|
||||
(chunks-tbl (bt:with-lock-held ((mock-server-lock server))
|
||||
(prog1 (gethash upload-id (mock-server-uploads server))
|
||||
(remhash upload-id (mock-server-uploads server)))))
|
||||
(keys (sort (alex:hash-table-keys chunks-tbl) #'string<))
|
||||
(total-len (loop for k in keys sum (length (gethash k chunks-tbl))))
|
||||
(merged (make-array total-len :element-type '(unsigned-byte 8)))
|
||||
(pos 0))
|
||||
(dolist (k keys)
|
||||
(let ((chunk (gethash k chunks-tbl)))
|
||||
(replace merged chunk :start1 pos)
|
||||
(incf pos (length chunk))))
|
||||
(let ((etag (mock-put-file server rel merged :mtime mtime)))
|
||||
(values 201 (list (cons "OC-ETag" (format nil "\"~a\"" etag))) ""))))
|
||||
((string= method "DELETE")
|
||||
(bt:with-lock-held ((mock-server-lock server))
|
||||
(remhash upload-id (mock-server-uploads server)))
|
||||
(values 204 nil ""))
|
||||
(t (values 405 nil "")))))
|
||||
|
||||
;; Standard WebDAV files endpoint
|
||||
((alex:starts-with-subseq files-prefix uri)
|
||||
(let ((rel (string-trim "/" (quri:url-decode (subseq uri (length files-prefix)) :lenient t))))
|
||||
(cond
|
||||
((string= method "PROPFIND")
|
||||
(incf (mock-server-propfind-count server))
|
||||
(let* ((depth (or (gethash "depth" headers) "1"))
|
||||
(xml (bt:with-lock-held ((mock-server-lock server))
|
||||
(%render-propfind-response server rel depth))))
|
||||
(if xml
|
||||
(values 207 '(("Content-Type" . "application/xml; charset=utf-8")) xml)
|
||||
(values 404 nil "Not Found"))))
|
||||
((string= method "MKCOL")
|
||||
(if (mock-node-exists-p server rel)
|
||||
(values 405 nil "")
|
||||
(progn
|
||||
(mock-put-dir server rel)
|
||||
(values 201 nil ""))))
|
||||
((string= method "PUT")
|
||||
(let* ((mtime-hdr (gethash "x-oc-mtime" headers))
|
||||
(mtime (when mtime-hdr (ignore-errors (parse-integer mtime-hdr))))
|
||||
(etag (mock-put-file server rel body :mtime mtime)))
|
||||
(values 201 (list (cons "ETag" (format nil "\"~a\"" etag))) "")))
|
||||
((string= method "GET")
|
||||
(let ((node (bt:with-lock-held ((mock-server-lock server))
|
||||
(gethash rel (mock-server-nodes server)))))
|
||||
(if (and node (not (mock-node-is-dir node)))
|
||||
(values 200
|
||||
(list (cons "ETag" (format nil "\"~a\"" (mock-node-etag node)))
|
||||
(cons "Last-Modified" (%format-http-date (mock-node-mtime node)))
|
||||
(cons "Content-Type" "application/octet-stream"))
|
||||
(mock-node-data node))
|
||||
(values 404 nil "Not Found"))))
|
||||
((string= method "DELETE")
|
||||
(if (mock-node-exists-p server rel)
|
||||
(progn
|
||||
(mock-delete-node server rel)
|
||||
(values 204 nil ""))
|
||||
(values 404 nil "")))
|
||||
(t (values 405 nil "")))))
|
||||
(t (values 404 nil "Not Found")))))
|
||||
|
||||
(defun %handle-client (server client-sock)
|
||||
(unwind-protect
|
||||
(handler-case
|
||||
(let* ((stream (sb-bsd-sockets:socket-make-stream
|
||||
client-sock
|
||||
:input t :output t
|
||||
:element-type '(unsigned-byte 8)
|
||||
:buffering :full))
|
||||
(req-line (%read-crlf-line stream)))
|
||||
(when (and req-line (> (length req-line) 0))
|
||||
(let* ((parts (uiop:split-string req-line :separator " "))
|
||||
(method (string-upcase (first parts)))
|
||||
(uri (second parts))
|
||||
(headers (make-hash-table :test #'equal)))
|
||||
(loop for line = (%read-crlf-line stream)
|
||||
while (and line (> (length line) 0))
|
||||
do (let ((colon (position #\: line)))
|
||||
(when colon
|
||||
(let ((k (string-downcase (string-trim '(#\Space #\Tab) (subseq line 0 colon))))
|
||||
(v (string-trim '(#\Space #\Tab) (subseq line (1+ colon)))))
|
||||
(setf (gethash k headers) v)))))
|
||||
(let* ((clen-str (gethash "content-length" headers))
|
||||
(clen (or (when clen-str (ignore-errors (parse-integer clen-str))) 0))
|
||||
(body (if (> clen 0)
|
||||
(%read-exact-bytes stream clen)
|
||||
(make-array 0 :element-type '(unsigned-byte 8)))))
|
||||
(multiple-value-bind (status resp-headers resp-body)
|
||||
(%dispatch-mock-request server method uri headers body)
|
||||
(%write-http-response stream status resp-headers resp-body))))))
|
||||
(error () nil))
|
||||
(ignore-errors (sb-bsd-sockets:socket-close client-sock))))
|
||||
|
||||
(defun start-mock-server (&key (port 0))
|
||||
(let ((sock (make-instance 'sb-bsd-sockets:inet-socket :type :stream :protocol :tcp)))
|
||||
(setf (sb-bsd-sockets:sockopt-reuse-address sock) t)
|
||||
(sb-bsd-sockets:socket-bind sock #(127 0 0 1) port)
|
||||
(sb-bsd-sockets:socket-listen sock 32)
|
||||
(let* ((actual-port (nth-value 1 (sb-bsd-sockets:socket-name sock)))
|
||||
(server (make-mock-server :socket sock :port actual-port :running t)))
|
||||
(setf (gethash "" (mock-server-nodes server))
|
||||
(make-mock-node :is-dir t
|
||||
:mtime (- (get-universal-time) 2208988800)
|
||||
:etag "etag-root-0"
|
||||
:id "id-root"))
|
||||
(setf (mock-server-thread server)
|
||||
(bt:make-thread
|
||||
(lambda ()
|
||||
(loop while (mock-server-running server)
|
||||
do (when (nextcloud-niri::poll-fd-readable-p
|
||||
(sb-bsd-sockets:socket-file-descriptor sock) 100)
|
||||
(let ((c (ignore-errors (sb-bsd-sockets:socket-accept sock))))
|
||||
(when c
|
||||
(%handle-client server c))))))
|
||||
:name "mock-nextcloud-webdav"))
|
||||
server)))
|
||||
|
||||
(defun stop-mock-server (server)
|
||||
(when server
|
||||
(setf (mock-server-running server) nil)
|
||||
(when (mock-server-thread server)
|
||||
(ignore-errors (bt:join-thread (mock-server-thread server))))
|
||||
(when (mock-server-socket server)
|
||||
(ignore-errors (sb-bsd-sockets:socket-close (mock-server-socket server))))))
|
||||
@@ -0,0 +1,6 @@
|
||||
(defpackage #:nextcloud-niri.tests
|
||||
(:use #:cl #:nextcloud-niri)
|
||||
(:local-nicknames (#:jzon #:com.inuoe.jzon)
|
||||
(#:bt #:bordeaux-threads)
|
||||
(#:alex #:alexandria))
|
||||
(:export #:run-all-tests))
|
||||
@@ -0,0 +1,396 @@
|
||||
(in-package #:nextcloud-niri.tests)
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Lightweight Test Harness & Comprehensive End-to-End Tests
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defvar *pass-count* 0)
|
||||
(defvar *fail-count* 0)
|
||||
|
||||
(defmacro check (expr &optional (desc (format nil "~s" expr)))
|
||||
`(if ,expr
|
||||
(incf *pass-count*)
|
||||
(progn
|
||||
(incf *fail-count*)
|
||||
(format *error-output* " FAIL: ~a~%" ,desc))))
|
||||
|
||||
(defun %mktemp-dir (prefix)
|
||||
(let ((dir (format nil "/tmp/~a-~d-~d" prefix (sb-posix:getpid) (get-internal-real-time))))
|
||||
(ensure-directories-exist (uiop:parse-native-namestring (concatenate 'string dir "/")))
|
||||
dir))
|
||||
|
||||
(defun %rm-rf (dir)
|
||||
(ignore-errors
|
||||
(uiop:delete-directory-tree (uiop:parse-native-namestring (concatenate 'string (string-right-trim "/" dir) "/"))
|
||||
:validate t
|
||||
:if-does-not-exist :ignore)))
|
||||
|
||||
(defun %write-text (path text &key mtime)
|
||||
(let ((slash (position #\/ path :from-end t)))
|
||||
(when slash
|
||||
(ensure-directories-exist
|
||||
(uiop:parse-native-namestring (concatenate 'string (subseq path 0 slash) "/")))))
|
||||
(with-open-file (out (uiop:parse-native-namestring path)
|
||||
:direction :output
|
||||
:if-exists :supersede
|
||||
:if-does-not-exist :create
|
||||
:external-format :utf-8)
|
||||
(write-string text out))
|
||||
(when mtime
|
||||
(sb-posix:utime path mtime mtime)))
|
||||
|
||||
(defun %read-text (path)
|
||||
(with-open-file (in (uiop:parse-native-namestring path)
|
||||
:direction :input
|
||||
:external-format :utf-8)
|
||||
(let ((buf (make-string (file-length in))))
|
||||
(let ((n (read-sequence buf in)))
|
||||
(subseq buf 0 n)))))
|
||||
|
||||
(defun %file-exists (path)
|
||||
(handler-case (progn (sb-posix:lstat path) t)
|
||||
(sb-posix:syscall-error () nil)))
|
||||
|
||||
(defmacro with-isolated-env ((tmp-var) &body body)
|
||||
`(let* ((,tmp-var (%mktemp-dir "ncniri-test"))
|
||||
(*config-path-override* (format nil "~a/config.sexp" ,tmp-var))
|
||||
(*credentials-path-override* (format nil "~a/credentials.sexp" ,tmp-var))
|
||||
(*state-dir-override* (format nil "~a/state" ,tmp-var))
|
||||
(*runtime-dir-override* (format nil "~a/runtime" ,tmp-var)))
|
||||
(unwind-protect
|
||||
(progn ,@body)
|
||||
(%rm-rf ,tmp-var))))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Test 1: Config, Credentials (0600), Ignore Rules
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun test-config-and-ignores ()
|
||||
(format t "~&[1/6] Testing config, credentials, and ignore patterns...~%")
|
||||
(with-isolated-env (tmp)
|
||||
(save-credentials :url "https://cloud.example.com/"
|
||||
:username "alice"
|
||||
:password "app-pass-123")
|
||||
(let ((st (sb-posix:stat *credentials-path-override*)))
|
||||
(check (= (logand (sb-posix:stat-mode st) #o777) #o600)
|
||||
"credentials.sexp has 0600 permissions"))
|
||||
(let ((cfg (load-config)))
|
||||
(check (string= (server-url (config-server cfg)) "https://cloud.example.com")
|
||||
"config inherits url from credentials")
|
||||
(check (string= (resolve-password cfg) "app-pass-123")
|
||||
"resolve-password reads credentials")
|
||||
(setf (config-folders cfg)
|
||||
(list (nextcloud-niri::make-folder-config
|
||||
:name "Notes"
|
||||
:local (format nil "~a/Notes" tmp)
|
||||
:remote "Documents/Notes")))
|
||||
(save-config cfg)
|
||||
(let ((reloaded (load-config)))
|
||||
(check (= (length (config-folders reloaded)) 1) "folder round-trip count")
|
||||
(check (string= (folder-name (first (config-folders reloaded))) "Notes") "folder name round-trip")
|
||||
(check (string= (folder-remote (first (config-folders reloaded))) "Documents/Notes") "folder remote round-trip")))
|
||||
|
||||
;; Ignore pattern matching
|
||||
(let ((pats '(".git" "*.tmp" "*~" "secret/*.key")))
|
||||
(check (path-ignored-p ".git" pats) "ignores .git")
|
||||
(check (path-ignored-p "sub/.git/HEAD" pats) "ignores nested .git")
|
||||
(check (path-ignored-p "notes/draft.tmp" pats) "ignores *.tmp")
|
||||
(check (path-ignored-p "todo.md~" pats) "ignores *~")
|
||||
(check (path-ignored-p "secret/id.key" pats) "ignores path glob")
|
||||
(check (not (path-ignored-p "notes/[2026] meeting.md" pats)) "does not ignore normal/bracket filename"))))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Test 2: 3-Way Bidirectional Sync, Wildcard Filenames, Dedup, ETag Pruning
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun test-bidirectional-sync ()
|
||||
(format t "~&[2/6] Testing 3-way bidirectional sync, ETag pruning, and mtime preservation...~%")
|
||||
(with-isolated-env (tmp)
|
||||
(let* ((server (start-mock-server :port 0))
|
||||
(port (mock-server-port server))
|
||||
(base-url (format nil "http://127.0.0.1:~d" port))
|
||||
(local-dir (format nil "~a/Notes" tmp))
|
||||
(folder (nextcloud-niri::make-folder-config :name "Notes" :local local-dir :remote "Documents/Notes"))
|
||||
(sync-cfg (nextcloud-niri::make-sync-config :notify-on-error nil))
|
||||
(client (make-webdav-client :url base-url :username "alice" :password "secret-app-pw")))
|
||||
(unwind-protect
|
||||
(progn
|
||||
;; Seed local files (including special chars: spaces & brackets!) and one remote file
|
||||
(%write-text (format nil "~a/hello.md" local-dir) "Hello local!" :mtime 1700000100)
|
||||
(%write-text (format nil "~a/sub/[2026] plan.md" local-dir) "Nested brackets!" :mtime 1700000200)
|
||||
(%write-text (format nil "~a/ignored.tmp" local-dir) "skip me")
|
||||
(mock-put-file server "Documents/Notes/remote-only.md" "From server!" :mtime 1700000300)
|
||||
|
||||
;; Sync #1: initial bidirectional sync
|
||||
(let ((r1 (sync-folder client folder sync-cfg)))
|
||||
(check (null (sync-result-errors r1)) "sync #1 no errors")
|
||||
(check (= (sync-result-uploaded r1) 2) "sync #1 uploaded 2 local files")
|
||||
(check (= (sync-result-downloaded r1) 1) "sync #1 downloaded 1 remote file")
|
||||
(check (string= (mock-get-file-string server "Documents/Notes/hello.md") "Hello local!")
|
||||
"hello.md uploaded intact")
|
||||
(check (string= (mock-get-file-string server "Documents/Notes/sub/[2026] plan.md") "Nested brackets!")
|
||||
"bracket filename uploaded intact")
|
||||
(check (not (mock-node-exists-p server "Documents/Notes/ignored.tmp"))
|
||||
"ignored.tmp was not uploaded")
|
||||
(check (string= (%read-text (format nil "~a/remote-only.md" local-dir)) "From server!")
|
||||
"remote-only.md downloaded intact")
|
||||
(check (= (sb-posix:stat-mtime (sb-posix:stat (format nil "~a/remote-only.md" local-dir))) 1700000300)
|
||||
"downloaded file preserved remote mtime"))
|
||||
|
||||
;; Sync #2: NO changes -> ETag fast-path should issue ONLY 1 PROPFIND (Depth 0 on root)!
|
||||
(setf (mock-propfind-count server) 0)
|
||||
(let ((r2 (sync-folder client folder sync-cfg)))
|
||||
(check (sync-result-skipped-p r2) "sync #2 skipped via root ETag fast-path")
|
||||
(check (= (mock-propfind-count server) 1) "sync #2 made only 1 PROPFIND request"))
|
||||
|
||||
;; Touch local file (change mtime only, same content) -> SHA-256 dedup avoids upload!
|
||||
(sb-posix:utime (format nil "~a/hello.md" local-dir) 1700000999 1700000999)
|
||||
(let ((r-touch (sync-folder client folder sync-cfg)))
|
||||
(check (= (sync-result-uploaded r-touch) 0) "mtime-only touch did not re-upload"))
|
||||
|
||||
;; Modify local file -> uploads; modify remote file -> downloads
|
||||
(%write-text (format nil "~a/hello.md" local-dir) "Hello local v2!" :mtime 1700001000)
|
||||
(mock-put-file server "Documents/Notes/remote-only.md" "From server v2!" :mtime 1700001100)
|
||||
(let ((r3 (sync-folder client folder sync-cfg)))
|
||||
(check (= (sync-result-uploaded r3) 1) "sync #3 uploaded modified local")
|
||||
(check (= (sync-result-downloaded r3) 1) "sync #3 downloaded modified remote")
|
||||
(check (string= (mock-get-file-string server "Documents/Notes/hello.md") "Hello local v2!")
|
||||
"remote got local v2")
|
||||
(check (string= (%read-text (format nil "~a/remote-only.md" local-dir)) "From server v2!")
|
||||
"local got remote v2"))
|
||||
|
||||
;; Propagate deletions both ways
|
||||
(sb-posix:unlink (format nil "~a/hello.md" local-dir))
|
||||
(mock-delete-node server "Documents/Notes/remote-only.md")
|
||||
(let ((r4 (sync-folder client folder sync-cfg)))
|
||||
(check (= (sync-result-deleted-remote r4) 1) "sync #4 propagated local delete to remote")
|
||||
(check (= (sync-result-deleted-local r4) 1) "sync #4 propagated remote delete to local")
|
||||
(check (not (mock-node-exists-p server "Documents/Notes/hello.md")) "hello.md deleted remotely")
|
||||
(check (not (%file-exists (format nil "~a/remote-only.md" local-dir))) "remote-only.md deleted locally")))
|
||||
(stop-mock-server server)))))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Test 3: Conflict Preservation, Missing Root Guard, Chunked Upload v2, Login v2
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun test-conflicts-safety-and-chunked ()
|
||||
(format t "~&[3/6] Testing conflicts, missing-root safety guard, chunked upload v2, and Login Flow v2...~%")
|
||||
(with-isolated-env (tmp)
|
||||
(let* ((server (start-mock-server :port 0))
|
||||
(port (mock-server-port server))
|
||||
(base-url (format nil "http://127.0.0.1:~d" port))
|
||||
(local-dir (format nil "~a/Docs" tmp))
|
||||
(folder (nextcloud-niri::make-folder-config :name "Docs" :local local-dir :remote "Docs"))
|
||||
;; 1 MB chunk size to test Chunked Upload v2 cleanly
|
||||
(sync-cfg (nextcloud-niri::make-sync-config :chunk-size-mb 1 :notify-on-error nil))
|
||||
(client (make-webdav-client :url base-url :username "alice" :password "secret-app-pw" :chunk-size-mb 1)))
|
||||
(unwind-protect
|
||||
(progn
|
||||
;; Initial file synced
|
||||
(%write-text (format nil "~a/shared.md" local-dir) "v1" :mtime 1700000100)
|
||||
(sync-folder client folder sync-cfg)
|
||||
|
||||
;; Both sides edit shared.md differently -> conflict!
|
||||
(%write-text (format nil "~a/shared.md" local-dir) "local edit!" :mtime 1700000500)
|
||||
(mock-put-file server "Docs/shared.md" "remote edit!" :mtime 1700000600)
|
||||
(let ((rc (sync-folder client folder sync-cfg)))
|
||||
(check (= (length (sync-result-conflicts rc)) 1) "detected true conflict")
|
||||
(check (string= (%read-text (format nil "~a/shared.md" local-dir)) "remote edit!")
|
||||
"remote version placed at original path")
|
||||
(let* ((names (nextcloud-niri::%list-dir-names local-dir))
|
||||
(conf-file (find-if (lambda (n) (search "conflicted copy" n)) names)))
|
||||
(check (not (null conf-file)) "created conflicted copy file locally")
|
||||
(when conf-file
|
||||
(check (string= (%read-text (format nil "~a/~a" local-dir conf-file)) "local edit!")
|
||||
"conflicted copy preserved local edits")
|
||||
(check (string= (mock-get-file-string server (format nil "Docs/~a" conf-file)) "local edit!")
|
||||
"conflicted copy also uploaded to remote"))))
|
||||
|
||||
;; Both sides edit identically -> NO conflict!
|
||||
(%write-text (format nil "~a/same.md" local-dir) "identical bytes" :mtime 1700000700)
|
||||
(mock-put-file server "Docs/same.md" "identical bytes" :mtime 1700000800)
|
||||
(let ((rs (sync-folder client folder sync-cfg)))
|
||||
(check (null (sync-result-conflicts rs)) "identical concurrent edit produces zero conflicts"))
|
||||
|
||||
;; Chunked Upload v2 (> 1MB file -> 1.5MB)
|
||||
(let* ((big-path (format nil "~a/big.bin" local-dir))
|
||||
(big-bytes (make-array (* 1536 1024) :element-type '(unsigned-byte 8) :initial-element 65)))
|
||||
(setf (aref big-bytes 0) 90
|
||||
(aref big-bytes (1- (length big-bytes))) 89)
|
||||
(with-open-file (out (uiop:parse-native-namestring big-path)
|
||||
:direction :output
|
||||
:element-type '(unsigned-byte 8)
|
||||
:if-exists :supersede)
|
||||
(write-sequence big-bytes out))
|
||||
(let ((rb (sync-folder client folder sync-cfg)))
|
||||
(check (= (sync-result-uploaded rb) 1) "chunked upload v2 succeeded")
|
||||
(let ((node (gethash "Docs/big.bin" (mock-nodes server))))
|
||||
(check (and node (= (length (mock-node-data node)) (length big-bytes))
|
||||
(= (aref (mock-node-data node) 0) 90)
|
||||
(= (aref (mock-node-data node) (1- (length big-bytes))) 89))
|
||||
"chunked upload assembled exact bytes"))))
|
||||
|
||||
;; Missing Local Root Safety Guard: remove local folder -> must error and NOT delete remote!
|
||||
(%rm-rf local-dir)
|
||||
(let ((rm (sync-folder client folder sync-cfg)))
|
||||
(check (not (null (sync-result-errors rm))) "missing local root produces error")
|
||||
(check (mock-node-exists-p server "Docs/shared.md")
|
||||
"missing local root did NOT wipe remote files"))
|
||||
|
||||
;; Login Flow v2
|
||||
(multiple-value-bind (login-url poll-ep poll-tok)
|
||||
(nextcloud-login-flow-start base-url)
|
||||
(check (search "/login/v2/flow/test" login-url) "login flow v2 returned login URL")
|
||||
(check (null (nextcloud-login-flow-poll poll-ep poll-tok)) "first poll returns NIL (404)")
|
||||
(multiple-value-bind (srv user pw) (nextcloud-login-flow-poll poll-ep poll-tok)
|
||||
(check (string= srv base-url) "second poll returns server URL")
|
||||
(check (string= user "alice") "second poll returns loginName")
|
||||
(check (string= pw "secret-app-pw") "second poll returns appPassword"))))
|
||||
(stop-mock-server server)))))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Test 4: Pure SBCL sb-alien Linux inotify Watcher
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun test-inotify-watcher ()
|
||||
(format t "~&[4/6] Testing pure SBCL Linux inotify recursive watcher...~%")
|
||||
(let* ((tmp (%mktemp-dir "ncniri-inotify"))
|
||||
(w (make-inotify-watcher :ignores '("*.tmp"))))
|
||||
(unwind-protect
|
||||
(progn
|
||||
(watcher-add-tree w tmp :register-root t)
|
||||
(%write-text (format nil "~a/note.md" tmp) "hello")
|
||||
(%write-text (format nil "~a/ignore.tmp" tmp) "skip")
|
||||
(let ((evs (watcher-poll-events w :timeout-ms 500)))
|
||||
(check (some (lambda (e) (search "note.md" (nextcloud-niri::ievent-path e))) evs)
|
||||
"inotify detected note.md creation/write")
|
||||
(check (not (some (lambda (e) (search "ignore.tmp" (nextcloud-niri::ievent-path e))) evs))
|
||||
"inotify filtered ignored *.tmp file"))
|
||||
;; Create a new subdirectory and then a file inside it
|
||||
(let ((sub (format nil "~a/nested" tmp)))
|
||||
(sb-posix:mkdir sub #o755)
|
||||
(watcher-poll-events w :timeout-ms 500)
|
||||
(%write-text (format nil "~a/deep.md" sub) "deep!")
|
||||
(let ((evs2 (watcher-poll-events w :timeout-ms 500)))
|
||||
(check (some (lambda (e) (search "deep.md" (nextcloud-niri::ievent-path e))) evs2)
|
||||
"inotify auto-watched newly created subdirectory"))))
|
||||
(watcher-close w)
|
||||
(%rm-rf tmp))))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Test 5: End-to-End Daemon + inotify Auto-Sync + Unix Socket IPC + Waybar JSON
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun %wait-for-state (target-state &key (timeout-sec 8))
|
||||
(let ((deadline (+ (get-internal-real-time) (* timeout-sec internal-time-units-per-second))))
|
||||
(loop while (< (get-internal-real-time) deadline)
|
||||
do (let ((st (read-status)))
|
||||
(when (and st (string= (gethash "state" st) target-state))
|
||||
(return t)))
|
||||
(sleep 0.1))))
|
||||
|
||||
(defun test-daemon-ipc-and-waybar ()
|
||||
(format t "~&[5/6] Testing daemon lifecycle, real-time inotify sync, IPC, and Waybar JSON states...~%")
|
||||
(with-isolated-env (tmp)
|
||||
(let* ((server (start-mock-server :port 0))
|
||||
(port (mock-server-port server))
|
||||
(base-url (format nil "http://127.0.0.1:~d" port))
|
||||
(local-dir (format nil "~a/Notes" tmp))
|
||||
(cfg (nextcloud-niri::make-app-config
|
||||
:server (nextcloud-niri::make-server-config
|
||||
:url base-url :username "alice" :password "secret-app-pw")
|
||||
:sync (nextcloud-niri::make-sync-config
|
||||
:poll-interval 60 :debounce-seconds 0.3 :notify-on-error nil)
|
||||
:waybar (nextcloud-niri::make-waybar-config :signal 0 :label "nc")
|
||||
:folders (list (nextcloud-niri::make-folder-config
|
||||
:name "Notes" :local local-dir :remote "Documents/Notes"))))
|
||||
(daemon nil))
|
||||
(unwind-protect
|
||||
(progn
|
||||
(%write-text (format nil "~a/init.md" local-dir) "initial note")
|
||||
(save-config cfg)
|
||||
|
||||
;; Before daemon starts -> waybar shows "off"
|
||||
(let ((wb-off (jzon:parse (render-waybar-json cfg))))
|
||||
(check (string= (gethash "class" wb-off) "off") "waybar class is 'off' when daemon stopped"))
|
||||
|
||||
;; Start daemon -> initial sync -> synced!
|
||||
(setf daemon (make-daemon cfg))
|
||||
(daemon-start daemon :initial-sync t)
|
||||
(check (%wait-for-state "synced") "daemon reached 'synced' state after startup")
|
||||
(check (string= (mock-get-file-string server "Documents/Notes/init.md") "initial note")
|
||||
"daemon synced initial file")
|
||||
(let ((wb-ok (jzon:parse (render-waybar-json cfg))))
|
||||
(check (string= (gethash "class" wb-ok) "synced") "waybar class is 'synced'")
|
||||
(check (string= (gethash "text" wb-ok) "nc") "waybar text is 'nc' when synced")
|
||||
(check (search "Notes:" (gethash "tooltip" wb-ok)) "waybar tooltip lists folder"))
|
||||
|
||||
;; Edit local file -> inotify triggers auto-sync without manual trigger!
|
||||
(%write-text (format nil "~a/live.md" local-dir) "edited live!")
|
||||
(let ((deadline (+ (get-internal-real-time) (* 6 internal-time-units-per-second))))
|
||||
(loop while (and (< (get-internal-real-time) deadline)
|
||||
(not (string= (or (mock-get-file-string server "Documents/Notes/live.md") "")
|
||||
"edited live!")))
|
||||
do (sleep 0.1)))
|
||||
(check (string= (or (mock-get-file-string server "Documents/Notes/live.md") "") "edited live!")
|
||||
"daemon automatically synced live local edit via inotify")
|
||||
(check (%wait-for-state "synced") "daemon returned to 'synced' after live edit")
|
||||
|
||||
;; Pause via Unix socket IPC -> waybar shows "paused"
|
||||
(let ((resp (ipc-send-command "toggle")))
|
||||
(check (and resp (gethash "ok" resp) (gethash "paused" resp)) "IPC toggle paused daemon"))
|
||||
(let ((wb-paused (jzon:parse (render-waybar-json cfg))))
|
||||
(check (string= (gethash "class" wb-paused) "paused") "waybar class is 'paused'"))
|
||||
|
||||
;; Resume via IPC + inject server 500 error -> waybar shows "error"!
|
||||
(setf (mock-force-error-status server) 500)
|
||||
(ipc-send-command "resume")
|
||||
(check (%wait-for-state "error") "daemon transitioned to 'error' on HTTP 500")
|
||||
(let ((wb-err (jzon:parse (render-waybar-json cfg))))
|
||||
(check (string= (gethash "class" wb-err) "error") "waybar class is 'error'")
|
||||
(check (search "!" (gethash "text" wb-err)) "waybar text shows '!' on error")
|
||||
(check (search "problem syncing" (gethash "tooltip" wb-err)) "waybar tooltip explains problem"))
|
||||
|
||||
;; Recover from error -> IPC sync -> synced!
|
||||
(setf (mock-force-error-status server) nil)
|
||||
(ipc-send-command "sync")
|
||||
(check (%wait-for-state "synced") "daemon recovered to 'synced' after error cleared")
|
||||
|
||||
;; Stop daemon -> waybar returns to "off"
|
||||
(daemon-stop daemon)
|
||||
(setf daemon nil)
|
||||
(let ((wb-after (jzon:parse (render-waybar-json cfg))))
|
||||
(check (string= (gethash "class" wb-after) "off") "waybar class is 'off' after daemon stop")))
|
||||
(when daemon (daemon-stop daemon))
|
||||
(stop-mock-server server)))))
|
||||
|
||||
;;; ---------------------------------------------------------------------------
|
||||
;;; Test 6: Waybar Unsynced Visual State
|
||||
;;; ---------------------------------------------------------------------------
|
||||
|
||||
(defun test-waybar-unsynced-and-syncing ()
|
||||
(format t "~&[6/6] Testing Waybar unsynced and syncing visual states...~%")
|
||||
(with-isolated-env (tmp)
|
||||
(progn
|
||||
tmp
|
||||
(let ((cfg (nextcloud-niri::make-app-config)))
|
||||
(write-status :state :unsynced :pending 3 :server-url "https://nc.test")
|
||||
(let ((wb (jzon:parse (render-waybar-json cfg))))
|
||||
(check (string= (gethash "class" wb) "unsynced") "waybar class is 'unsynced'")
|
||||
(check (search "*3" (gethash "text" wb)) "waybar text shows pending count '*3'"))
|
||||
(write-status :state :syncing :progress-done 2 :progress-total 5 :progress-detail "↑ note.md")
|
||||
(let ((wb2 (jzon:parse (render-waybar-json cfg))))
|
||||
(check (string= (gethash "class" wb2) "syncing") "waybar class is 'syncing'")
|
||||
(check (search "2/5" (gethash "text" wb2)) "waybar text shows progress '2/5'"))))) )
|
||||
|
||||
(defun run-all-tests ()
|
||||
(setf *pass-count* 0
|
||||
*fail-count* 0)
|
||||
(test-config-and-ignores)
|
||||
(test-bidirectional-sync)
|
||||
(test-conflicts-safety-and-chunked)
|
||||
(test-inotify-watcher)
|
||||
(test-daemon-ipc-and-waybar)
|
||||
(test-waybar-unsynced-and-syncing)
|
||||
(format t "~&~%=== Results: ~d passed, ~d failed ===~%" *pass-count* *fail-count*)
|
||||
(zerop *fail-count*))
|
||||
@@ -0,0 +1,14 @@
|
||||
// Add "custom/nextcloud" to your "modules-right" array in ~/.config/waybar/config,
|
||||
// e.g.:
|
||||
// "modules-right": ["custom/player", "custom/nextcloud", "custom/bright", "custom/net", "custom/vol", "custom/bat", "custom/bt", "clock"],
|
||||
|
||||
"custom/nextcloud": {
|
||||
"exec": "~/.local/bin/nextcloud-niri waybar",
|
||||
"return-type": "json",
|
||||
"markup": "pango",
|
||||
"tooltip": true,
|
||||
"interval": 30,
|
||||
"signal": 7,
|
||||
"on-click": "~/.local/bin/nextcloud-niri sync",
|
||||
"on-click-right": "~/.local/bin/nextcloud-niri toggle"
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/* Add to ~/.config/waybar/style.css (matches olivtsi base16 palette) */
|
||||
|
||||
#custom-nextcloud {
|
||||
padding: 0 10px;
|
||||
color: #c2c7b3;
|
||||
}
|
||||
|
||||
#custom-nextcloud.synced {
|
||||
color: #c2c7b3;
|
||||
}
|
||||
|
||||
#custom-nextcloud.unsynced,
|
||||
#custom-nextcloud.syncing {
|
||||
color: #de9d5f;
|
||||
}
|
||||
|
||||
#custom-nextcloud.error {
|
||||
color: #cc7066;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
#custom-nextcloud.paused,
|
||||
#custom-nextcloud.off {
|
||||
color: #7a806f;
|
||||
}
|
||||
Reference in new issue
Block a user