Extract dufs cloud (web + app + scripts) to github.com/kuhyx/dufs-cloud
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run

Move cloud_gallery/, the Flutter dufs_client app, and the dufs/cloud setup
scripts into a new public repo (with full git history), leaving pointers here.
The live media-cloud-sync systemd units were re-pointed to ~/dufs-cloud/scripts/.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0126QvdMrv2WNeUVShFiLTc3
This commit is contained in:
Krzysztof Rudnicki 2026-07-12 18:38:37 +02:00
parent dfd0e2d70a
commit b500b5daba
41 changed files with 62 additions and 5950 deletions

View File

@ -12,6 +12,12 @@ Extracted to their own repos:
- [`screen-locker`](https://github.com/kuhyx/screen-locker)
- [`diet-guard`](https://github.com/kuhyx/diet-guard)
- [`wake-alarm`](https://github.com/kuhyx/wake-alarm)
- [`dufs-cloud`](https://github.com/kuhyx/dufs-cloud) — self-hosted dufs cloud:
React web gallery (`web/`), Flutter app (`app/`), and the dufs/media setup
scripts (`scripts/`). Extracted from `cloud_gallery/` + the
`linux_configuration` dufs scripts + the standalone `dufs_client` repo. The
live `media-cloud-sync` systemd units now run the scripts from
`~/dufs-cloud/scripts/`.
Archived / unmaintained projects live in the sibling repository
[`testsAndMisc-archive`](https://github.com/kuhyx/testsAndMisc-archive).

View File

@ -1,6 +0,0 @@
node_modules/
dist/
coverage/
*.tsbuildinfo
*.local
.DS_Store

View File

@ -1,47 +0,0 @@
import js from "@eslint/js";
import reactHooksPlugin from "eslint-plugin-react-hooks";
import tseslint from "typescript-eslint";
// Aggressive, type-aware config: everything typescript-eslint's strict +
// stylistic *type-checked* presets flag is an error, plus the React Hooks
// rules. Unused disable directives are themselves errors, so every
// `eslint-disable` must be load-bearing.
//
// eslint-plugin-react is intentionally omitted: 7.37.x still calls the
// `context.getFilename()` API that ESLint 10 removed, so it crashes the run.
// TypeScript already covers prop typing, and react-hooks (v10-ready) covers the
// hook-specific rules that TS cannot.
export default tseslint.config(
{ ignores: ["dist", "coverage"] },
{ linterOptions: { reportUnusedDisableDirectives: "error" } },
js.configs.recommended,
...tseslint.configs.strictTypeChecked,
...tseslint.configs.stylisticTypeChecked,
{
files: ["**/*.{ts,tsx}"],
plugins: { "react-hooks": reactHooksPlugin },
languageOptions: {
parserOptions: {
project: "./tsconfig.json",
tsconfigRootDir: import.meta.dirname,
},
},
rules: {
...reactHooksPlugin.configs.recommended.rules,
"@typescript-eslint/restrict-template-expressions": [
"error",
{ allowNumber: true },
],
},
},
{
// Asserting on a vitest mock method (e.g. `expect(client.remove)`) trips
// unbound-method even though the reference is safe; disable it in tests.
files: ["**/*.test.{ts,tsx}", "src/test/**"],
rules: { "@typescript-eslint/unbound-method": "off" },
},
{
files: ["*.js", "*.mjs", "*.cjs"],
...tseslint.configs.disableTypeChecked,
},
);

View File

@ -1,13 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light dark" />
<title>Cloud</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@ -1,40 +0,0 @@
{
"name": "cloud-gallery",
"private": true,
"version": "0.1.0",
"type": "module",
"description": "Media-gallery SPA served by dufs at the self-hosted cloud",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "tsc --noEmit && eslint src",
"preview": "vite preview",
"test": "vitest run",
"coverage": "vitest run --coverage"
},
"engines": {
"node": ">=22",
"pnpm": ">=10"
},
"dependencies": {
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.1",
"@types/react": "^19.1.0",
"@types/react-dom": "^19.1.0",
"@vitejs/plugin-react": "^4.5.2",
"@vitest/coverage-v8": "^4.1.9",
"eslint": "^10.6.0",
"eslint-plugin-react-hooks": "^7.1.1",
"jsdom": "^29.1.1",
"typescript": "~5.8.3",
"typescript-eslint": "^8.62.0",
"vite": "^6.3.5",
"vitest": "^4.1.9"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +0,0 @@
# pnpm build-script allowlist. esbuild needs its postinstall to link its
# platform binary (Vite depends on it). `onlyBuiltDependencies` is the pnpm 10
# location; `allowBuilds` is the pnpm 11 location — both are set so either works.
allowBuilds:
esbuild: true
onlyBuiltDependencies:
- esbuild

View File

@ -1,134 +0,0 @@
import { describe, it, expect, vi } from "vitest";
import {
createDufsClient,
parsePropfind,
sortEntries,
} from "./dufs-client.ts";
import type { DirEntry } from "./types.ts";
const PROPFIND_XML = `<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:">
<D:response>
<D:href>/Media/2026/07/</D:href>
<D:propstat><D:prop><D:resourcetype><D:collection/></D:resourcetype></D:prop></D:propstat>
</D:response>
<D:response>
<D:href>/Media/2026/07/sub/</D:href>
<D:propstat><D:prop>
<D:resourcetype><D:collection/></D:resourcetype>
<D:getlastmodified>Sat, 12 Jul 2026 03:00:00 GMT</D:getlastmodified>
</D:prop></D:propstat>
</D:response>
<D:response>
<D:href>/Media/2026/07/a%20b.jpg</D:href>
<D:propstat><D:prop>
<D:resourcetype/>
<D:getcontentlength>2048</D:getcontentlength>
<D:getlastmodified>Sat, 12 Jul 2026 03:00:00 GMT</D:getlastmodified>
</D:prop></D:propstat>
</D:response>
<D:response><D:href></D:href></D:response>
</D:multistatus>`;
describe("parsePropfind", () => {
it("parses entries, skips self, decodes names, reads size/mtime", () => {
const entries = parsePropfind(PROPFIND_XML, "/Media/2026/07");
// self ("/Media/2026/07/") and the empty-href entry are dropped
expect(entries.map((e) => e.name)).toEqual(["sub", "a b.jpg"]);
const file = entries.find((e) => e.name === "a b.jpg");
expect(file?.kind).toBe("file");
expect(file?.size).toBe(2048);
expect(file?.mtimeMs).toBeGreaterThan(0);
expect(entries.find((e) => e.name === "sub")?.kind).toBe("dir");
});
it("handles missing size/mtime as zero", () => {
const xml = `<D:multistatus xmlns:D="DAV:"><D:response><D:href>/x.bin</D:href><D:propstat><D:prop><D:resourcetype/></D:prop></D:propstat></D:response></D:multistatus>`;
const [entry] = parsePropfind(xml, "/");
expect(entry?.size).toBe(0);
expect(entry?.mtimeMs).toBe(0);
});
it("coerces an unparsable size/mtime to zero", () => {
const xml = `<D:multistatus xmlns:D="DAV:"><D:response><D:href>/y.bin</D:href><D:propstat><D:prop><D:resourcetype/><D:getcontentlength>not-a-number</D:getcontentlength><D:getlastmodified>never</D:getlastmodified></D:prop></D:propstat></D:response></D:multistatus>`;
const [entry] = parsePropfind(xml, "/");
expect(entry?.size).toBe(0);
expect(entry?.mtimeMs).toBe(0);
});
});
describe("sortEntries", () => {
it("dirs first then case-insensitive name", () => {
const mk = (name: string, kind: "dir" | "file"): DirEntry => ({
name,
path: `/${name}`,
kind,
size: 0,
mtimeMs: 0,
});
const sorted = sortEntries([
mk("banana.jpg", "file"),
mk("Apple", "dir"),
mk("apple.png", "file"),
mk("Zeta", "dir"),
]);
expect(sorted.map((e) => e.name)).toEqual([
"Apple",
"Zeta",
"apple.png",
"banana.jpg",
]);
});
});
function jsonResponse(body: string, ok = true, status = 200): Response {
return {
ok,
status,
text: () => Promise.resolve(body),
} as unknown as Response;
}
describe("createDufsClient", () => {
it("list() PROPFINDs, sorts, and returns entries", async () => {
const fetchImpl = vi.fn<typeof fetch>(() =>
Promise.resolve(jsonResponse(PROPFIND_XML)),
);
const client = createDufsClient(fetchImpl);
const entries = await client.list("/Media/2026/07");
const firstCall = fetchImpl.mock.calls.at(0);
expect(firstCall?.[0]).toBe("/Media/2026/07");
expect(firstCall?.[1]?.method).toBe("PROPFIND");
expect(entries.length).toBe(2);
});
it("builds file and thumbnail URLs (encoded)", () => {
const client = createDufsClient(vi.fn<typeof fetch>());
expect(client.fileUrl("/Media/a b.jpg")).toBe("/Media/a%20b.jpg");
expect(client.thumbUrl("/Media/a b.jpg")).toBe(
"/.thumbs/Media/a%20b.jpg.jpg",
);
});
it("upload PUTs to dir/name, remove DELETEs, writeText PUTs, readText GETs", async () => {
const fetchImpl = vi.fn<typeof fetch>(() =>
Promise.resolve(jsonResponse("content")),
);
const client = createDufsClient(fetchImpl);
const file = new File(["x"], "n.txt");
await client.upload("/dir", file);
await client.remove("/dir/n.txt");
await client.writeText("/dir/n.txt", "hi");
const text = await client.readText("/dir/n.txt");
expect(text).toBe("content");
const methods = fetchImpl.mock.calls.map((c) => c[1]?.method);
expect(methods).toEqual(["PUT", "DELETE", "PUT", "GET"]);
expect(fetchImpl.mock.calls.at(0)?.[0]).toBe("/dir/n.txt");
});
it("throws on non-ok responses", async () => {
const fetchImpl = vi.fn<typeof fetch>(() =>
Promise.resolve(jsonResponse("", false, 404)),
);
const client = createDufsClient(fetchImpl);
await expect(client.remove("/nope")).rejects.toThrow("404");
});
});

View File

@ -1,112 +0,0 @@
import type { DirEntry, EntryKind } from "./types.ts";
import { basename, encodePath, joinPath, normalize } from "../lib/paths.ts";
const DAV_NS = "DAV:";
/** Client over the dufs WebDAV + HTTP API (same-origin; browser supplies auth). */
export interface DufsClient {
/** List a directory via WebDAV PROPFIND (works under dufs `render-spa`). */
list(dirPath: string): Promise<DirEntry[]>;
/** Same-origin URL to fetch/stream a file's raw bytes. */
fileUrl(path: string): string;
/** URL of the generated thumbnail for a media entry (see generate_thumbnails.sh). */
thumbUrl(path: string): string;
upload(dirPath: string, file: File): Promise<void>;
remove(path: string): Promise<void>;
readText(path: string): Promise<string>;
writeText(path: string, content: string): Promise<void>;
}
/** Parse a dufs PROPFIND multistatus XML body into entries under `dirPath`. */
export function parsePropfind(xml: string, dirPath: string): DirEntry[] {
const doc = new DOMParser().parseFromString(xml, "application/xml");
const self = normalize(dirPath);
const responses = Array.from(doc.getElementsByTagNameNS(DAV_NS, "response"));
const entries: DirEntry[] = [];
for (const res of responses) {
const hrefEl = res.getElementsByTagNameNS(DAV_NS, "href")[0];
const rawHref = hrefEl?.textContent;
if (rawHref === null || rawHref === undefined || rawHref === "") continue;
// href is URL-encoded and absolute; decode and normalize.
const path = normalize(decodeURIComponent(rawHref));
if (path === self) continue; // skip the directory itself
const isDir =
res.getElementsByTagNameNS(DAV_NS, "collection").length > 0;
const kind: EntryKind = isDir ? "dir" : "file";
const sizeText = res
.getElementsByTagNameNS(DAV_NS, "getcontentlength")[0]
?.textContent;
const size = sizeText !== null && sizeText !== undefined ? Number(sizeText) : 0;
const mtimeText = res
.getElementsByTagNameNS(DAV_NS, "getlastmodified")[0]
?.textContent;
const mtimeMs =
mtimeText !== null && mtimeText !== undefined
? Date.parse(mtimeText) || 0
: 0;
entries.push({
name: basename(path),
path,
kind,
size: Number.isFinite(size) ? size : 0,
mtimeMs,
});
}
return entries;
}
/** Sort: directories first, then by name (locale, case-insensitive). */
export function sortEntries(entries: readonly DirEntry[]): DirEntry[] {
return [...entries].sort((a, b) => {
if (a.kind !== b.kind) return a.kind === "dir" ? -1 : 1;
return a.name.localeCompare(b.name, undefined, { sensitivity: "base" });
});
}
export function createDufsClient(fetchImpl: typeof fetch = fetch): DufsClient {
// `method` is always supplied by callers, so the error message and the fetch
// options never need to fall back — keeping it a required arg avoids an
// unreachable default branch.
async function request(
method: string,
path: string,
init: RequestInit = {},
): Promise<Response> {
const res = await fetchImpl(encodePath(path), {
method,
credentials: "same-origin",
...init,
});
if (!res.ok) {
throw new Error(`${method} ${path} → ${res.status}`);
}
return res;
}
return {
async list(dirPath) {
const res = await request("PROPFIND", dirPath, {
headers: { Depth: "1" },
});
return sortEntries(parsePropfind(await res.text(), dirPath));
},
fileUrl(path) {
return encodePath(path);
},
thumbUrl(path) {
return encodePath(`/.thumbs${normalize(path)}.jpg`);
},
async upload(dirPath, file) {
await request("PUT", joinPath(dirPath, file.name), { body: file });
},
async remove(path) {
await request("DELETE", path);
},
async readText(path) {
return (await request("GET", path)).text();
},
async writeText(path, content) {
await request("PUT", path, { body: content });
},
};
}

View File

@ -1,14 +0,0 @@
export type EntryKind = "dir" | "file";
/** One entry in a directory listing, as returned by the dufs WebDAV PROPFIND. */
export interface DirEntry {
/** Base name, e.g. "pic.jpg". */
readonly name: string;
/** Absolute path from the cloud root, e.g. "/Media/2026/07/pic.jpg". */
readonly path: string;
readonly kind: EntryKind;
/** Size in bytes (0 for directories). */
readonly size: number;
/** Last-modified time in epoch milliseconds (0 if unknown). */
readonly mtimeMs: number;
}

View File

@ -1,8 +0,0 @@
import { useMemo } from "react";
import { createDufsClient } from "./api/dufs-client.ts";
import { Gallery } from "./components/gallery.tsx";
export function App(): React.JSX.Element {
const client = useMemo(() => createDufsClient(), []);
return <Gallery client={client} />;
}

View File

@ -1,35 +0,0 @@
interface ConfirmDialogProps {
readonly message: string;
readonly confirmLabel: string;
readonly onConfirm: () => void;
readonly onCancel: () => void;
}
/** A small modal confirm used to guard destructive actions (delete). */
export function ConfirmDialog({
message,
confirmLabel,
onConfirm,
onCancel,
}: ConfirmDialogProps): React.JSX.Element {
return (
<div className="overlay" role="dialog" aria-modal="true" onClick={onCancel}>
<div
className="dialog"
onClick={(e) => {
e.stopPropagation();
}}
>
<p>{message}</p>
<div className="dialog-actions">
<button type="button" onClick={onCancel}>
Cancel
</button>
<button type="button" className="danger" onClick={onConfirm}>
{confirmLabel}
</button>
</div>
</div>
</div>
);
}

View File

@ -1,256 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Gallery } from "./gallery.tsx";
import type { DufsClient } from "../api/dufs-client.ts";
import type { DirEntry } from "../api/types.ts";
function entry(name: string, kind: "dir" | "file"): DirEntry {
return { name, path: `/${name}`, kind, size: 10, mtimeMs: 0 };
}
function makeClient(overrides: Partial<DufsClient> = {}): DufsClient {
return {
list: vi.fn(() =>
Promise.resolve([
entry("Media", "dir"),
entry("pic.jpg", "file"),
entry("clip.mp4", "file"),
entry("notes.txt", "file"),
]),
),
fileUrl: (p: string) => p,
thumbUrl: (p: string) => `/.thumbs${p}.jpg`,
upload: vi.fn(() => Promise.resolve()),
remove: vi.fn(() => Promise.resolve()),
readText: vi.fn(() => Promise.resolve("hello world")),
writeText: vi.fn(() => Promise.resolve()),
...overrides,
};
}
beforeEach(() => {
window.location.hash = "";
});
describe("Gallery", () => {
it("renders a directory listing", async () => {
render(<Gallery client={makeClient()} />);
expect(await screen.findByText("Media")).toBeInTheDocument();
expect(screen.getByText("pic.jpg")).toBeInTheDocument();
expect(screen.getByText("clip.mp4")).toBeInTheDocument();
});
it("opens an image in the viewer and closes it", async () => {
render(<Gallery client={makeClient()} />);
await userEvent.click(await screen.findByText("pic.jpg"));
await waitFor(() => {
expect(document.querySelector(".viewer-img")).not.toBeNull();
});
await userEvent.click(screen.getByLabelText("Close"));
await waitFor(() => {
expect(document.querySelector(".viewer-img")).toBeNull();
});
});
it("plays a video in the viewer", async () => {
render(<Gallery client={makeClient()} />);
await userEvent.click(await screen.findByText("clip.mp4"));
await waitFor(() => {
expect(document.querySelector("video")).not.toBeNull();
});
});
it("edits a text file and saves it", async () => {
const client = makeClient();
render(<Gallery client={client} />);
await userEvent.click(await screen.findByText("notes.txt"));
const area = await screen.findByDisplayValue("hello world");
await userEvent.clear(area);
await userEvent.type(area, "new text");
await userEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => {
expect(client.writeText).toHaveBeenCalledWith("/notes.txt", "new text");
});
});
it("deletes a file after confirming", async () => {
const client = makeClient();
render(<Gallery client={client} />);
await screen.findByText("pic.jpg");
await userEvent.click(screen.getByLabelText("Delete pic.jpg"));
await userEvent.click(screen.getByRole("button", { name: "Delete" }));
await waitFor(() => {
expect(client.remove).toHaveBeenCalledWith("/pic.jpg");
});
});
it("uploads picked files", async () => {
const client = makeClient();
const { container } = render(<Gallery client={client} />);
await screen.findByText("pic.jpg");
const input = container.querySelector<HTMLInputElement>(
'input[type="file"]',
);
expect(input).not.toBeNull();
const file = new File(["x"], "up.png", { type: "image/png" });
if (input) fireEvent.change(input, { target: { files: [file] } });
await waitFor(() => {
expect(client.upload).toHaveBeenCalled();
});
});
it("navigates between media in the viewer", async () => {
render(<Gallery client={makeClient()} />);
await userEvent.click(await screen.findByText("pic.jpg"));
await waitFor(() => {
expect(document.querySelector(".viewer-img")).not.toBeNull();
});
fireEvent.keyDown(window, { key: "ArrowRight" });
await waitFor(() => {
expect(document.querySelector("video")).not.toBeNull();
});
});
it("surfaces an upload error", async () => {
const client = makeClient({
upload: vi.fn(() => Promise.reject(new Error("uperr"))),
});
const { container } = render(<Gallery client={client} />);
await screen.findByText("pic.jpg");
const input = container.querySelector<HTMLInputElement>(
'input[type="file"]',
);
if (input) {
fireEvent.change(input, {
target: { files: [new File(["x"], "u.png")] },
});
}
expect(await screen.findByText(/uperr/)).toBeInTheDocument();
});
it("surfaces a delete error", async () => {
const client = makeClient({
remove: vi.fn(() => Promise.reject(new Error("delerr"))),
});
render(<Gallery client={client} />);
await screen.findByText("pic.jpg");
await userEvent.click(screen.getByLabelText("Delete pic.jpg"));
await userEvent.click(screen.getByRole("button", { name: "Delete" }));
expect(await screen.findByText(/delerr/)).toBeInTheDocument();
});
it("cancels a delete", async () => {
const client = makeClient();
render(<Gallery client={client} />);
await screen.findByText("pic.jpg");
await userEvent.click(screen.getByLabelText("Delete pic.jpg"));
await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(client.remove).not.toHaveBeenCalled();
});
it("shows an error when listing fails", async () => {
const client = makeClient({
list: vi.fn(() => Promise.reject(new Error("boom"))),
});
render(<Gallery client={client} />);
expect(await screen.findByText(/boom/)).toBeInTheDocument();
});
it("navigates via a breadcrumb", async () => {
render(<Gallery client={makeClient()} />);
await screen.findByText("pic.jpg");
await userEvent.click(screen.getByRole("button", { name: "cloud" }));
expect(window.location.hash).toBe("#/");
});
it("opens the file picker from the Upload button", async () => {
render(<Gallery client={makeClient()} />);
await screen.findByText("pic.jpg");
// Should not throw; exercises the hidden-input click path.
await userEvent.click(screen.getByRole("button", { name: "Upload" }));
expect(screen.getByRole("button", { name: "Upload" })).toBeInTheDocument();
});
it("steps to the previous media with ArrowLeft (wrapping)", async () => {
render(<Gallery client={makeClient()} />);
await userEvent.click(await screen.findByText("pic.jpg"));
await waitFor(() => {
expect(document.querySelector(".viewer-img")).not.toBeNull();
});
// media = [pic.jpg, clip.mp4]; from index 0, prev wraps to the video.
fireEvent.keyDown(window, { key: "ArrowLeft" });
await waitFor(() => {
expect(document.querySelector("video")).not.toBeNull();
});
});
it("shows an empty-folder message", async () => {
const client = makeClient({ list: vi.fn(() => Promise.resolve([])) });
render(<Gallery client={client} />);
expect(await screen.findByText("This folder is empty.")).toBeInTheDocument();
});
it("renders breadcrumb separators for nested paths", async () => {
window.location.hash = "#/Media/2026";
render(<Gallery client={makeClient()} />);
await screen.findByText("pic.jpg");
expect(screen.getByRole("button", { name: "Media" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "2026" })).toBeInTheDocument();
expect(document.querySelectorAll(".crumb-sep").length).toBeGreaterThan(0);
});
it("ignores an upload with no files selected", async () => {
const client = makeClient();
const { container } = render(<Gallery client={client} />);
await screen.findByText("pic.jpg");
const input = container.querySelector<HTMLInputElement>(
'input[type="file"]',
);
if (input) fireEvent.change(input, { target: { files: null } });
expect(client.upload).not.toHaveBeenCalled();
});
it("stringifies a non-Error upload rejection", async () => {
const client = makeClient({
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
upload: vi.fn(() => Promise.reject("plain-up")),
});
const { container } = render(<Gallery client={client} />);
await screen.findByText("pic.jpg");
const input = container.querySelector<HTMLInputElement>(
'input[type="file"]',
);
if (input) {
fireEvent.change(input, {
target: { files: [new File(["x"], "u.png")] },
});
}
expect(await screen.findByText("plain-up")).toBeInTheDocument();
});
it("stringifies a non-Error delete rejection", async () => {
const client = makeClient({
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
remove: vi.fn(() => Promise.reject("plain-del")),
});
render(<Gallery client={client} />);
await screen.findByText("pic.jpg");
await userEvent.click(screen.getByLabelText("Delete pic.jpg"));
await userEvent.click(screen.getByRole("button", { name: "Delete" }));
expect(await screen.findByText("plain-del")).toBeInTheDocument();
});
it("closes the text editor and reloads", async () => {
const client = makeClient();
render(<Gallery client={client} />);
await userEvent.click(await screen.findByText("notes.txt"));
await screen.findByDisplayValue("hello world");
await userEvent.click(screen.getByRole("button", { name: "Close" }));
await waitFor(() => {
expect(screen.queryByDisplayValue("hello world")).toBeNull();
});
// reload() re-invokes list (initial + after close).
expect((client.list as ReturnType<typeof vi.fn>).mock.calls.length).toBeGreaterThan(1);
});
});

View File

@ -1,170 +0,0 @@
import { useMemo, useRef, useState } from "react";
import type { DufsClient } from "../api/dufs-client.ts";
import type { DirEntry } from "../api/types.ts";
import { crumbs, isImage, isVideo } from "../lib/paths.ts";
import { useHashPath } from "../lib/use-hash-path.ts";
import { useListing } from "../hooks/use-listing.ts";
import { Grid } from "./grid.tsx";
import { MediaViewer } from "./media-viewer.tsx";
import { TextEditor } from "./text-editor.tsx";
import { ConfirmDialog } from "./confirm-dialog.tsx";
export function Gallery({ client }: { readonly client: DufsClient }): React.JSX.Element {
const [path, navigate] = useHashPath();
const { entries, loading, error, reload } = useListing(client, path);
// -1 means "no viewer open" (avoids a null branch in step()).
const [viewerIndex, setViewerIndex] = useState(-1);
const [editEntry, setEditEntry] = useState<DirEntry | null>(null);
const [deleteEntry, setDeleteEntry] = useState<DirEntry | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const fileInput = useRef<HTMLInputElement>(null);
const media = useMemo(
() => entries.filter((e) => isImage(e.name) || isVideo(e.name)),
[entries],
);
// Grid only calls this for media entries, so the entry is always in `media`.
function openMedia(entry: DirEntry): void {
setViewerIndex(media.findIndex((m) => m.path === entry.path));
}
function step(delta: number): void {
setViewerIndex((cur) => (cur + delta + media.length) % media.length);
}
function onUploadPicked(files: FileList | null): void {
if (files === null || files.length === 0) return;
setBusy(`Uploading ${files.length} file(s)…`);
void (async () => {
try {
for (const file of Array.from(files)) {
await client.upload(path, file);
}
reload();
} catch (err: unknown) {
setBusy(err instanceof Error ? err.message : String(err));
return;
}
setBusy(null);
})();
}
function confirmDelete(entry: DirEntry): void {
setDeleteEntry(null);
setBusy(`Deleting ${entry.name}…`);
client
.remove(entry.path)
.then(() => {
setBusy(null);
reload();
})
.catch((err: unknown) => {
setBusy(err instanceof Error ? err.message : String(err));
});
}
const viewerEntry = viewerIndex >= 0 ? media[viewerIndex] : null;
return (
<div className="gallery">
<header className="topbar">
<nav className="crumbs" aria-label="Breadcrumb">
{crumbs(path).map((c, i, all) => (
<span key={c.path}>
<button
type="button"
className="crumb"
onClick={() => {
navigate(c.path);
}}
>
{c.name}
</button>
{i < all.length - 1 && <span className="crumb-sep">/</span>}
</span>
))}
</nav>
<div className="tools">
{busy !== null && <span className="busy">{busy}</span>}
<button
type="button"
className="primary"
onClick={() => {
fileInput.current?.click();
}}
>
Upload
</button>
<input
ref={fileInput}
type="file"
multiple
hidden
onChange={(e) => {
onUploadPicked(e.target.files);
e.target.value = "";
}}
/>
</div>
</header>
<main className="content">
{loading && <p className="muted">Loading…</p>}
{error !== null && <p className="error">Could not load: {error}</p>}
{!loading && error === null && entries.length === 0 && (
<p className="muted">This folder is empty.</p>
)}
{!loading && error === null && entries.length > 0 && (
<Grid
client={client}
entries={entries}
onOpenDir={navigate}
onOpenMedia={openMedia}
onEditText={setEditEntry}
onDelete={setDeleteEntry}
/>
)}
</main>
{viewerEntry && (
<MediaViewer
key={viewerEntry.path}
entry={viewerEntry}
url={client.fileUrl(viewerEntry.path)}
onClose={() => {
setViewerIndex(-1);
}}
onPrev={() => {
step(-1);
}}
onNext={() => {
step(1);
}}
/>
)}
{editEntry && (
<TextEditor
client={client}
entry={editEntry}
onClose={() => {
setEditEntry(null);
reload();
}}
/>
)}
{deleteEntry && (
<ConfirmDialog
message={`Delete "${deleteEntry.name}"? This cannot be undone.`}
confirmLabel="Delete"
onConfirm={() => {
confirmDelete(deleteEntry);
}}
onCancel={() => {
setDeleteEntry(null);
}}
/>
)}
</div>
);
}

View File

@ -1,80 +0,0 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Grid } from "./grid.tsx";
import type { DufsClient } from "../api/dufs-client.ts";
import type { DirEntry } from "../api/types.ts";
function entry(name: string, kind: "dir" | "file"): DirEntry {
return { name, path: `/${name}`, kind, size: 42, mtimeMs: 0 };
}
function makeClient(): DufsClient {
return {
list: vi.fn(),
fileUrl: (p: string) => p,
thumbUrl: (p: string) => `/.thumbs${p}.jpg`,
upload: vi.fn(),
remove: vi.fn(),
readText: vi.fn(),
writeText: vi.fn(),
};
}
const entries: DirEntry[] = [
entry("Media", "dir"),
entry("pic.jpg", "file"),
entry("clip.mp4", "file"),
entry("notes.txt", "file"),
entry("data.bin", "file"),
];
function renderGrid(over: Partial<Parameters<typeof Grid>[0]> = {}) {
const props = {
client: makeClient(),
entries,
onOpenDir: vi.fn(),
onOpenMedia: vi.fn(),
onEditText: vi.fn(),
onDelete: vi.fn(),
...over,
};
render(<Grid {...props} />);
return props;
}
describe("Grid", () => {
it("activates dir, media and text entries via their tiles", async () => {
const onOpenDir = vi.fn();
const onOpenMedia = vi.fn();
const onEditText = vi.fn();
renderGrid({ onOpenDir, onOpenMedia, onEditText });
await userEvent.click(screen.getByText("Media"));
await userEvent.click(screen.getByText("pic.jpg"));
await userEvent.click(screen.getByText("notes.txt"));
// Non-media, non-text file does nothing on activate.
await userEvent.click(screen.getByText("data.bin"));
expect(onOpenDir).toHaveBeenCalledWith("/Media");
expect(onOpenMedia).toHaveBeenCalledWith(entries[1]);
expect(onEditText).toHaveBeenCalledWith(entries[3]);
});
it("renders a download link and a delete button for files", async () => {
const onDelete = vi.fn();
renderGrid({ onDelete });
const download = screen.getByLabelText("Download pic.jpg");
expect(download).toHaveAttribute("href", "/pic.jpg");
await userEvent.click(screen.getByLabelText("Delete pic.jpg"));
expect(onDelete).toHaveBeenCalledWith(entries[1]);
});
it("falls back to an icon when a thumbnail fails to load", () => {
renderGrid();
// Image thumbnail breaks -> picture fallback glyph.
fireEvent.error(screen.getByAltText("pic.jpg"));
expect(screen.getByText("🖼")).toBeInTheDocument();
// Video thumbnail breaks -> film fallback glyph.
fireEvent.error(screen.getByAltText("clip.mp4"));
expect(screen.getByText("🎞")).toBeInTheDocument();
});
});

View File

@ -1,105 +0,0 @@
import { useState } from "react";
import type { DufsClient } from "../api/dufs-client.ts";
import type { DirEntry } from "../api/types.ts";
import { humanSize, isImage, isText, isVideo } from "../lib/paths.ts";
interface GridProps {
readonly client: DufsClient;
readonly entries: readonly DirEntry[];
readonly onOpenDir: (path: string) => void;
readonly onOpenMedia: (entry: DirEntry) => void;
readonly onEditText: (entry: DirEntry) => void;
readonly onDelete: (entry: DirEntry) => void;
}
function Thumb({
client,
entry,
}: {
readonly client: DufsClient;
readonly entry: DirEntry;
}): React.JSX.Element {
const [broken, setBroken] = useState(false);
if (broken) {
return <div className="thumb-fallback">{isVideo(entry.name) ? "🎞" : "🖼"}</div>;
}
return (
<img
className="thumb-img"
src={client.thumbUrl(entry.path)}
alt={entry.name}
loading="lazy"
onError={() => {
setBroken(true);
}}
/>
);
}
export function Grid({
client,
entries,
onOpenDir,
onOpenMedia,
onEditText,
onDelete,
}: GridProps): React.JSX.Element {
return (
<ul className="grid">
{entries.map((entry) => {
const media = isImage(entry.name) || isVideo(entry.name);
const activate = (): void => {
if (entry.kind === "dir") onOpenDir(entry.path);
else if (media) onOpenMedia(entry);
else if (isText(entry.name)) onEditText(entry);
};
return (
<li key={entry.path} className={`tile tile-${entry.kind}`}>
<button type="button" className="tile-main" onClick={activate}>
<span className="tile-preview">
{entry.kind === "dir" ? (
<span className="tile-icon">📁</span>
) : media ? (
<>
<Thumb client={client} entry={entry} />
{isVideo(entry.name) && <span className="play-badge">▶</span>}
</>
) : (
<span className="tile-icon">{isText(entry.name) ? "📝" : "📄"}</span>
)}
</span>
<span className="tile-name" title={entry.name}>
{entry.name}
</span>
{entry.kind === "file" && (
<span className="tile-size">{humanSize(entry.size)}</span>
)}
</button>
{entry.kind === "file" && (
<div className="tile-actions">
<a
className="tile-act"
href={client.fileUrl(entry.path)}
download
aria-label={`Download ${entry.name}`}
>
⭳
</a>
<button
type="button"
className="tile-act danger"
aria-label={`Delete ${entry.name}`}
onClick={() => {
onDelete(entry);
}}
>
🗑
</button>
</div>
)}
</li>
);
})}
</ul>
);
}

View File

@ -1,99 +0,0 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MediaViewer } from "./media-viewer.tsx";
import type { DirEntry } from "../api/types.ts";
function mk(name: string): DirEntry {
return { name, path: `/${name}`, kind: "file", size: 1, mtimeMs: 0 };
}
describe("MediaViewer", () => {
it("shows an image and toggles zoom on click", async () => {
render(
<MediaViewer
entry={mk("a.jpg")}
url="/a.jpg"
onClose={vi.fn()}
onPrev={vi.fn()}
onNext={vi.fn()}
/>,
);
const img = screen.getByAltText("a.jpg");
expect(img.className).not.toContain("zoomed");
await userEvent.click(img);
expect(img.className).toContain("zoomed");
});
it("renders a <video> for video files and does not close on video click", () => {
const onClose = vi.fn();
render(
<MediaViewer
entry={mk("v.mp4")}
url="/v.mp4"
onClose={onClose}
onPrev={vi.fn()}
onNext={vi.fn()}
/>,
);
const video = document.querySelector("video");
expect(video).not.toBeNull();
if (video) fireEvent.click(video);
// stopPropagation keeps the stage's onClose from firing.
expect(onClose).not.toHaveBeenCalled();
});
it("offers a download for non-media files", () => {
render(
<MediaViewer
entry={mk("x.bin")}
url="/x.bin"
onClose={vi.fn()}
onPrev={vi.fn()}
onNext={vi.fn()}
/>,
);
expect(screen.getByText("Download")).toBeInTheDocument();
});
it("responds to keyboard: Esc/←/→", () => {
const onClose = vi.fn();
const onPrev = vi.fn();
const onNext = vi.fn();
render(
<MediaViewer
entry={mk("a.jpg")}
url="/a.jpg"
onClose={onClose}
onPrev={onPrev}
onNext={onNext}
/>,
);
fireEvent.keyDown(window, { key: "ArrowRight" });
fireEvent.keyDown(window, { key: "ArrowLeft" });
fireEvent.keyDown(window, { key: "Escape" });
fireEvent.keyDown(window, { key: "a" });
expect(onNext).toHaveBeenCalledOnce();
expect(onPrev).toHaveBeenCalledOnce();
expect(onClose).toHaveBeenCalledOnce();
});
it("nav buttons and stage click work", async () => {
const onClose = vi.fn();
const onPrev = vi.fn();
const onNext = vi.fn();
render(
<MediaViewer
entry={mk("a.jpg")}
url="/a.jpg"
onClose={onClose}
onPrev={onPrev}
onNext={onNext}
/>,
);
await userEvent.click(screen.getByLabelText("Previous"));
await userEvent.click(screen.getByLabelText("Next"));
expect(onPrev).toHaveBeenCalledOnce();
expect(onNext).toHaveBeenCalledOnce();
});
});

View File

@ -1,98 +0,0 @@
import { useEffect, useState } from "react";
import type { DirEntry } from "../api/types.ts";
import { isImage, isVideo } from "../lib/paths.ts";
interface MediaViewerProps {
readonly entry: DirEntry;
readonly url: string;
readonly onClose: () => void;
readonly onPrev: () => void;
readonly onNext: () => void;
}
/** Full-screen viewer: image lightbox (click-to-zoom) or an inline video player. */
export function MediaViewer({
entry,
url,
onClose,
onPrev,
onNext,
}: MediaViewerProps): React.JSX.Element {
// Zoom resets automatically per media because the parent keys this component
// by path, remounting it on navigation.
const [zoomed, setZoomed] = useState(false);
useEffect(() => {
function onKey(e: KeyboardEvent): void {
if (e.key === "Escape") onClose();
else if (e.key === "ArrowLeft") onPrev();
else if (e.key === "ArrowRight") onNext();
}
window.addEventListener("keydown", onKey);
return () => {
window.removeEventListener("keydown", onKey);
};
}, [onClose, onPrev, onNext]);
const video = isVideo(entry.name);
return (
<div className="overlay viewer" role="dialog" aria-modal="true">
<button
type="button"
className="viewer-close"
aria-label="Close"
onClick={onClose}
>
✕
</button>
<button
type="button"
className="viewer-nav prev"
aria-label="Previous"
onClick={onPrev}
>
‹
</button>
<div className="viewer-stage" onClick={onClose}>
{video ? (
<video
className="viewer-video"
src={url}
controls
autoPlay
onClick={(e) => {
e.stopPropagation();
}}
/>
) : isImage(entry.name) ? (
<img
className={zoomed ? "viewer-img zoomed" : "viewer-img"}
src={url}
alt={entry.name}
onClick={(e) => {
e.stopPropagation();
setZoomed((z) => !z);
}}
/>
) : (
<div className="viewer-fallback">
<p>{entry.name}</p>
<a href={url} download>
Download
</a>
</div>
)}
</div>
<button
type="button"
className="viewer-nav next"
aria-label="Next"
onClick={onNext}
>
›
</button>
<div className="viewer-caption">{entry.name}</div>
</div>
);
}

View File

@ -1,118 +0,0 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen, waitFor, act } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { TextEditor } from "./text-editor.tsx";
import type { DufsClient } from "../api/dufs-client.ts";
import type { DirEntry } from "../api/types.ts";
const entry: DirEntry = {
name: "n.txt",
path: "/n.txt",
kind: "file",
size: 3,
mtimeMs: 0,
};
function client(over: Partial<DufsClient>): DufsClient {
return {
list: vi.fn(),
fileUrl: (p) => p,
thumbUrl: (p) => p,
upload: vi.fn(),
remove: vi.fn(),
readText: vi.fn(() => Promise.resolve("body")),
writeText: vi.fn(() => Promise.resolve()),
...over,
};
}
describe("TextEditor", () => {
it("loads, edits and saves", async () => {
const c = client({});
render(<TextEditor client={c} entry={entry} onClose={vi.fn()} />);
const area = await screen.findByDisplayValue("body");
await userEvent.clear(area);
await userEvent.type(area, "changed");
await userEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => {
expect(c.writeText).toHaveBeenCalledWith("/n.txt", "changed");
});
expect(await screen.findByText("Saved")).toBeInTheDocument();
});
it("shows a load error", async () => {
const c = client({ readText: vi.fn(() => Promise.reject(new Error("nope"))) });
render(<TextEditor client={c} entry={entry} onClose={vi.fn()} />);
expect(await screen.findByText("nope")).toBeInTheDocument();
});
it("shows a save error", async () => {
const c = client({
writeText: vi.fn(() => Promise.reject(new Error("wfail"))),
});
render(<TextEditor client={c} entry={entry} onClose={vi.fn()} />);
await screen.findByDisplayValue("body");
await userEvent.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText("wfail")).toBeInTheDocument();
});
it("stringifies a non-Error load rejection", async () => {
const c = client({
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
readText: vi.fn(() => Promise.reject("plain-load-failure")),
});
render(<TextEditor client={c} entry={entry} onClose={vi.fn()} />);
expect(await screen.findByText("plain-load-failure")).toBeInTheDocument();
});
it("stringifies a non-Error save rejection", async () => {
const c = client({
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
writeText: vi.fn(() => Promise.reject("plain-save-failure")),
});
render(<TextEditor client={c} entry={entry} onClose={vi.fn()} />);
await screen.findByDisplayValue("body");
await userEvent.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText("plain-save-failure")).toBeInTheDocument();
});
it("closes", async () => {
const onClose = vi.fn();
render(<TextEditor client={client({})} entry={entry} onClose={onClose} />);
await screen.findByDisplayValue("body");
await userEvent.click(screen.getByRole("button", { name: "Close" }));
expect(onClose).toHaveBeenCalledOnce();
});
it("ignores a load that resolves after unmount", async () => {
let settle: (v: string) => void = () => undefined;
const pending = new Promise<string>((resolve) => {
settle = resolve;
});
const c = client({ readText: vi.fn(() => pending) });
const { unmount } = render(
<TextEditor client={c} entry={entry} onClose={vi.fn()} />,
);
unmount();
await act(async () => {
settle("late");
await pending;
});
});
it("ignores a load that rejects after unmount", async () => {
let fail: (e: unknown) => void = () => undefined;
const pending = new Promise<string>((_, reject) => {
fail = reject;
});
const c = client({ readText: vi.fn(() => pending) });
const { unmount } = render(
<TextEditor client={c} entry={entry} onClose={vi.fn()} />,
);
unmount();
await act(async () => {
fail(new Error("late"));
await pending.catch(() => undefined);
});
});
});

