diff --git a/apps/api/src/library/uploads.ts b/apps/api/src/library/uploads.ts index 1ac8f73..6500989 100644 --- a/apps/api/src/library/uploads.ts +++ b/apps/api/src/library/uploads.ts @@ -47,11 +47,10 @@ export async function registerUploadRoutes( app.post("/v1/orgs/:orgId/uploads", { preHandler: authenticate }, async (req, reply) => { const { orgId } = OrgParams.parse(req.params); const query = UploadQuery.parse(req.query); - const { eventId } = query; + // A computer can still name an event that was removed or belongs to somewhere else. Refusing the file + // drops the photo. Ingest keeps the event only when it is this organization's, and otherwise uses the clock. + const eventId = query.eventId; const membership = await requireMembership(db, req, orgId, "PHOTOGRAPHER"); - if (eventId && !(await db.event.findFirst({ where: { id: eventId, organizationId: orgId }, select: { id: true } }))) { - throw badRequest("event_not_in_organization"); - } let uploaderId = currentUserId(req); if (query.uploaderUserId && query.uploaderUserId !== uploaderId) { if (ROLE_RANK[membership.role] < ROLE_RANK.INGESTER) throw badRequest("uploader_forbidden"); @@ -191,7 +190,6 @@ export async function registerUploadRoutes( const membership = await requireMembership(db, req, orgId, "PHOTOGRAPHER"); const name = path.basename(body.name); if (!ACCEPTED_EXTENSIONS.has(path.extname(name).toLowerCase())) throw new AppError(415, "unsupported_type", "JPEG only for now"); - if (body.eventId && !(await db.event.findFirst({ where: { id: body.eventId, organizationId: orgId }, select: { id: true } }))) throw badRequest("event_not_in_organization"); const userId = currentUserId(req); let uploaderUserId: string | null = null; if (body.uploaderUserId && body.uploaderUserId !== userId) { diff --git a/apps/app/src/library/folderDrop.test.ts b/apps/app/src/library/folderDrop.test.ts index dfbbe73..5435bc6 100644 --- a/apps/app/src/library/folderDrop.test.ts +++ b/apps/app/src/library/folderDrop.test.ts @@ -16,6 +16,20 @@ describe("folder drop", () => { expect(opened).toEqual(["/tmp/job"]); }); + it("uploads every loose file the shell can read", async () => { + const sent: string[] = []; + const wait = beginDropWait(); + nativePaths( + ["/tmp/a.jpg", "/tmp/b.jpg"], + async () => null, + () => {}, + async (paths) => paths.map((path) => new File([path], path.split("/").pop()!)), + (files) => sent.push(...files.map((file) => file.name)), + ); + await expect(wait).resolves.toBe("native"); + expect(sent).toEqual(["a.jpg", "b.jpg"]); + }); + it("leaves loose files to the upload", async () => { const opened: string[] = []; const wait = beginDropWait(); diff --git a/apps/app/src/library/folderDrop.ts b/apps/app/src/library/folderDrop.ts index 8aa3898..b5ad232 100644 --- a/apps/app/src/library/folderDrop.ts +++ b/apps/app/src/library/folderDrop.ts @@ -11,7 +11,7 @@ export interface FolderListing { files: FolderFile[]; } -type Kind = "folder" | "files"; +type Kind = "folder" | "files" | "native"; interface Gate { promise: Promise; @@ -66,18 +66,34 @@ export function nativePaths( paths: string[], isFolder: (paths: string[]) => Promise, open: (path: string) => void, + /** + * Loose files. Return the photos to upload. An empty list (an older shell that cannot read the drop) + * falls back to the page's own file list, which may contain only a few of them. + */ + readFiles?: (paths: string[]) => Promise, + upload?: (files: File[]) => void, ): void { nativeSeen = true; const current = takeGate(); clearTimeout(current.timer); void isFolder(paths) - .then((folder) => { + .then(async (folder) => { if (folder) { finish("folder"); open(folder); - } else { - finish("files"); + return; } + if (!readFiles) { + finish("files"); + return; + } + const files = await readFiles(paths).catch(() => [] as File[]); + if (!files.length) { + finish("files"); + return; + } + finish("native"); + upload?.(files); }) .catch(() => finish("files")); } @@ -104,6 +120,18 @@ export function folderDropPath(paths: string[], invoke: Invoke = desktopInvoke): return invoke("folder_drop", { paths }); } +/** Bytes of one photo from the latest drop of loose files. Null when this shell cannot read drops yet. */ +export async function readDroppedFile(path: string, invoke: Invoke = desktopInvoke): Promise { + if (!/\.jpe?g$/i.test(path)) return null; + try { + return asArrayBuffer(await invoke("drop_read", { path })); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + if (/not found|unknown command/i.test(message)) return null; + return null; + } +} + export async function openFolder(path: string, invoke: Invoke = desktopInvoke): Promise { try { return await invoke("folder_open", { path }); diff --git a/apps/app/src/library/uploads.ts b/apps/app/src/library/uploads.ts index c6eb642..0c45cb2 100644 --- a/apps/app/src/library/uploads.ts +++ b/apps/app/src/library/uploads.ts @@ -174,10 +174,12 @@ export function useUploadQueue(api: ApiClient, orgId: string) { eventId: string | undefined; original?: DesktopOrigin; uploaderUserId?: string; - sha256?: string | null; - onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void; - }[] - >([]); + sha256?: string | null; + onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void; + /** The named event was refused once. The next try lets the server place the photo by its clock. */ + eventStripped?: boolean; + }[] + >([]); const running = useRef(0); /** No network: the queue waits (nothing fails) and carries on when the connection is back. */ const paused = useRef(false); @@ -222,7 +224,14 @@ export function useUploadQueue(api: ApiClient, orgId: string) { else if (res.status === 200) final = "duplicate"; else if (res.status === 0 || res.status === 502 || res.status === 503 || res.status === 504) throw new Error("network"); if (photo && final !== "failed") filed = photo; - if (final === "failed") update(item.id, { status: "failed", error: (res.body as { error?: string } | null)?.error ?? `http_${res.status}` }); + const errorCode = (res.body as { error?: string } | null)?.error; + if (final === "failed" && errorCode === "event_not_in_organization" && next.eventId && !next.eventStripped) { + next.eventId = undefined; + next.eventStripped = true; + waiting = true; + update(item.id, { status: "queued", progress: 0, error: undefined }); + queue.current.unshift(next); + } else if (final === "failed") update(item.id, { status: "failed", error: errorCode ?? `http_${res.status}` }); else update(item.id, { status: final, progress: 1 }); } catch (err) { if (isNetworkError(err)) { diff --git a/apps/app/src/pages/LibraryPage.tsx b/apps/app/src/pages/LibraryPage.tsx index 8679d7b..71ab9d9 100644 --- a/apps/app/src/pages/LibraryPage.tsx +++ b/apps/app/src/pages/LibraryPage.tsx @@ -14,7 +14,7 @@ import { FacesView } from "../library/FacesView.js"; import { LookupBanner } from "../library/PhotoLookup.js"; import { FolderDevelop } from "../library/FolderDevelop.js"; import { FolderSheet } from "../library/FolderSheet.js"; -import { beginDropWait, folderDropPath, folderMeta, htmlDropIsFolder, mergeFolderDng, nativePaths, openFolder, folderThumb, type FolderListing } from "../library/folderDrop.js"; +import { beginDropWait, folderDropPath, folderMeta, htmlDropIsFolder, mergeFolderDng, nativePaths, openFolder, readDroppedFile, folderThumb, type FolderListing } from "../library/folderDrop.js"; import { finishMergedJpeg } from "../library/finishMergedJpeg.js"; import { mergeFolderNative } from "../library/folderMerge.js"; import { MERGE_EDGE } from "../library/mergeStacks.js"; @@ -279,6 +279,11 @@ export function LibraryPage() { const [developPath, setDevelopPath] = useState(null); const [openingFolder, setOpeningFolder] = useState(false); const [removeOpen, setRemoveOpen] = useState(false); + const uploadInto = state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? state.scope : undefined; + const uploadAddRef = useRef(uploads.add); + const uploadIntoRef = useRef(uploadInto); + uploadAddRef.current = uploads.add; + uploadIntoRef.current = uploadInto; useEffect(() => { if (!isDesktop()) return; let dead = false; @@ -289,23 +294,38 @@ export function LibraryPage() { else if (event.payload.type === "leave") setDragging(false); else if (event.payload.type === "drop") { setDragging(false); - nativePaths(event.payload.paths, folderDropPath, (path) => { - setOpeningFolder(true); - setLoupe(false); - void openFolder(path).then( - (listing) => { - if (dead) return; - setOpeningFolder(false); - setDevelopPath(null); - setSheet(listing); - }, - () => { - if (dead) return; - setOpeningFolder(false); - setError(t.folderSheet.failed); - }, - ); - }); + nativePaths( + event.payload.paths, + folderDropPath, + (path) => { + setOpeningFolder(true); + setLoupe(false); + void openFolder(path).then( + (listing) => { + if (dead) return; + setOpeningFolder(false); + setDevelopPath(null); + setSheet(listing); + }, + () => { + if (dead) return; + setOpeningFolder(false); + setError(t.folderSheet.failed); + }, + ); + }, + async (paths) => { + const files: File[] = []; + for (const path of paths) { + const bytes = await readDroppedFile(path); + if (!bytes) continue; + const name = path.split(/[/\\]/).pop() || "photo.jpg"; + files.push(new File([bytes], name, { type: "image/jpeg" })); + } + return files; + }, + (files) => uploadAddRef.current(files, uploadIntoRef.current), + ); } }), ).then((stop) => { @@ -317,7 +337,6 @@ export function LibraryPage() { unlisten(); }; }, []); - const uploadInto = state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? state.scope : undefined; const openEvent = events.find((e) => e.id === uploadInto) ?? archivedEvents?.find((e) => e.id === uploadInto); useEffect(() => { const games = openEvent && !events.some((event) => event.id === openEvent.id) ? [openEvent, ...events] : events; diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 9f4dc50..e9f6ef7 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@photoreport/desktop", - "version": "0.3.29", + "version": "0.3.30", "private": true, "type": "module", "scripts": { diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 7d4a6f8..19eedc9 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "photoreport-desktop" -version = "0.3.29" +version = "0.3.30" edition = "2024" publish = false description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine." diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rs index 1ba8b13..7c73240 100644 --- a/apps/desktop/src-tauri/build.rs +++ b/apps/desktop/src-tauri/build.rs @@ -38,6 +38,7 @@ fn main() { "local_original_changed", "local_film_thumb", "folder_drop", + "drop_read", "folder_open", "folder_thumb", "folder_read", diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json index 838c588..71420a0 100644 --- a/apps/desktop/src-tauri/capabilities/default.json +++ b/apps/desktop/src-tauri/capabilities/default.json @@ -35,6 +35,7 @@ "allow-local-original-changed", "allow-local-film-thumb", "allow-folder-drop", + "allow-drop-read", "allow-folder-open", "allow-folder-thumb", "allow-folder-read", diff --git a/apps/desktop/src-tauri/permissions/autogenerated/drop_read.toml b/apps/desktop/src-tauri/permissions/autogenerated/drop_read.toml new file mode 100644 index 0000000..cbe80a1 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/drop_read.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-drop-read" +description = "Enables the drop_read command without any pre-configured scope." +commands.allow = ["drop_read"] + +[[permission]] +identifier = "deny-drop-read" +description = "Denies the drop_read command without any pre-configured scope." +commands.deny = ["drop_read"] diff --git a/apps/desktop/src-tauri/src/browse.rs b/apps/desktop/src-tauri/src/browse.rs index ea1321d..d77a124 100644 --- a/apps/desktop/src-tauri/src/browse.rs +++ b/apps/desktop/src-tauri/src/browse.rs @@ -17,6 +17,9 @@ use crate::local::read_film_thumb; pub struct OpenFolders { /// Canonical paths of folders the user actually dropped on the window. dropped: Mutex>, + /// Photos dropped as files (not inside a folder). Readable until the next drop. The page's file list + /// often receives only a few of them. + files: Mutex>, /// Folders opened as a contact sheet this session. Thumbnails stay inside these. open: Mutex>, } @@ -36,19 +39,40 @@ pub struct FolderFile { } impl OpenFolders { - /// Remember folders from a drop on this window. Files in the same drop are ignored. + /// Remember what was dropped on this window. Folders can be opened. Loose photos can be read back, + /// because the page's own file list keeps only a few of a large drop. pub fn note(&self, paths: &[PathBuf]) { let mut dropped = self.dropped.lock().unwrap(); + let mut files = self.files.lock().unwrap(); + files.clear(); for path in paths { - if !path.is_dir() { + if path.is_dir() { + if let Ok(canon) = path.canonicalize() { + dropped.insert(canon); + } + continue; + } + if !path.is_file() || !is_photo(path) { continue; } if let Ok(canon) = path.canonicalize() { - dropped.insert(canon); + files.insert(canon); } } } + /// A photo from the latest drop, canonical. Anything else is refused. + pub fn allow_dropped_file(&self, path: &Path) -> Result { + let canon = path.canonicalize().map_err(|_| "not_found".to_string())?; + if !canon.is_file() || !is_photo(&canon) { + return Err("not_a_photo".to_string()); + } + if !self.files.lock().unwrap().contains(&canon) { + return Err("not_allowed".to_string()); + } + Ok(canon) + } + /// The dropped folder, canonical, or an error when it was not dropped here or is not a folder. pub fn open(&self, path: &Path) -> Result { let canon = path.canonicalize().map_err(|e| e.to_string())?; @@ -296,6 +320,21 @@ fn listing(root: PathBuf) -> FolderListing { } } +/// One photo from the latest drop of loose files. The page uploads it. A path from anywhere else is refused. +#[tauri::command] +pub async fn drop_read( + folders: tauri::State<'_, OpenFolders>, + path: String, +) -> Result { + let p = folders.allow_dropped_file(Path::new(&path))?; + let meta = tokio::fs::metadata(&p).await.map_err(|e| e.to_string())?; + if meta.len() == 0 || meta.len() > 200 * 1024 * 1024 { + return Err("bad_file".to_string()); + } + let bytes = tokio::fs::read(&p).await.map_err(|e| e.to_string())?; + Ok(tauri::ipc::Response::new(bytes)) +} + /// The first dropped path that is a folder, so the page can open it instead of uploading the files inside. #[tauri::command] pub fn folder_drop(paths: Vec) -> Option { diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 2fe4707..40694fa 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -150,6 +150,7 @@ pub fn run() { local::local_stat, local::local_xmp, browse::folder_drop, + browse::drop_read, browse::folder_open, browse::folder_thumb, browse::folder_read, diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index b43d157..414a479 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "PhotoReport", - "version": "0.3.29", + "version": "0.3.30", "identifier": "pt.photoreport.desktop", "build": { "devUrl": "http://localhost:5173",