View File

@ -1,94 +0,0 @@
import { useEffect, useState } from "react";
import type { DufsClient } from "../api/dufs-client.ts";
import type { DirEntry } from "../api/types.ts";
interface TextEditorProps {
readonly client: DufsClient;
readonly entry: DirEntry;
readonly onClose: () => void;
}
type Status = "loading" | "ready" | "saving" | "error";
/** A minimal editor for .txt/.md files: GET the text, edit, PUT it back. */
export function TextEditor({
client,
entry,
onClose,
}: TextEditorProps): React.JSX.Element {
const [text, setText] = useState("");
const [status, setStatus] = useState<Status>("loading");
const [message, setMessage] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
client
.readText(entry.path)
.then((content) => {
if (cancelled) return;
setText(content);
setStatus("ready");
})
.catch((err: unknown) => {
if (cancelled) return;
setMessage(err instanceof Error ? err.message : String(err));
setStatus("error");
});
return () => {
cancelled = true;
};
}, [client, entry.path]);
function save(): void {
setStatus("saving");
setMessage(null);
client
.writeText(entry.path, text)
.then(() => {
setStatus("ready");
setMessage("Saved");
})
.catch((err: unknown) => {
setMessage(err instanceof Error ? err.message : String(err));
setStatus("error");
});
}
return (
<div className="overlay" role="dialog" aria-modal="true">
<div
className="dialog editor"
onClick={(e) => {
e.stopPropagation();
}}
>
<header className="editor-head">
<span>{entry.name}</span>
<span className="editor-status">{message ?? status}</span>
</header>
<textarea
className="editor-area"
value={text}
spellCheck={false}
disabled={status === "loading"}
onChange={(e) => {
setText(e.target.value);
}}
/>
<div className="dialog-actions">
<button type="button" onClick={onClose}>
Close
</button>
<button
type="button"
className="primary"
disabled={status === "loading" || status === "saving"}
onClick={save}
>
Save
</button>
</div>
</div>
</div>
);
}

View File

@ -1,99 +0,0 @@
import { describe, it, expect, vi } from "vitest";
import { renderHook, waitFor, act } from "@testing-library/react";
import { useListing } from "./use-listing.ts";
import type { DufsClient } from "../api/dufs-client.ts";
import type { DirEntry } from "../api/types.ts";
function entry(name: string, kind: "dir" | "file"): DirEntry {
return { name, path: `/${name}`, kind, size: 0, mtimeMs: 0 };
}
function mkClient(list: DufsClient["list"]): DufsClient {
return {
list,
fileUrl: (p: string) => p,
thumbUrl: (p: string) => p,
upload: vi.fn(),
remove: vi.fn(),
readText: vi.fn(),
writeText: vi.fn(),
};
}
describe("useListing", () => {
it("loads entries and hides app-owned files", async () => {
const client = mkClient(() =>
Promise.resolve([
entry("index.html", "file"),
entry(".thumbs", "dir"),
entry("real.jpg", "file"),
]),
);
const { result } = renderHook(() => useListing(client, "/"));
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
expect(result.current.entries.map((e) => e.name)).toEqual(["real.jpg"]);
expect(result.current.error).toBeNull();
});
it("exposes an Error message", async () => {
const client = mkClient(() => Promise.reject(new Error("boom")));
const { result } = renderHook(() => useListing(client, "/"));
await waitFor(() => {
expect(result.current.error).toBe("boom");
});
});
it("stringifies a non-Error rejection", async () => {
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
const client = mkClient(() => Promise.reject("weird"));
const { result } = renderHook(() => useListing(client, "/"));
await waitFor(() => {
expect(result.current.error).toBe("weird");
});
});
it("reload re-fetches the current path", async () => {
const list = vi.fn(() => Promise.resolve([entry("a.jpg", "file")]));
const client = mkClient(list);
const { result } = renderHook(() => useListing(client, "/"));
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
act(() => {
result.current.reload();
});
await waitFor(() => {
expect(list).toHaveBeenCalledTimes(2);
});
});
it("ignores a resolution that arrives after unmount", async () => {
let settle: (v: DirEntry[]) => void = () => undefined;
const pending = new Promise<DirEntry[]>((resolve) => {
settle = resolve;
});
const client = mkClient(() => pending);
const { unmount } = renderHook(() => useListing(client, "/"));
unmount();
await act(async () => {
settle([entry("late.jpg", "file")]);
await pending;
});
});
it("ignores a rejection that arrives after unmount", async () => {
let fail: (e: unknown) => void = () => undefined;
const pending = new Promise<DirEntry[]>((_, reject) => {
fail = reject;
});
const client = mkClient(() => pending);
const { unmount } = renderHook(() => useListing(client, "/"));
unmount();
await act(async () => {
fail(new Error("late"));
await pending.catch(() => undefined);
});
});
});

View File

@ -1,73 +0,0 @@
import { useCallback, useEffect, useState } from "react";
import type { DufsClient } from "../api/dufs-client.ts";
import type { DirEntry } from "../api/types.ts";
/** Names the app owns in the cloud root — hidden from the browsing grid. */
const APP_FILES = new Set([
"index.html",
"assets",
"favicon.ico",
"vite.svg",
".thumbs",
"_thumbs",
]);
export interface Listing {
readonly entries: readonly DirEntry[];
readonly loading: boolean;
readonly error: string | null;
readonly reload: () => void;
}
interface Loaded {
readonly path: string;
readonly entries: readonly DirEntry[];
readonly error: string | null;
}
export function useListing(client: DufsClient, path: string): Listing {
const [loaded, setLoaded] = useState<Loaded>({
path: "",
entries: [],
error: null,
});
const [nonce, setNonce] = useState(0);
const reload = useCallback(() => {
setNonce((n) => n + 1);
}, []);
useEffect(() => {
let cancelled = false;
client
.list(path)
.then((all) => {
if (cancelled) return;
setLoaded({
path,
entries: all.filter((e) => !APP_FILES.has(e.name)),
error: null,
});
})
.catch((err: unknown) => {
if (cancelled) return;
setLoaded({
path,
entries: [],
error: err instanceof Error ? err.message : String(err),
});
});
return () => {
cancelled = true;
};
}, [client, path, nonce]);
// Loading is derived (no synchronous setState in the effect): we are loading
// whenever the last completed load is for a different path than the current.
const loading = loaded.path !== path;
return {
entries: loading ? [] : loaded.entries,
loading,
error: loading ? null : loaded.error,
reload,
};
}

View File

@ -1,343 +0,0 @@
:root {
--bg: #ffffff;
--fg: #1c1f24;
--muted: #5b6570;
--card: #f4f6f8;
--border: #d8dee4;
--accent: #2f6feb;
--danger: #cf222e;
--overlay: rgba(0, 0, 0, 0.82);
color-scheme: light dark;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0d1117;
--fg: #e6edf3;
--muted: #9198a1;
--card: #161b22;
--border: #30363d;
--accent: #589bff;
--danger: #f85149;
--overlay: rgba(0, 0, 0, 0.9);
}
}
* {
box-sizing: border-box;
}
html,
body,
#root {
margin: 0;
height: 100%;
}
body {
background: var(--bg);
color: var(--fg);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
Arial, sans-serif;
-webkit-font-smoothing: antialiased;
}
button {
font: inherit;
color: inherit;
cursor: pointer;
}
.gallery {
display: flex;
flex-direction: column;
min-height: 100%;
}
/* top bar */
.topbar {
position: sticky;
top: 0;
z-index: 5;
display: flex;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
padding: 0.6rem 1rem;
background: var(--bg);
border-bottom: 1px solid var(--border);
}
.crumbs {
flex: 1 1 auto;
min-width: 0;
overflow-x: auto;
white-space: nowrap;
}
.crumb {
background: none;
border: none;
color: var(--accent);
padding: 0.15rem 0.2rem;
}
.crumb:hover {
text-decoration: underline;
}
.crumb-sep {
color: var(--muted);
margin: 0 0.1rem;
}
.tools {
display: flex;
align-items: center;
gap: 0.6rem;
}
.busy {
color: var(--muted);
font-size: 0.85rem;
}
button.primary {
background: var(--accent);
color: #fff;
border: none;
border-radius: 8px;
padding: 0.4rem 0.9rem;
}
button.primary:disabled {
opacity: 0.5;
cursor: default;
}
.content {
flex: 1 1 auto;
padding: 1rem;
}
.muted {
color: var(--muted);
}
.error {
color: var(--danger);
}
/* grid */
.grid {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.8rem;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
}
.tile {
position: relative;
background: var(--card);
border: 1px solid var(--border);
border-radius: 10px;
overflow: hidden;
}
.tile-main {
display: flex;
flex-direction: column;
width: 100%;
border: none;
background: none;
padding: 0;
text-align: left;
}
.tile-preview {
position: relative;
display: grid;
place-items: center;
aspect-ratio: 1 / 1;
background: color-mix(in srgb, var(--card) 60%, #000 6%);
overflow: hidden;
}
.thumb-img {
width: 100%;
height: 100%;
object-fit: cover;
}
.thumb-fallback,
.tile-icon {
font-size: 2.4rem;
}
.play-badge {
position: absolute;
bottom: 0.35rem;
right: 0.4rem;
background: rgba(0, 0, 0, 0.6);
color: #fff;
border-radius: 50%;
width: 1.6rem;
height: 1.6rem;
display: grid;
place-items: center;
font-size: 0.8rem;
}
.tile-name {
padding: 0.4rem 0.5rem 0.1rem;
font-size: 0.82rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tile-size {
padding: 0 0.5rem 0.45rem;
font-size: 0.72rem;
color: var(--muted);
}
.tile-actions {
position: absolute;
top: 0.3rem;
right: 0.3rem;
display: flex;
gap: 0.25rem;
opacity: 0;
transition: opacity 0.12s;
}
.tile:hover .tile-actions,
.tile:focus-within .tile-actions {
opacity: 1;
}
.tile-act {
background: rgba(0, 0, 0, 0.55);
color: #fff;
border: none;
border-radius: 6px;
padding: 0.15rem 0.35rem;
font-size: 0.8rem;
text-decoration: none;
line-height: 1;
}
.tile-act.danger:hover {
background: var(--danger);
}
/* overlays / dialogs */
.overlay {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
background: var(--overlay);
}
.dialog {
background: var(--bg);
border: 1px solid var(--border);
border-radius: 12px;
padding: 1.1rem 1.2rem;
max-width: min(92vw, 40rem);
width: 100%;
}
.dialog-actions {
display: flex;
justify-content: flex-end;
gap: 0.6rem;
margin-top: 1rem;
}
.dialog-actions button {
border: 1px solid var(--border);
background: var(--card);
border-radius: 8px;
padding: 0.4rem 0.9rem;
}
.dialog-actions .danger {
background: var(--danger);
color: #fff;
border-color: var(--danger);
}
.dialog-actions .primary {
background: var(--accent);
color: #fff;
border-color: var(--accent);
}
/* editor */
.editor {
display: flex;
flex-direction: column;
height: min(80vh, 44rem);
}
.editor-head {
display: flex;
justify-content: space-between;
margin-bottom: 0.6rem;
font-size: 0.9rem;
}
.editor-status {
color: var(--muted);
}
.editor-area {
flex: 1 1 auto;
resize: none;
width: 100%;
background: var(--card);
color: var(--fg);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.7rem;
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
font-size: 0.9rem;
}
/* viewer */
.viewer {
flex-direction: column;
}
.viewer-stage {
position: absolute;
inset: 0;
display: grid;
place-items: center;
padding: 3rem 1rem;
}
.viewer-img {
max-width: 96vw;
max-height: 88vh;
object-fit: contain;
cursor: zoom-in;
}
.viewer-img.zoomed {
max-width: none;
max-height: none;
cursor: zoom-out;
}
.viewer-video {
max-width: 96vw;
max-height: 88vh;
}
.viewer-fallback {
color: #fff;
text-align: center;
}
.viewer-close,
.viewer-nav {
position: absolute;
z-index: 2;
background: rgba(0, 0, 0, 0.5);
color: #fff;
border: none;
border-radius: 50%;
width: 2.6rem;
height: 2.6rem;
font-size: 1.4rem;
}
.viewer-close {
top: 0.8rem;
right: 0.8rem;
}
.viewer-nav.prev {
left: 0.6rem;
top: 50%;
transform: translateY(-50%);
}
.viewer-nav.next {
right: 0.6rem;
top: 50%;
transform: translateY(-50%);
}
.viewer-caption {
position: absolute;
bottom: 0.8rem;
left: 0;
right: 0;
text-align: center;
color: #fff;
font-size: 0.85rem;
pointer-events: none;
}

View File

@ -1,83 +0,0 @@
import { describe, it, expect } from "vitest";
import {
basename,
crumbs,
encodePath,
extname,
humanSize,
isImage,
isText,
isVideo,
joinPath,
normalize,
parentPath,
} from "./paths.ts";
describe("extname", () => {
it("returns lower-case extension without dot", () => {
expect(extname("PIC.JPG")).toBe("jpg");
expect(extname("a.tar.gz")).toBe("gz");
});
it("returns empty for no/edge extensions", () => {
expect(extname("README")).toBe("");
expect(extname(".hidden")).toBe("");
expect(extname("trailing.")).toBe("");
});
});
describe("type predicates", () => {
it("classifies images, videos and text", () => {
expect(isImage("a.png")).toBe(true);
expect(isImage("a.mp4")).toBe(false);
expect(isVideo("a.mkv")).toBe(true);
expect(isVideo("a.png")).toBe(false);
expect(isText("notes.md")).toBe(true);
expect(isText("a.bin")).toBe(false);
});
});
describe("normalize / join / parent / basename", () => {
it("normalizes dots and slashes", () => {
expect(normalize("/a//b/./c")).toBe("/a/b/c");
expect(normalize("/a/b/../c")).toBe("/a/c");
expect(normalize("")).toBe("/");
expect(normalize("/")).toBe("/");
});
it("joins and finds parents / basenames", () => {
expect(joinPath("/a/b", "c.jpg")).toBe("/a/b/c.jpg");
expect(parentPath("/a/b/c.jpg")).toBe("/a/b");
expect(parentPath("/")).toBe("/");
expect(parentPath("/only")).toBe("/");
expect(basename("/a/b/c.jpg")).toBe("c.jpg");
expect(basename("/")).toBe("/");
});
});
describe("encodePath", () => {
it("encodes each segment", () => {
expect(encodePath("/Media/2026/07/a b.jpg")).toBe("/Media/2026/07/a%20b.jpg");
expect(encodePath("/")).toBe("/");
});
});
describe("crumbs", () => {
it("builds breadcrumb trail", () => {
expect(crumbs("/")).toEqual([{ name: "cloud", path: "/" }]);
expect(crumbs("/Media/2026")).toEqual([
{ name: "cloud", path: "/" },
{ name: "Media", path: "/Media" },
{ name: "2026", path: "/Media/2026" },
]);
});
});
describe("humanSize", () => {
it("formats bytes across units", () => {
expect(humanSize(512)).toBe("512 B");
expect(humanSize(1536)).toBe("1.5 KB");
expect(humanSize(5 * 1024 * 1024)).toBe("5.0 MB");
expect(humanSize(3 * 1024 * 1024 * 1024)).toBe("3.0 GB");
expect(humanSize(2 * 1024 ** 4)).toBe("2.0 TB");
expect(humanSize(50 * 1024)).toBe("50 KB");
});
});

View File

@ -1,96 +0,0 @@
/** Path and file-type helpers for cloud paths (absolute, from the cloud root). */
const IMAGE_EXTS = new Set([
"jpg", "jpeg", "png", "gif", "bmp", "tiff", "tif", "webp",
"heic", "heif", "avif", "svg",
]);
const VIDEO_EXTS = new Set([
"mp4", "avi", "mkv", "mov", "wmv", "flv", "webm", "m4v",
"3gp", "ogv", "mpg", "mpeg", "mts", "m2ts", "vob",
]);
const TEXT_EXTS = new Set([
"txt", "md", "markdown", "log", "csv", "json", "yaml", "yml",
"ini", "conf", "sh", "toml", "xml",
]);
/** Lower-case extension without the dot, or "" if none. */
export function extname(name: string): string {
const dot = name.lastIndexOf(".");
if (dot <= 0 || dot === name.length - 1) return "";
return name.slice(dot + 1).toLowerCase();
}
export function isImage(name: string): boolean {
return IMAGE_EXTS.has(extname(name));
}
export function isVideo(name: string): boolean {
return VIDEO_EXTS.has(extname(name));
}
export function isText(name: string): boolean {
return TEXT_EXTS.has(extname(name));
}
/** Normalize to a leading-slash, no-trailing-slash absolute path ("/" stays "/"). */
export function normalize(path: string): string {
const parts = path.split("/").filter((p) => p.length > 0 && p !== ".");
const out: string[] = [];
for (const p of parts) {
if (p === "..") out.pop();
else out.push(p);
}
return "/" + out.join("/");
}
export function joinPath(base: string, name: string): string {
return normalize(`${base}/${name}`);
}
export function parentPath(path: string): string {
const n = normalize(path);
if (n === "/") return "/";
return normalize(n.slice(0, n.lastIndexOf("/")) || "/");
}
export function basename(path: string): string {
const n = normalize(path);
if (n === "/") return "/";
return n.slice(n.lastIndexOf("/") + 1);
}
/** Encode an absolute path into a same-origin URL, encoding each segment. */
export function encodePath(path: string): string {
return (
"/" +
normalize(path)
.split("/")
.filter((p) => p.length > 0)
.map((p) => encodeURIComponent(p))
.join("/")
);
}
/** Breadcrumb segments for a path: [{name, path}], root first. */
export function crumbs(path: string): readonly { name: string; path: string }[] {
const n = normalize(path);
const out: { name: string; path: string }[] = [{ name: "cloud", path: "/" }];
if (n === "/") return out;
let acc = "";
for (const seg of n.split("/").filter((p) => p.length > 0)) {
acc += "/" + seg;
out.push({ name: seg, path: acc });
}
return out;
}
/** Human-readable byte size. */
export function humanSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
let v = bytes / 1024;
let unit = "KB";
for (const next of ["MB", "GB", "TB"]) {
if (v < 1024) break;
v /= 1024;
unit = next;
}
return `${v.toFixed(v < 10 ? 1 : 0)} ${unit}`;
}

View File

@ -1,32 +0,0 @@
import { useCallback, useSyncExternalStore } from "react";
import { normalize } from "./paths.ts";
/**
* Hash-based routing: the current directory lives in the URL hash (e.g.
* `#/Media/2026/07`). Using the hash keeps the HTTP path at "/", so dufs
* `render-spa` always serves the app shell and deep links never 404.
*/
function readHash(): string {
const raw = window.location.hash.replace(/^#/, "");
return normalize(raw === "" ? "/" : raw);
}
/** Server-render snapshot: there is no hash off the client, so default to root. */
export function serverPath(): string {
return "/";
}
function subscribe(onChange: () => void): () => void {
window.addEventListener("hashchange", onChange);
return () => {
window.removeEventListener("hashchange", onChange);
};
}
export function useHashPath(): readonly [string, (path: string) => void] {
const path = useSyncExternalStore(subscribe, readHash, serverPath);
const navigate = useCallback((next: string) => {
window.location.hash = normalize(next);
}, []);
return [path, navigate];
}

View File

@ -1,13 +0,0 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./app.tsx";
import "./index.css";
const root = document.getElementById("root");
if (root !== null) {
createRoot(root).render(
<StrictMode>
<App />
</StrictMode>,
);
}

View File

@ -1,84 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor, act } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { serverPath, useHashPath } from "./lib/use-hash-path.ts";
import { ConfirmDialog } from "./components/confirm-dialog.tsx";
import { App } from "./app.tsx";
function Harness(): React.JSX.Element {
const [path, navigate] = useHashPath();
return (
<div>
<span data-testid="p">{path}</span>
<button
type="button"
onClick={() => {
navigate("/x/y");
}}
>
go
</button>
</div>
);
}
describe("useHashPath", () => {
beforeEach(() => {
window.location.hash = "";
});
it("reflects and updates the hash", async () => {
render(<Harness />);
expect(screen.getByTestId("p").textContent).toBe("/");
await userEvent.click(screen.getByText("go"));
// hashchange may not auto-fire in jsdom; nudge it.
act(() => {
window.dispatchEvent(new HashChangeEvent("hashchange"));
});
await waitFor(() => {
expect(screen.getByTestId("p").textContent).toBe("/x/y");
});
});
it("defaults to root for the server snapshot", () => {
expect(serverPath()).toBe("/");
});
});
describe("ConfirmDialog", () => {
it("confirms, cancels and cancels on overlay click", async () => {
const onConfirm = vi.fn();
const onCancel = vi.fn();
const { rerender } = render(
<ConfirmDialog
message="Sure?"
confirmLabel="Yes"
onConfirm={onConfirm}
onCancel={onCancel}
/>,
);
await userEvent.click(screen.getByRole("button", { name: "Yes" }));
expect(onConfirm).toHaveBeenCalledOnce();
await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(onCancel).toHaveBeenCalledOnce();
rerender(
<ConfirmDialog
message="Sure?"
confirmLabel="Yes"
onConfirm={onConfirm}
onCancel={onCancel}
/>,
);
// clicking the dialog body should NOT cancel (stopPropagation)
await userEvent.click(screen.getByText("Sure?"));
expect(onCancel).toHaveBeenCalledOnce();
});
});
describe("App", () => {
it("mounts the gallery", async () => {
globalThis.fetch = vi.fn(() => Promise.reject(new Error("offline")));
render(<App />);
expect(
await screen.findByRole("button", { name: "Upload" }),
).toBeInTheDocument();
});
});

View File

@ -1,10 +0,0 @@
import "@testing-library/jest-dom";
import { vi, beforeEach } from "vitest";
beforeEach(() => {
vi.clearAllMocks();
});
// jsdom lacks object-URL support; several flows touch it.
URL.createObjectURL = vi.fn(() => "blob:mock");
URL.revokeObjectURL = vi.fn();

View File

@ -1,23 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "esnext",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"jsx": "react-jsx",
"types": ["vite/client", "vitest/globals"],
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"strict": true,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src", "vite.config.ts"]
}

View File

@ -1,22 +0,0 @@
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
// base: "./" so the built asset URLs are relative. The app is served by dufs
// with `render-spa` from the cloud root, and uses HashRouter, so the document
// path is always "/" and "./assets/..." resolves to "/assets/...".
export default defineConfig({
base: "./",
plugins: [react()],
server: { port: 5273 },
test: {
environment: "jsdom",
globals: true,
setupFiles: ["./src/test/setup.ts"],
coverage: {
provider: "v8",
include: ["src/**/*.{ts,tsx}"],
exclude: ["src/main.tsx", "src/test/**", "src/**/*.d.ts"],
thresholds: { statements: 100, branches: 100, functions: 100, lines: 100 },
},
},
});

View File

@ -0,0 +1,17 @@
{
"title": "Extract dufs cloud (web + app + scripts) to github.com/kuhyx/dufs-cloud",
"objective": "Move the dufs web gallery, the Flutter mobile app, and the dufs/cloud setup scripts out of this monorepo into a new public repo with preserved git history, CI, 100% coverage and aggressive linting for both apps, then remove them here and leave a pointer, without breaking the live media-cloud-sync systemd units.",
"acceptance_criteria": [
"New public repo github.com/kuhyx/dufs-cloud exists with web/, app/, scripts/ and preserved history (original dufs commits present).",
"CI at .github/workflows/ci.yml runs web (lint + 100% vitest coverage + build) and app (flutter analyze --fatal-infos + test + 100% line-coverage gate).",
"The live media-cloud-sync.service and its thumbnails drop-in run the scripts from ~/dufs-cloud/scripts/ and the service still succeeds.",
"cloud_gallery/ and the 6 scripts are git rm'd from testsAndMisc; CLAUDE.md and the phone_focus_mode comment point to the new repo.",
"No active unit or executed script in testsAndMisc still references the removed files."
],
"out_of_scope": [
"KeePass sync scripts (separate feature, stay in testsAndMisc)",
"Deleting the old ~/dufs_client checkout",
"The Phase B media filter/sort/move/multi-download features (done after this)"
],
"verifier": "flutter analyze --fatal-infos + flutter test --coverage (100%); pnpm lint + coverage + build; systemctl re-point verification (ExecMainStatus=0); gh repo view (PUBLIC); grep for dangling references"
}

View File

@ -0,0 +1,38 @@
{
"intent": "Extract the dufs web gallery, the Flutter app, and the dufs/cloud setup scripts into a new public repo github.com/kuhyx/dufs-cloud (with history), then remove them from this monorepo, leaving a pointer.",
"scope": [
"Remove cloud_gallery/ and the 6 dufs/cloud scripts + dufs.service template",
"Update phone_focus_mode/config.sh comment and CLAUDE.md pointer",
"Non-goal: KeePass sync scripts stay (separate feature)"
],
"changes": [
"git rm cloud_gallery/ and linux_configuration/.../{setup_dufs_cloud,setup_cloud_gallery,setup_media_cloud_sync,generate_thumbnails,sync_media_to_cloud,import_media_archives}.sh + features/systemd/dufs.service.",
"These now live (with full git history) in github.com/kuhyx/dufs-cloud under web/, app/, scripts/; the live media-cloud-sync systemd units were re-pointed to ~/dufs-cloud/scripts/.",
"phone_focus_mode/config.sh: dufs_client whitelist comment now points at the new repo.",
"CLAUDE.md: added dufs-cloud to the extracted-repos list."
],
"verification": [
{
"command": "systemctl (re-pointed units)",
"result": "pass",
"evidence": "media-cloud-sync.service ExecStart=/home/kuhy/dufs-cloud/scripts/sync_media_to_cloud.sh; ran once with ExecMainStatus=0; timer+path active"
},
{
"command": "new repo CI locally (web + app)",
"result": "pass",
"evidence": "web: 62 tests 100% cov, lint clean, build ok; app: 36 tests 100% line cov, flutter analyze --fatal-infos clean"
},
{
"command": "grep remaining references",
"result": "pass",
"evidence": "only comments/docs (historical HTML, inactive legacy keepass templates) reference the removed names"
}
],
"risks": [
"The live media-cloud-sync units depend on ~/dufs-cloud being present; if that checkout is deleted, the timer's ExecStart fails (path watcher/timer stay, sync no-ops).",
"The docs/explanations HTML still references the old script paths (historical record, left intentionally)."
],
"rollback": [
"git revert this commit restores the scripts in the monorepo; re-point the systemd units back with sed to the testsAndMisc paths and daemon-reload."
]
}

View File

@ -1,121 +0,0 @@
#!/bin/bash
# setup_cloud_gallery.sh — build and deploy the React media-gallery SPA so it
# becomes the UI of the dufs cloud (served same-origin behind the existing auth).
#
# It builds cloud_gallery/ (Vite), copies the static build into the dufs serve
# path, turns on dufs `render-spa`, generates thumbnails, and wires thumbnail
# regeneration into the Phase-2 media sync. Run on the dufs host (the PC).
#
# The SPA lists directories with WebDAV PROPFIND and streams files with GET, so
# it works under render-spa without disturbing the KeePass sync (file GET/PUT/
# ?hash are unaffected — verified).
set -euo pipefail
HERE="$(dirname "$(readlink -f "$0")")"
readonly HERE
REPO_ROOT="$(git -C "$HERE" rev-parse --show-toplevel)"
readonly REPO_ROOT
readonly GALLERY_DIR="$REPO_ROOT/cloud_gallery"
readonly THUMBS_SCRIPT="$REPO_ROOT/linux_configuration/scripts/single_use/utils/generate_thumbnails.sh"
readonly DUFS_YAML="$HOME/.config/dufs/dufs.yaml"
C() { printf '\033[1;34m[cloud-gallery]\033[0m %s\n' "$*"; }
OK() { printf '\033[1;32m ✓\033[0m %s\n' "$*"; }
WARN() { printf '\033[1;33m !\033[0m %s\n' "$*"; }
die() { printf '\033[1;31m[cloud-gallery] ERROR:\033[0m %s\n' "$*" >&2; exit 1; }
cloud_root() {
local sp=""
[[ -f "$DUFS_YAML" ]] && sp="$(sed -nE 's/^serve-path:[[:space:]]*//p' "$DUFS_YAML" | head -1)"
printf '%s' "${sp:-$HOME/cloud}"
}
install_deps() {
C "Installing build + thumbnail dependencies"
local pkgs=(imagemagick ffmpeg)
command -v node >/dev/null || pkgs+=(nodejs)
command -v pnpm >/dev/null || pkgs+=(pnpm)
command -v fd >/dev/null || pkgs+=(fd)
if command -v pacman >/dev/null; then
sudo pacman -S --needed --noconfirm "${pkgs[@]}"
else
die "this installer targets the Arch dufs host (pacman)"
fi
command -v node >/dev/null || die "node missing after install"
command -v pnpm >/dev/null || die "pnpm missing after install"
OK "dependencies present ($(node -v), pnpm $(pnpm -v))"
command -v ffmpeg >/dev/null && ffmpeg -version >/dev/null 2>&1 \
|| WARN "ffmpeg is present but not runnable — video posters will be skipped (fix ffmpeg, e.g. full system upgrade)"
}
build_spa() {
C "Building the gallery (pnpm build)"
[[ -d "$GALLERY_DIR" ]] || die "missing $GALLERY_DIR"
(cd "$GALLERY_DIR" && pnpm install --silent && pnpm build)
[[ -f "$GALLERY_DIR/dist/index.html" ]] || die "build produced no dist/index.html"
OK "built $GALLERY_DIR/dist"
}
deploy_spa() {
local root; root="$(cloud_root)"
C "Deploying the SPA into the cloud root: $root"
mkdir -p "$root"
rm -rf "$root/assets"
cp -r "$GALLERY_DIR/dist/assets" "$root/assets"
cp -f "$GALLERY_DIR/dist/index.html" "$root/index.html"
OK "deployed index.html + assets/"
}
enable_render_spa() {
[[ -f "$DUFS_YAML" ]] || die "dufs config $DUFS_YAML not found — run setup_dufs_cloud.sh first"
if grep -q '^render-spa:' "$DUFS_YAML"; then
OK "dufs render-spa already enabled"
else
# Insert after the allow-all line so the app shell is served for the UI.
sed -i '/^allow-all:/a render-spa: true' "$DUFS_YAML"
OK "enabled render-spa in dufs.yaml"
fi
sudo systemctl restart dufs.service
OK "dufs restarted"
}
wire_thumbnails() {
C "Generating thumbnails + wiring into media sync"
bash "$THUMBS_SCRIPT" || WARN "initial thumbnail pass reported problems (continuing)"
# Regenerate thumbnails after each Phase-2 media sync (best-effort).
if systemctl is-enabled media-cloud-sync.timer >/dev/null 2>&1 \
|| systemctl is-active media-cloud-sync.path >/dev/null 2>&1; then
sudo mkdir -p /etc/systemd/system/media-cloud-sync.service.d
sudo tee /etc/systemd/system/media-cloud-sync.service.d/10-thumbnails.conf >/dev/null <<EOF
[Service]
ExecStartPost=-$THUMBS_SCRIPT
EOF
sudo systemctl daemon-reload
OK "thumbnails will refresh after each media sync"
else
WARN "media-cloud-sync not set up — run setup_media_cloud_sync.sh for auto thumbnails"
fi
}
main() {
[[ "${1:-}" == "-h" || "${1:-}" == "--help" ]] \
&& { grep -E '^#( |$)' "$0" | sed -E 's/^# ?//'; exit 0; }
install_deps
build_spa
deploy_spa
enable_render_spa
wire_thumbnails
local url="https://kuhy-cloud.duckdns.org"
cat <<EOF
────────────────────────────────────────────────────────────────────────────
Cloud gallery deployed. Open ${url}/ (log in with your dufs credentials).
Browse folders, view images in the lightbox, play videos, upload/download,
delete, and edit .txt/.md files — all from the browser.
Rebuild + redeploy anytime by re-running this script.
────────────────────────────────────────────────────────────────────────────
EOF
}
main "$@"

View File

@ -1,333 +0,0 @@
#!/bin/bash
# setup_dufs_cloud.sh — Self-hosted "cloud" storage (dufs) on this Arch PC.
#
# Stands up dufs (a single Rust binary: web UI + built-in WebDAV over a real
# folder), bound to 127.0.0.1 and fronted by the EXISTING Caddy reverse proxy
# (from setup_gitea.sh) for automatic public HTTPS at a new DuckDNS subdomain.
# Also mirrors the KeePassXC vault into the served folder on every change so it
# is always fetchable from the phone (KeePassDX syncs it natively over WebDAV).
#
# Reuses the host's existing exposure stack — it does NOT add a second Caddy,
# a second DuckDNS updater, or hand-edit /etc/nftables.conf. See
# .github/skills/self-hosted-service-exposure/SKILL.md.
#
# Run as your normal user (NOT root). It uses sudo only for pacman, the binary
# install, systemd units and the firewall flag. Idempotent — safe to re-run.
#
# Usage:
# ./setup_dufs_cloud.sh Install / update everything
# ./setup_dufs_cloud.sh -h Show help
set -euo pipefail
# --- Pinned dufs release (verified by sha256) --------------------------------
readonly DUFS_VERSION="0.46.0"
readonly DUFS_SHA256="817769f726613194bcff9d0e3e481eaccc86ac11208857614f36a8c02f410977"
readonly DUFS_ASSET="dufs-v${DUFS_VERSION}-x86_64-unknown-linux-musl.tar.gz"
readonly DUFS_URL="https://github.com/sigoden/dufs/releases/download/v${DUFS_VERSION}/${DUFS_ASSET}"
readonly DUFS_BIN="/usr/local/bin/dufs"
readonly DUFS_PORT=5000
# --- Existing host infrastructure (from setup_gitea.sh / install_joplin.sh) --
readonly CADDY_CONTAINER="gitea-caddy"
readonly CADDYFILE="${HOME}/gitea/Caddyfile"
readonly CADDYFILE_IN_CONTAINER="/etc/caddy/Caddyfile"
readonly DUCKDNS_UPDATER="${HOME}/.joplin-server/duckdns-update.sh"
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
readonly SCRIPT_DIR
readonly SYSTEMD_SRC="${SCRIPT_DIR}/systemd"
readonly WG_SCRIPT="${SCRIPT_DIR}/setup_wireguard_ssh.sh"
readonly CONFIG_FILE="${SCRIPT_DIR}/.dufs_cloud.conf"
# Git repo root (used by the paranoid secret guards below).
REPO_ROOT="$(git -C "${SCRIPT_DIR}" rev-parse --show-toplevel 2>/dev/null || true)"
readonly REPO_ROOT
# shellcheck source=../../lib/common.sh
# shellcheck disable=SC1091
source "${SCRIPT_DIR}/../../lib/common.sh"
# OS user that will own and run the service (not the dufs web-login user).
SYS_USER="$(get_actual_user)"
readonly SYS_USER
# Config values (populated from CONFIG_FILE / prompts).
DUFS_USER=""
DUFS_PASSWORD=""
DUFS_SUBDOMAIN=""
CLOUD_ROOT=""
die() {
log_error "$1"
exit 1
}
usage() {
grep -E '^#( |$)' "$0" | sed -E 's/^# ?//'
exit 0
}
# --- Step 1: preflight -------------------------------------------------------
preflight() {
log_info "Preflight checks"
[[ ${EUID} -ne 0 ]] || die "Run as your normal user, not root (it will sudo where needed)."
# Runtime deps; install any that are missing from the official repos.
install_missing_pacman_packages curl rsync inotify-tools openssl
# The public-exposure stack must already exist (Caddy from setup_gitea.sh).
has_cmd docker || die "docker not found — run setup_gitea.sh first."
docker ps --format '{{.Names}}' | grep -qx "${CADDY_CONTAINER}" \
|| die "Caddy container '${CADDY_CONTAINER}' not running — run setup_gitea.sh first."
[[ -f ${CADDYFILE} ]] || die "Caddyfile ${CADDYFILE} missing — run setup_gitea.sh first."
[[ -x ${DUCKDNS_UPDATER} ]] || die "DuckDNS updater ${DUCKDNS_UPDATER} missing — run install_joplin.sh first."
log_ok "Host exposure stack present (docker + ${CADDY_CONTAINER} + DuckDNS updater)"
}
# --- Step 2: configuration (gitignored .conf, prompt when empty) -------------
load_config() {
if [[ -f ${CONFIG_FILE} ]]; then
# shellcheck source=/dev/null
source "${CONFIG_FILE}"
fi
DUFS_USER="${DUFS_USER:-}"
DUFS_PASSWORD="${DUFS_PASSWORD:-}"
DUFS_SUBDOMAIN="${DUFS_SUBDOMAIN:-}"
CLOUD_ROOT="${CLOUD_ROOT:-}"
}
prompt_config() {
if [[ -z ${DUFS_USER} ]]; then
read -r -p "dufs web username [${SYS_USER}]: " DUFS_USER
DUFS_USER="${DUFS_USER:-${SYS_USER}}"
fi
if [[ -z ${DUFS_PASSWORD} ]]; then
read -r -s -p "dufs web password: " DUFS_PASSWORD
echo
[[ -n ${DUFS_PASSWORD} ]] || die "A password is required (this server is public)."
fi
if [[ -z ${DUFS_SUBDOMAIN} ]]; then
read -r -p "public subdomain [kuhy-cloud.duckdns.org]: " DUFS_SUBDOMAIN
DUFS_SUBDOMAIN="${DUFS_SUBDOMAIN:-kuhy-cloud.duckdns.org}"
fi
if [[ -z ${CLOUD_ROOT} ]]; then
read -r -p "cloud storage folder [${HOME}/cloud]: " CLOUD_ROOT
CLOUD_ROOT="${CLOUD_ROOT:-${HOME}/cloud}"
fi
}
# Paranoid guard: never persist the plaintext password unless git is certain
# the file is ignored. This is checked against the live .gitignore, so a broken
# or removed ignore rule stops the write instead of leaking the secret.
assert_config_gitignored() {
[[ -n ${REPO_ROOT} ]] || die "Not inside a git repo — refusing to write the secret config."
if ! git -C "${REPO_ROOT}" check-ignore -q "${CONFIG_FILE}"; then
die "Refusing to write ${CONFIG_FILE}: it is NOT gitignored. Restore the .gitignore rule first — will not risk leaking the password."
fi
}
save_config() {
assert_config_gitignored
# 0600, gitignored — holds the plaintext web password so re-runs stay
# non-interactive. Never committed (see .gitignore + the check-no-dufs-conf
# pre-commit hook, which blocks it even against `git add -f`).
umask 077
{
printf 'DUFS_USER=%q\n' "${DUFS_USER}"
printf 'DUFS_PASSWORD=%q\n' "${DUFS_PASSWORD}"
printf 'DUFS_SUBDOMAIN=%q\n' "${DUFS_SUBDOMAIN}"
printf 'CLOUD_ROOT=%q\n' "${CLOUD_ROOT}"
} >"${CONFIG_FILE}"
chmod 600 "${CONFIG_FILE}"
log_ok "Saved config to ${CONFIG_FILE} (0600)"
}
# --- Step 3: install the pinned, checksum-verified dufs binary ---------------
install_dufs() {
if [[ -x ${DUFS_BIN} ]] && "${DUFS_BIN}" --version 2>/dev/null | grep -q "${DUFS_VERSION}"; then
log_ok "dufs ${DUFS_VERSION} already installed"
return 0
fi
log_info "Installing dufs ${DUFS_VERSION}"
local tmp
tmp="$(mktemp -d)"
# shellcheck disable=SC2064
trap "rm -rf '${tmp}'" RETURN
curl -fsSL -o "${tmp}/${DUFS_ASSET}" "${DUFS_URL}"
echo "${DUFS_SHA256} ${tmp}/${DUFS_ASSET}" | sha256sum -c - \
|| die "dufs checksum mismatch — refusing to install."
tar -xzf "${tmp}/${DUFS_ASSET}" -C "${tmp}"
sudo install -m 0755 "${tmp}/dufs" "${DUFS_BIN}"
log_ok "Installed ${DUFS_BIN}"
}
# Paranoid guard: never let dufs serve a directory that would expose secrets
# (home root, ~/.ssh, ~/.config — which holds dufs.yaml — ~/.gnupg, / , or the
# git repo which holds the gitignored .dufs_cloud.conf).
assert_cloud_root_safe() {
local resolved home_r
resolved="$(readlink -m "${CLOUD_ROOT}")"
home_r="$(readlink -m "${HOME}")"
case "${resolved}" in
"${home_r}" | / | "${home_r}/.ssh" | "${home_r}/.ssh/"* \
| "${home_r}/.config" | "${home_r}/.config/"* \
| "${home_r}/.gnupg" | "${home_r}/.gnupg/"*)
die "Unsafe cloud folder '${CLOUD_ROOT}' — it would expose sensitive files. Use a dedicated folder like ${HOME}/cloud." ;;
esac
if [[ -n ${REPO_ROOT} && (${resolved} == "${REPO_ROOT}" || ${resolved} == "${REPO_ROOT}/"*) ]]; then
die "Unsafe cloud folder '${CLOUD_ROOT}' — it is inside the git repo (which holds the secret config). Use a dedicated folder."
fi
}
# --- Step 4: served folder ---------------------------------------------------
create_serve_dir() {
assert_cloud_root_safe
ensure_dir "${CLOUD_ROOT}"
ensure_dir "${CLOUD_ROOT}/Keepass"
chmod 700 "${CLOUD_ROOT}"
log_ok "Cloud folder ${CLOUD_ROOT} ready"
}
# --- Step 5: dufs config (SHA-512 hashed password, no anonymous access) -------
write_dufs_config() {
local cfg_dir="${HOME}/.config/dufs"
local cfg="${cfg_dir}/dufs.yaml"
local hash
# Read the password from stdin so it never appears in the process argv (ps).
hash="$(printf '%s' "${DUFS_PASSWORD}" | openssl passwd -6 -stdin)"
# Serve the cloud_gallery SPA (render-spa) ONLY once it is deployed into the
# cloud root — a fresh dufs with no gallery keeps the default file listing.
local render=""
[[ -f "${CLOUD_ROOT}/index.html" ]] && render="render-spa: true"
ensure_dir "${cfg_dir}"
umask 077
cat >"${cfg}" <<EOF
# Generated by setup_dufs_cloud.sh — do not edit by hand.
serve-path: ${CLOUD_ROOT}
bind: 127.0.0.1
port: ${DUFS_PORT}
allow-all: true
${render}
auth:
- "${DUFS_USER}:${hash}@/:rw"
EOF
chmod 600 "${cfg}"
log_ok "Wrote ${cfg} (auth required, password hashed)"
}
# --- Step 6: systemd units (render placeholders → /etc/systemd/system) -------
render_unit() {
local name="$1"
sed -e "s|__USER__|${SYS_USER}|g" \
-e "s|__HOME__|${HOME}|g" \
-e "s|__CLOUD_ROOT__|${CLOUD_ROOT}|g" \
"${SYSTEMD_SRC}/${name}" | sudo tee "/etc/systemd/system/${name}" >/dev/null
}
install_units() {
log_info "Installing systemd units"
render_unit dufs.service
render_unit keepass-cloud-sync.service
render_unit keepass-cloud-sync.path
sudo systemctl daemon-reload
sudo systemctl enable --now dufs.service
log_ok "dufs.service enabled and started"
}
# --- Step 7: Caddy reverse-proxy block (append + reload) ---------------------
configure_caddy() {
if grep -qE "^${DUFS_SUBDOMAIN} \{" "${CADDYFILE}"; then
log_ok "Caddyfile already has a block for ${DUFS_SUBDOMAIN}"
else
log_info "Adding Caddy block for ${DUFS_SUBDOMAIN}"
# NOTE: appended to the shared Gitea Caddyfile. Re-running setup_gitea.sh
# regenerates that file and drops this block — re-run setup_dufs_cloud.sh
# to restore it. Caddyfile uses tab indentation.
printf '\n%s {\n\treverse_proxy 127.0.0.1:%s\n}\n' "${DUFS_SUBDOMAIN}" "${DUFS_PORT}" \
>>"${CADDYFILE}"
fi
docker exec "${CADDY_CONTAINER}" caddy reload --config "${CADDYFILE_IN_CONTAINER}" \
|| die "caddy reload failed — check 'docker logs ${CADDY_CONTAINER}'."
log_ok "Caddy reloaded (auto-HTTPS will be issued once the subdomain resolves)"
}
# --- Step 8: DuckDNS subdomain (extend existing updater; no new cron) --------
configure_duckdns() {
local label="${DUFS_SUBDOMAIN%.duckdns.org}"
if grep -qE "domains=[^&\"']*${label}([,&\"']|$)" "${DUCKDNS_UPDATER}"; then
log_ok "DuckDNS updater already includes '${label}'"
else
log_info "Adding '${label}' to the existing DuckDNS updater"
sed -i -E "s|(domains=)([^&\"']*)|\1\2,${label}|" "${DUCKDNS_UPDATER}"
fi
# Refresh now (harmless if the subdomain isn't registered yet).
bash "${DUCKDNS_UPDATER}" || log_warn "DuckDNS update returned non-zero (register the subdomain first)."
if getent hosts "${DUFS_SUBDOMAIN}" >/dev/null 2>&1; then
log_ok "${DUFS_SUBDOMAIN} resolves"
else
log_warn "${DUFS_SUBDOMAIN} does not resolve yet — create the '${label}' subdomain in the DuckDNS dashboard."
fi
}
# --- Step 9: firewall (open 80/443 via the owning script, idempotent) -------
ensure_firewall() {
if sudo nft list ruleset 2>/dev/null | grep -qE 'dport \{[^}]*80[^}]*443'; then
log_ok "Firewall already allows tcp/80 + tcp/443"
elif [[ -f ${WG_SCRIPT} ]]; then
log_info "Opening 80/443 via setup_wireguard_ssh.sh allow-web"
sudo bash "${WG_SCRIPT}" allow-web
else
log_warn "setup_wireguard_ssh.sh not found — ensure tcp/80+443 are open."
fi
}
# --- Step 10: KeePass auto-sync (initial mirror + enable the path watcher) ---
setup_autosync() {
log_info "Setting up KeePass auto-sync watcher"
# Mirror only the vault file (not the whole dir with local .backup_* vaults).
rsync -a "${HOME}/Keepass/Passwords.kdbx" "${CLOUD_ROOT}/Keepass/"
sudo systemctl enable --now keepass-cloud-sync.path
log_ok "Vault mirrored and watcher enabled"
}
# --- Step 11: report ---------------------------------------------------------
print_report() {
local url="https://${DUFS_SUBDOMAIN}"
cat <<EOF
============================================================================
dufs cloud is up.
Web UI / WebDAV : ${url}/
Login : ${DUFS_USER} / (your password)
Served folder : ${CLOUD_ROOT}
KeePassDX target: ${url}/Keepass/Passwords.kdbx (WebDAV)
If the subdomain is new, create it once in the DuckDNS dashboard
(label: ${DUFS_SUBDOMAIN%.duckdns.org}) so Caddy can issue TLS.
Acceptance test: on your phone with Wi-Fi OFF (cellular), open ${url}/,
log in, and confirm you see Keepass/Passwords.kdbx.
============================================================================
EOF
}
main() {
[[ "${1:-}" == "-h" || "${1:-}" == "--help" ]] && usage
print_setup_header "Self-hosted dufs cloud storage"
preflight
load_config
prompt_config
save_config
install_dufs
create_serve_dir
write_dufs_config
install_units
configure_caddy
configure_duckdns
ensure_firewall
setup_autosync
print_report
}
main "$@"

View File

@ -1,22 +0,0 @@
[Unit]
# dufs self-hosted cloud file server (web UI + WebDAV), bound to loopback and
# fronted by the existing Caddy reverse proxy for public HTTPS.
# Placeholders (__USER__ / __HOME__) are substituted by setup_dufs_cloud.sh at
# install time; this file is the source of truth, not the installed copy.
Description=dufs self-hosted cloud file server
Documentation=https://github.com/sigoden/dufs
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=__USER__
ExecStart=/usr/local/bin/dufs --config __HOME__/.config/dufs/dufs.yaml
Restart=on-failure
RestartSec=3
# Minimal hardening (dufs needs $HOME/.config and the served dir under /home).
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target

View File

@ -1,85 +0,0 @@
#!/bin/bash
# generate_thumbnails.sh — make small preview thumbnails for the cloud media so
# the web gallery (cloud_gallery) loads fast instead of downloading full files.
#
# For every image/video under the dufs cloud it writes a ~400px JPEG to
# $CLOUD_ROOT/.thumbs/<same-path>.jpg
# which the gallery requests as `/.thumbs/<path>.jpg`. Images are resized with
# ImageMagick; videos get a poster frame via ffmpeg. Idempotent: a thumbnail
# newer than its source is skipped. flock-guarded, self-contained.
#
# CLOUD_ROOT comes from the dufs serve-path (~/.config/dufs/dufs.yaml), else
# ~/cloud. Usage: generate_thumbnails.sh [ROOT_DIR]
set -euo pipefail
readonly THUMB_MAX=400
log() { printf '[thumbnails] %s\n' "$*" >&2; }
CLOUD_ROOT="${CLOUD_ROOT:-}"
if [[ -z "$CLOUD_ROOT" && -f "$HOME/.config/dufs/dufs.yaml" ]]; then
CLOUD_ROOT="$(sed -nE 's/^serve-path:[[:space:]]*//p' "$HOME/.config/dufs/dufs.yaml" | head -1)"
fi
CLOUD_ROOT="${CLOUD_ROOT:-$HOME/cloud}"
ROOT="${1:-$CLOUD_ROOT}"
readonly THUMBS="$CLOUD_ROOT/.thumbs"
FD="$(command -v fd || command -v fdfind || true)"
[[ -n "$FD" ]] || { log "ERROR: fd (fd-find) not installed"; exit 1; }
command -v ffmpeg >/dev/null || { log "ERROR: ffmpeg not installed"; exit 1; }
MAGICK="$(command -v magick || command -v convert || true)"
[[ -n "$MAGICK" ]] || { log "ERROR: ImageMagick (magick/convert) not installed"; exit 1; }
readonly IMG_EXTS=(jpg jpeg png gif bmp tiff tif webp heic heif avif)
readonly VID_EXTS=(mp4 avi mkv mov wmv flv webm m4v 3gp ogv mpg mpeg mts m2ts vob)
FD_ARGS=()
for e in "${IMG_EXTS[@]}" "${VID_EXTS[@]}"; do FD_ARGS+=(-e "$e"); done
STATE_DIR="${THUMB_STATE:-$HOME/.local/state/media-cloud-sync}"
mkdir -p "$STATE_DIR" "$THUMBS"
exec 9>"$STATE_DIR/thumbs.lock"
flock -n 9 || { log "another thumbnail run is in progress — skipping"; exit 0; }
is_video() {
local ext="${1##*.}"
ext="${ext,,}"
for v in "${VID_EXTS[@]}"; do [[ "$ext" == "$v" ]] && return 0; done
return 1
}
made=0 skipped=0 failed=0
while IFS= read -r src; do
[[ -f "$src" ]] || continue
# Thumbnail path mirrors the file's path under the cloud root.
rel="${src#"$CLOUD_ROOT"}"
dst="$THUMBS${rel}.jpg"
if [[ -f "$dst" && "$dst" -nt "$src" ]]; then
skipped=$((skipped + 1)); continue
fi
mkdir -p "$(dirname "$dst")"
if is_video "$src"; then
if ffmpeg -y -loglevel error -ss 1 -i "$src" -frames:v 1 \
-vf "scale=${THUMB_MAX}:-2:force_original_aspect_ratio=decrease" \
"$dst" </dev/null 2>/dev/null; then
made=$((made + 1))
else
# Fall back to the very first frame (videos shorter than 1s).
if ffmpeg -y -loglevel error -i "$src" -frames:v 1 \
-vf "scale=${THUMB_MAX}:-2" "$dst" </dev/null 2>/dev/null; then
made=$((made + 1))
else
failed=$((failed + 1))
fi
fi
else
if "$MAGICK" "${src}[0]" -auto-orient -thumbnail "${THUMB_MAX}x${THUMB_MAX}>" \
-strip "$dst" 2>/dev/null; then
made=$((made + 1))
else
failed=$((failed + 1))
fi
fi
done < <("$FD" "${FD_ARGS[@]}" --type f --exclude '.thumbs' --exclude '_thumbs' . "$ROOT" 2>/dev/null || true)
log "done: $made made, $skipped current, $failed failed → $THUMBS"

View File

@ -1,99 +0,0 @@
#!/bin/bash
# import_media_archives.sh — extract media_archive_*.zip snapshots and MOVE their
# media into the self-hosted dufs cloud, deduplicating across the overlapping
# snapshots, then delete each zip once its media is safely in the cloud.
#
# These archives are incremental snapshots of ~/Downloads (each holds a top-level
# downloads/ dir) and contain only images/videos — so "media only" loses nothing.
#
# Per zip (safe + resumable):
# 1. extract into a staging dir on the cloud filesystem (so mv is a rename)
# 2. hand the staging dir to sync_media_to_cloud.sh, which MOVES media into
# $CLOUD/Media/YYYY/MM (by mtime) and drops files already in the cloud
# 3. verify no media remains in staging (nothing failed to move)
# 4. delete the staging dir, then delete the zip
# A zip is deleted ONLY after its media is confirmed in the cloud; on any problem
# the zip is kept and the run continues.
#
# Usage: import_media_archives.sh [ARCHIVE_DIR]
# (default ARCHIVE_DIR: ~/Downloads/media_archive_archive)
set -euo pipefail
HERE="$(dirname "$(readlink -f "$0")")"
readonly HERE
readonly ORGANIZER="$HERE/sync_media_to_cloud.sh"
readonly ARCHIVE_DIR="${1:-$HOME/Downloads/media_archive_archive}"
log() { printf '[import-archives] %s\n' "$*" >&2; }
die() { printf '[import-archives] ERROR: %s\n' "$*" >&2; exit 1; }
# --- dependencies (self-installing on Arch) ----------------------------------
if ! command -v unzip >/dev/null; then
if command -v pacman >/dev/null; then
sudo pacman -S --needed --noconfirm unzip
else
die "unzip is required but not installed"
fi
fi
[[ -x "$ORGANIZER" ]] || die "organizer script not found/executable: $ORGANIZER"
[[ -d "$ARCHIVE_DIR" ]] || die "archive directory not found: $ARCHIVE_DIR"
# Media extensions must match sync_media_to_cloud.sh — used only to verify that
# staging was fully drained before deleting a zip.
readonly MEDIA_RE='.*\.(jpg|jpeg|png|gif|bmp|tiff|tif|webp|raw|cr2|nef|orf|arw|dng|heic|heif|mp4|avi|mkv|mov|wmv|flv|webm|m4v|3gp|ogv|mpg|mpeg|mts|m2ts|vob)$'
# --- stage on the cloud filesystem so mv is an atomic rename -----------------
CLOUD_ROOT="${CLOUD_ROOT:-}"
if [[ -z "$CLOUD_ROOT" && -f "$HOME/.config/dufs/dufs.yaml" ]]; then
CLOUD_ROOT="$(sed -nE 's/^serve-path:[[:space:]]*//p' "$HOME/.config/dufs/dufs.yaml" | head -1)"
fi
CLOUD_ROOT="${CLOUD_ROOT:-$HOME/cloud}"
STAGE_PARENT="$(dirname "$CLOUD_ROOT")"
readonly STAGE_PARENT
STAGING=""
cleanup() { [[ -n "$STAGING" && -d "$STAGING" ]] && rm -rf "$STAGING"; }
trap cleanup EXIT
count_media() {
find "$1" -type f -regextype posix-extended -iregex "$MEDIA_RE" 2>/dev/null | wc -l
}
shopt -s nullglob
zips=("$ARCHIVE_DIR"/*.zip)
(( ${#zips[@]} )) || { log "no *.zip found in $ARCHIVE_DIR — nothing to do"; exit 0; }
readonly total=${#zips[@]}
i=0 deleted=0 kept=0
log "importing $total archive(s) from $ARCHIVE_DIR into $CLOUD_ROOT/Media"
for zip in "${zips[@]}"; do
i=$((i + 1))
log "[$i/$total] $(basename "$zip") ($(du -h "$zip" | cut -f1))"
STAGING="$(mktemp -d "$STAGE_PARENT/.media-import.XXXXXX")"
if ! unzip -q -o "$zip" -d "$STAGING"; then
log " unzip failed — keeping zip"; rm -rf "$STAGING"; STAGING=""; kept=$((kept + 1)); continue
fi
before="$(count_media "$STAGING")"
if ! "$ORGANIZER" "$STAGING"; then
log " organizer failed — keeping zip"; rm -rf "$STAGING"; STAGING=""; kept=$((kept + 1)); continue
fi
after="$(count_media "$STAGING")"
if (( after > 0 )); then
log " WARNING: $after/$before media file(s) not moved — keeping zip for safety"
rm -rf "$STAGING"; STAGING=""; kept=$((kept + 1)); continue
fi
rm -rf "$STAGING"; STAGING=""
if rm -f "$zip"; then
deleted=$((deleted + 1))
log " ✓ $before media handled; zip deleted"
else
log " media moved but zip delete failed: $zip"; kept=$((kept + 1))
fi
done
log "done: $deleted zip(s) imported + deleted, $kept kept"

View File

@ -1,120 +0,0 @@
#!/bin/bash
# setup_media_cloud_sync.sh — install the "downloads media → dufs cloud" sync.
#
# Installs systemd units that mirror ~/Downloads images/videos into the dufs
# cloud (unzipped + browsable) so they're viewable from anywhere:
# • media-cloud-sync.service (oneshot → sync_media_to_cloud.sh)
# • media-cloud-sync.timer (catch-up every 30 min)
# • media-cloud-sync.path (immediate, when ~/Downloads changes)
# Plus a drop-in so the existing media-organizer (which zips + deletes Downloads
# for local cold archive) runs AFTER the cloud sync — nothing is deleted before
# the cloud has a copy.
#
# Runs on the dufs host (the PC). Run as your normal user; sudo is used only for
# the system units.
set -euo pipefail
HERE="$(dirname "$(readlink -f "$0")")"
readonly HERE
readonly SYNC_SCRIPT="$HERE/sync_media_to_cloud.sh"
RUN_USER="$(id -un)"
readonly RUN_USER
readonly DOWNLOADS="$HOME/Downloads"
C() { printf '\033[1;34m[media-cloud-setup]\033[0m %s\n' "$*"; }
OK() { printf '\033[1;32m ✓\033[0m %s\n' "$*"; }
die() { printf '\033[1;31m[media-cloud-setup] ERROR:\033[0m %s\n' "$*" >&2; exit 1; }
usage() { grep -E '^#( |$)' "$0" | sed -E 's/^# ?//'; exit 0; }
write_unit() { # write_unit <name> <content-on-stdin>
sudo tee "/etc/systemd/system/$1" >/dev/null
OK "wrote /etc/systemd/system/$1"
}
main() {
[[ "${1:-}" == "-h" || "${1:-}" == "--help" ]] && usage
[[ -x "$SYNC_SCRIPT" ]] || die "missing $SYNC_SCRIPT"
# fd is the only extra dependency of the sync script.
if command -v pacman >/dev/null; then
sudo pacman -S --needed --noconfirm fd >/dev/null
elif command -v apt-get >/dev/null; then
sudo apt-get install -y fd-find >/dev/null
fi
command -v fd >/dev/null || command -v fdfind >/dev/null || die "fd (fd-find) not installed"
OK "dependencies present"
C "Installing systemd units"
write_unit media-cloud-sync.service <<EOF
[Unit]
Description=Mirror organized downloads media into the dufs cloud (unzipped, browsable)
After=network.target
[Service]
Type=oneshot
User=$RUN_USER
ExecStart=$SYNC_SCRIPT
EOF
write_unit media-cloud-sync.timer <<EOF
[Unit]
Description=Periodically mirror ~/Downloads media into the dufs cloud
[Timer]
OnBootSec=2min
OnUnitActiveSec=30min
Persistent=true
[Install]
WantedBy=timers.target
EOF
write_unit media-cloud-sync.path <<EOF
[Unit]
Description=Watch ~/Downloads and mirror new media into the dufs cloud
[Path]
PathModified=$DOWNLOADS
Unit=media-cloud-sync.service
[Install]
WantedBy=multi-user.target
EOF
# Ordering drop-in: the organizer (zips + deletes Downloads) must run AFTER
# the cloud sync, so media reaches the cloud before it is pruned locally.
C "Ordering the existing media-organizer after the cloud sync"
sudo mkdir -p /etc/systemd/system/media-organizer.service.d
sudo tee /etc/systemd/system/media-organizer.service.d/10-after-cloud-sync.conf >/dev/null <<EOF
[Unit]
After=media-cloud-sync.service
Wants=media-cloud-sync.service
EOF
OK "drop-in installed (harmless if media-organizer isn't set up)"
sudo systemctl daemon-reload
sudo systemctl enable --now media-cloud-sync.timer media-cloud-sync.path
OK "timer + path watcher enabled"
C "Initial sweep (this may take a moment)…"
"$SYNC_SCRIPT"
local cloud_root
cloud_root="$(sed -nE 's/^serve-path:[[:space:]]*//p' "$HOME/.config/dufs/dufs.yaml" 2>/dev/null | head -1)"
cloud_root="${cloud_root:-$HOME/cloud}"
cat <<EOF
────────────────────────────────────────────────────────────────────────────
Done. Your Downloads images/videos are now MOVED into ${cloud_root}/Media/YYYY/MM
automatically (within ~30 min, or right after Downloads changes) — no
duplication: the files leave Downloads and live only in the cloud folder.
Files still downloading (modified in the last 2 min) are left until they settle.
Browse them at your cloud URL, e.g. https://kuhy-cloud.duckdns.org/Media/
(Because media is moved out first, organize_downloads.sh no longer zips it —
the cloud folder is the storage now.)
────────────────────────────────────────────────────────────────────────────
EOF
}
main "$@"

View File

@ -1,100 +0,0 @@
#!/bin/bash
# sync_media_to_cloud.sh — MOVE organized images/videos into the dufs cloud,
# unzipped and browsable, so they're viewable from anywhere (web + app) without
# duplicating them. The file LEAVES ~/Downloads and lives only in the cloud
# folder (which is on local disk and served by dufs) — so the cloud is the
# single storage; there is no separate local copy or zip duplicate.
#
# For each Downloads image/video it moves the file to $CLOUD_ROOT/Media/YYYY/MM/
# (by file mtime) with `mv`: an atomic rename on the same filesystem (instant,
# no extra disk), or a copy-then-remove-source across filesystems (mv removes
# the source only after a successful copy, so an interruption never loses data).
# The destination name is pre-checked to be free, so nothing is clobbered. Files
# modified in the last 2 minutes are skipped (they may still be downloading). A
# file identical to one already in the cloud is de-duplicated (source removed).
# Collisions with a different file get a numeric suffix. flock-guarded.
#
# CLOUD_ROOT is taken from the dufs serve-path (~/.config/dufs/dufs.yaml),
# falling back to ~/cloud. Self-contained; runs on Arch or Ubuntu.
#
# Usage: sync_media_to_cloud.sh [SOURCE_DIR ...] (default: ~/Downloads)
set -euo pipefail
log() { printf '[media-cloud-sync] %s\n' "$*" >&2; }
readonly QUIESCE_SECONDS=120 # skip files modified within this window (still downloading)
# --- where does the cloud live? -----------------------------------------------
CLOUD_ROOT="${CLOUD_ROOT:-}"
if [[ -z "$CLOUD_ROOT" && -f "$HOME/.config/dufs/dufs.yaml" ]]; then
CLOUD_ROOT="$(sed -nE 's/^serve-path:[[:space:]]*//p' "$HOME/.config/dufs/dufs.yaml" | head -1)"
fi
CLOUD_ROOT="${CLOUD_ROOT:-$HOME/cloud}"
readonly MEDIA_DEST="$CLOUD_ROOT/Media"
SOURCES=("$@")
[[ ${#SOURCES[@]} -eq 0 ]] && SOURCES=("$HOME/Downloads")
FD="$(command -v fd || command -v fdfind || true)"
[[ -n "$FD" ]] || { log "ERROR: fd (fd-find) not installed"; exit 1; }
# Same media extensions as organize_downloads.sh.
readonly EXTS=(jpg jpeg png gif bmp tiff tif webp raw cr2 nef orf arw dng heic heif \
mp4 avi mkv mov wmv flv webm m4v 3gp ogv mpg mpeg mts m2ts vob)
FD_EXT_ARGS=()
for e in "${EXTS[@]}"; do FD_EXT_ARGS+=(-e "$e"); done
# --- serialize ---------------------------------------------------------------
STATE_DIR="${MEDIA_SYNC_STATE:-$HOME/.local/state/media-cloud-sync}"
mkdir -p "$STATE_DIR" "$MEDIA_DEST"
exec 9>"$STATE_DIR/lock"
flock -n 9 || { log "another sync is running — skipping"; exit 0; }
now="$(date +%s)"
moved=0 deduped=0 skipped=0
for src in "${SOURCES[@]}"; do
[[ -e "$src" ]] || continue
if [[ -f "$src" ]]; then
mapfile -t FILES < <(printf '%s\n' "$src")
else
mapfile -t FILES < <(
"$FD" "${FD_EXT_ARGS[@]}" --type f \
--exclude 'media_archive_*' --exclude '*media_organize_*' \
--exclude '.git' --exclude 'node_modules' \
. "$src" 2>/dev/null || true
)
fi
for f in "${FILES[@]}"; do
[[ -f "$f" ]] || continue
# Skip files still being written (recently modified → maybe downloading).
mtime="$(stat -c%Y "$f" 2>/dev/null || echo 0)"
if (( now - mtime < QUIESCE_SECONDS )); then
log "skip (modified <${QUIESCE_SECONDS}s ago, may be downloading): $f"
skipped=$((skipped + 1)); continue
fi
ext="${f##*.}"; ext="${ext,,}"
sub="$(date -r "$f" +%Y/%m 2>/dev/null || echo unknown)"
dest_dir="$MEDIA_DEST/$sub"
base="$(basename "$f")"
dest="$dest_dir/$base"
if [[ -e "$dest" ]]; then
if [[ "$(stat -c%s "$f")" == "$(stat -c%s "$dest" 2>/dev/null)" ]]; then
rm -f "$f"; deduped=$((deduped + 1)); continue # identical already in cloud
fi
stem="${base%.*}"; n=1
while [[ -e "$dest_dir/${stem}_${n}.${ext}" ]]; do n=$((n + 1)); done
dest="$dest_dir/${stem}_${n}.${ext}"
fi
mkdir -p "$dest_dir"
# $dest is a pre-checked free name, so mv won't clobber. mv is atomic on
# the same filesystem and safe (copy-then-unlink) across filesystems.
if mv -f "$f" "$dest" 2>/dev/null; then
moved=$((moved + 1))
else
log "WARNING: failed to move $f (left in Downloads)"
fi
done
done
log "done: $moved moved, $deduped duplicates dropped, $skipped skipped → $MEDIA_DEST"

View File

@ -436,7 +436,7 @@ com.zaneschepke.wireguardautotunnel
org.connectbot
# --- Self-hosted cloud client (dufs; browse/upload media, see
# ~/dufs_client and setup_cloud_gallery.sh) ---
# github.com/kuhyx/dufs-cloud → app/) ---
com.kuhy.dufs_client
"