Compare commits

...
Author SHA1 Message Date
spark 5794660694 Stop an expired event pin from filing later shots into its folder.
When the pin is gone from the agenda and its ingest window has closed, arrivals follow the capture time instead of the old event.
2026-11-26 22:39:55 +00:00
spark 0a845f8bc6 Sign in to ZeroZero again when publish returns 403.
ci / rust (pull_request) Successful in 6m44s
ci / typescript (pull_request) Successful in 12m48s
A stale desk session answers Insufficient permissions instead of 401. One fresh login is tried before that refusal is accepted.
2026-11-26 22:20:55 +00:00
spark 56c115933c Do not fail a ZeroZero delivery when the account cannot publish.
ci / rust (pull_request) Successful in 4m10s
ci / typescript (pull_request) Successful in 11m13s
A photographer login may upload and still get 403 on photo-sync. The file is already on the desk, so that refusal is not a failed delivery.
2026-11-26 22:07:12 +00:00
spark 63b021cec8 Merge pull request 'Publish ZeroZero photos onto the public game after upload' (#310) from task/zerozero-publish-game into main
ci / rust (push) Successful in 4m23s
ci / typescript (push) Successful in 10m5s
2026-11-26 20:31:40 +00:00
spark 28f08bc5bc Publish ZeroZero photos onto the public game after upload.
ci / rust (pull_request) Successful in 4m15s
ci / typescript (pull_request) Successful in 10m36s
The desk keeps a file until photo-sync runs, so a delivery was done while the game stayed empty.
2026-11-26 20:11:48 +00:00
tiago-neves 7f44cba460 Merge pull request 'Desktop release builds open the local app and install their own updates (BIT-33402)' (#308) from task/BIT-33402-desktop-self-update into main
ci / rust (push) Successful in 4m10s
ci / typescript (push) Successful in 9m36s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Failing after 11m15s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Failing after 17m51s
desktop-release / build (, msi, windows-x86_64, windows) (push) Canceled after 0s
2026-11-26 15:25:05 +00:00
tiago-neves fcaa795b1d Merge branch 'main' into task/BIT-33402-desktop-self-update
ci / rust (pull_request) Successful in 11m45s
ci / typescript (pull_request) Successful in 15m6s
2026-11-26 15:09:48 +00:00
tiago-neves 6077a1062a Merge pull request 'fix(test): use date relative to now in ContextMenu event fixture (BIT-33405)' (#309) from task/BIT-33405-context-menu-date-flake into main
ci / rust (push) Successful in 11m52s
ci / typescript (push) Failing after 14m43s
2026-11-26 15:09:42 +00:00
spark e6b5f2e390 Let a Windows release, a Linux or Windows cable, and a future Developer ID join the desktop build.
ci / rust (pull_request) Successful in 11m45s
ci / typescript (pull_request) Failing after 14m55s
The installer job was waiting on a commented matrix row, USB stayed on Image Capture, face detection could not read the Windows CPU, and notarisation had nowhere to put an Apple account.
2026-11-26 15:09:36 +00:00
paula-alves 2a750ef916 fix(test): use date relative to now in ContextMenu event fixture (BIT-33405)
ci / rust (pull_request) Successful in 4m34s
ci / typescript (pull_request) Successful in 10m19s
The hardcoded startsAt 2026-11-21 fell outside EventsPanel RECENT_DAYS=4
window after 2026-11-25, collapsing the event under "Anteriores" and making
the test fail on every CI run. Derive startsAt, ingestFrom and ingestUntil
from Date.now() so the fixture stays inside the recent window regardless
of the run date.

Paperclip-Issue: BIT-33405
Paperclip-Agent: Bug Squasher (urlKey bug-squasher; id 4669adc7-6368-43ef-bf27-5a601a6b7b83)
2026-11-26 14:58:41 +00:00
spark 2a612a6f9a Keep a photo's arrival hash after it leaves the ingest folder.
ci / rust (pull_request) Successful in 4m9s
ci / typescript (pull_request) Failing after 9m40s
Filing rewrites the path, and a later caption change rewrites the hash. The index follows the filed file so the original can still be opened.
2026-11-26 14:45:06 +00:00
spark af63ea5673 Serve the installed interface from the app and let a release replace itself.
A production build was treated as development, so the window stayed on localhost:5173. Release builds now carry the updater key and install a newer signed shell on their own.
2026-11-26 14:45:06 +00:00
spark 452d84bff2 Merge pull request 'fix(shop): accept an order without a payment method (BIT-30361)' (#305) from task/BIT-30361-manual-payment into main
ci / rust (push) Successful in 4m24s
ci / typescript (push) Successful in 10m41s
2026-11-25 01:44:18 +00:00
paula-alves c75d4f81c3 Merge main so the autopilot suite sees a full-size frame.
ci / rust (pull_request) Successful in 7m6s
ci / typescript (pull_request) Successful in 12m43s
2026-11-25 01:31:06 +00:00
spark e731e48cb8 Merge pull request 'Define the full-frame size the autopilot tests record (BIT-33293)' (#307) from task/BIT-33293-autopilot-ci into main
ci / rust (push) Successful in 7m20s
ci / typescript (push) Successful in 12m53s
2026-11-25 01:30:42 +00:00
paula-alves cbd3f318d5 fix(shop): accept an order when no payment method is connected
ci / rust (pull_request) Successful in 4m18s
ci / typescript (pull_request) Failing after 8m42s
A buyer can still place the order. It stays unpaid until an admin records money collected out of band, and that admin is then responsible for delivering the work. No invoice goes out while invoicing is off.
2026-11-25 00:11:38 +00:00
38 changed files with 10982 additions and 83 deletions

No files matched your search

+51 -10
View File
@@ -1,8 +1,9 @@
name: desktop-release
# Tag `desktop-vX.Y.Z` builds the desktop installers and attaches them to a Gitea release.
# Linux builds on the standard runner. macOS (.dmg) builds on a Mac registered as a runner with the label "macos"
# (infra/desktop/macos-runner.sh, once); a release made while that Mac is off waits for it. Windows (.msi) needs a
# runner labelled "windows": register one, then uncomment its entry.
# (infra/desktop/macos-runner.sh, once); a release made while that Mac is off waits for it. Windows (.msi) builds
# on a runner labelled "windows" (Git bash, plus the WebView2 step). No Windows runner is registered yet, so a
# tag waits on that job until one is online. Notarisation runs only when the Apple secrets below are set.
#
# Self-updates (apps/desktop/src-tauri/src/updater.rs): with the secret TAURI_SIGNING_PRIVATE_KEY (and
# TAURI_SIGNING_PRIVATE_KEY_PASSWORD) and the variable TAURI_UPDATER_PUBKEY set (`tauri signer generate`), each job
@@ -14,6 +15,10 @@ on:
jobs:
build:
defaults:
run:
# Windows runners default to PowerShell. Git bash is what the rest of this job is written for.
shell: bash
strategy:
fail-fast: false
matrix:
@@ -25,9 +30,10 @@ jobs:
bundles: dmg,app
platform: darwin-universal
args: --target universal-apple-darwin
# - runner: windows
# bundles: msi
# platform: windows-x86_64
- runner: windows
bundles: msi
platform: windows-x86_64
args: ""
runs-on: ${{ matrix.runner }}
env:
VITE_API_URL: https://api.next.photoreport.pt
@@ -35,13 +41,23 @@ jobs:
PHOTOREPORT_UPDATER_PUBKEY: ${{ vars.TAURI_UPDATER_PUBKEY }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
# Empty until a Developer ID and an app-specific password (or an App Store Connect API key) are stored.
# Tauri notarises only when a full set is present; the install step drops blank values so a missing
# secret does not turn into a failed notarisation.
APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
APPLE_API_KEY_PATH: ${{ secrets.APPLE_API_KEY_PATH }}
steps:
- uses: actions/checkout@v4
- name: System libraries (Linux)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libsecret-1-dev
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libsecret-1-dev libgphoto2-dev pkg-config
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
@@ -68,6 +84,10 @@ jobs:
sleep 15
done
test "$ok" = 1
- name: WebView2 runtime (Windows)
if: runner.os == 'Windows'
shell: powershell
run: powershell -NoProfile -ExecutionPolicy Bypass -File infra/desktop/windows-webview2.ps1
- name: Both Mac processors (universal app)
if: runner.os == 'macOS'
run: rustup target add aarch64-apple-darwin x86_64-apple-darwin
@@ -82,11 +102,32 @@ jobs:
- name: Installers
shell: bash
run: |
# Blank Apple secrets must not look "set", or Tauri tries to notarise with an empty account.
for name in APPLE_SIGNING_IDENTITY APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID APPLE_API_ISSUER APPLE_API_KEY APPLE_API_KEY_PATH; do
if [[ -z "${!name:-}" ]]; then
unset "$name"
fi
done
extra=()
# Signed updater artifacts only when the release key is there (a build without it still works).
# The bundler checks each signature against plugins.updater.pubkey, so the public key goes into the config too.
if [[ -n "$TAURI_SIGNING_PRIVATE_KEY" ]]; then
extra=(--config "$(node -e 'console.log(JSON.stringify({bundle:{createUpdaterArtifacts:true},plugins:{updater:{pubkey:process.env.PHOTOREPORT_UPDATER_PUBKEY}}}))')")
# Updater artifacts when the release key is there. A Developer ID also turns on the hardened
# runtime with the entitlements the bundled ONNX library needs, which is what notarisation requires.
config="$(node -e '
const bundle = {};
const plugins = {};
if (process.env.TAURI_SIGNING_PRIVATE_KEY) {
bundle.createUpdaterArtifacts = true;
plugins.updater = { pubkey: process.env.PHOTOREPORT_UPDATER_PUBKEY };
}
if (process.platform === "darwin" && process.env.APPLE_SIGNING_IDENTITY) {
bundle.macOS = { hardenedRuntime: true, entitlements: "entitlements.plist" };
}
const cfg = {};
if (Object.keys(bundle).length) cfg.bundle = bundle;
if (Object.keys(plugins).length) cfg.plugins = plugins;
if (Object.keys(cfg).length) process.stdout.write(JSON.stringify(cfg));
')"
if [[ -n "$config" ]]; then
extra=(--config "$config")
fi
pnpm --filter @photoreport/desktop exec tauri build --bundles ${{ matrix.bundles }} ${{ matrix.args }} "${extra[@]}"
- name: Update manifest
+1
View File
@@ -175,6 +175,7 @@ export class ZerozeroTransport implements Transport {
const account = await this.client.login();
const author = meta?.author?.trim() || account.name || "PhotoReport";
const imageId = await this.client.upload(gameId, fileName, data, author);
await this.client.publish(gameId, imageId);
return `${gameId}/${imageId}`;
});
}
+145
View File
@@ -1,6 +1,45 @@
import { describe, expect, it } from "vitest";
import { TransportError } from "./transports.js";
import { ZerozeroClient } from "./zerozero.js";
/**
* A desk that is already willing to sign the client in, and answers photo-sync however the test says.
* Login is the real OAuth dance; only the publish routes vary.
*/
function desk(publish: (pathname: string) => Response): typeof fetch {
return async (input, init) => {
const url = new URL(String(input));
const method = init?.method ?? "GET";
const cookie = new Headers(init?.headers).get("cookie") ?? "";
const has = (name: string) => cookie.split(/;\s*/).some((part) => part.startsWith(`${name}=`));
if (url.hostname === "www.zerozero.pt" && url.pathname === "/oauth.php") {
if (has("zzuser")) {
return new Response(null, {
status: 302,
headers: { location: "https://fotos.zerozero.pt/api/auth/callback?code=c&state=s" },
});
}
return new Response("login", { status: 200, headers: { "set-cookie": "PHPSESSID=s; Domain=.zerozero.pt" } });
}
if (url.hostname === "www.zerozero.pt" && url.pathname === "/ax_login.php" && method === "POST") {
return new Response(JSON.stringify({ status: true }), { headers: { "set-cookie": "zzuser=1; Domain=.zerozero.pt" } });
}
if (url.pathname === "/api/auth/login") {
return Response.json({ authURL: "https://www.zerozero.pt/oauth.php?response_type=code&state=s" });
}
if (url.pathname === "/api/auth/callback") {
return new Response(null, { status: 302, headers: { location: "https://fotos.zerozero.pt/", "set-cookie": "desk=ok; Path=/" } });
}
if (url.pathname === "/api/auth/me") {
if (!has("desk")) return Response.json({ error: "unauthorized" }, { status: 401 });
return Response.json({ role: "photographer", photographer_name: "Kapta+" });
}
if (url.pathname === "/") return new Response("desk", { status: 200 });
if (method === "POST" && url.pathname.startsWith("/api/photo-sync/")) return publish(url.pathname);
return new Response("no", { status: 404 });
};
}
describe("zerozero remove", () => {
it("never asks the desk to delete a \"synced-\" placeholder (a real image is taken back: test/delivery.test.ts)", async () => {
const calls: string[] = [];
@@ -14,3 +53,109 @@ describe("zerozero remove", () => {
expect(calls).toEqual([]);
});
});
describe("zerozero publish", () => {
it("publishes the one photo that was just uploaded", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
return Response.json({ synced: 1, failed: 0, failures: [] });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual(["/api/photo-sync/img-9"]);
});
it("publishes the game when the account cannot publish one photo", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
if (pathname.startsWith("/api/photo-sync/match/")) return Response.json({ synced: 1, failed: 0, failures: [] });
return Response.json({ error: "forbidden" }, { status: 403 });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/img-9", "/api/photo-sync/match/12627743"]);
});
it("signs in again when publish answers insufficient permissions", async () => {
const calls: string[] = [];
let refused = false;
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
if (!refused && pathname === "/api/photo-sync/img-9") {
refused = true;
return Response.json({ error: "Insufficient permissions" }, { status: 403 });
}
return Response.json({ synced: 1, failed: 0, failures: [] });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/img-9"]);
});
it("publishes the whole game when the desk has no single-photo publish", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
if (pathname === "/api/photo-sync/match/12627743") return Response.json({ synced: 1, failed: 0, failures: [] });
return new Response("missing", { status: 404 });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/match/12627743"]);
});
it("publishes the game when the desk already had the file and there is no image id", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
return Response.json({ synced: 0, failed: 0, failures: [] });
}),
);
await client.publish("12627743", "synced-PS_jogo_1.jpg");
expect(calls).toEqual(["/api/photo-sync/match/12627743"]);
});
it("retries when the desk reports that this photo did not publish", async () => {
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk(() => Response.json({ synced: 0, failed: 1, failures: [{ id: "img-9", error: "desk busy" }] })),
);
const err = await client.publish("12627743", "img-9").then(
() => null,
(error: unknown) => error,
);
expect(err).toBeInstanceOf(TransportError);
expect((err as TransportError).message).toBe("zerozero publish: desk busy");
expect((err as TransportError).transient).toBe(true);
});
it("keeps the upload when the account is not allowed to publish", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
return Response.json({ error: "Insufficient permissions" }, { status: 403 });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual([
"/api/photo-sync/img-9",
"/api/photo-sync/img-9",
"/api/photo-sync/match/12627743",
"/api/photo-sync/match/12627743",
]);
});
});
+103 -2
View File
@@ -11,12 +11,16 @@ import { TransportError } from "./transports.js";
* Lisbon time).
* - Upload: tus 1.0 at `/api/upload?match_id=<id>`, metadata `match_id`, `artist` (the author shown with the photo)
* and the file name. The image's id is the upload's id; `DELETE /api/images/<id>` takes it back.
* - Publish: the upload only lands on the desk. The public game shows it after `POST /api/photo-sync/<image id>`
* (the desk's "send now"). When that route is missing, `POST /api/photo-sync/match/<id>` publishes the game.
*/
export const ZEROZERO_URL = "https://fotos.zerozero.pt";
const LOGIN_SITE = "https://www.zerozero.pt";
const CHUNK = 5 * 1024 * 1024;
const TIMEOUT_MS = 60_000;
/** Publishing pushes the file onwards to the public game, which is slower than one tus chunk. */
const PUBLISH_TIMEOUT_MS = 180_000;
export interface ZerozeroGame {
id: string;
@@ -104,7 +108,7 @@ export class ZerozeroClient {
) {}
/** One request with the jar's cookies; redirects followed by hand so every hop's cookies are kept. */
private async request(url: string, init: RequestInit = {}, hops = 10): Promise<{ res: Response; url: string }> {
private async request(url: string, init: RequestInit = {}, hops = 10, timeoutMs = TIMEOUT_MS): Promise<{ res: Response; url: string }> {
let current = url;
let options = init;
for (let i = 0; i <= hops; i++) {
@@ -114,7 +118,7 @@ export class ZerozeroClient {
if (!headers.has("user-agent")) headers.set("user-agent", "PhotoReport/2 (delivery)");
let res: Response;
try {
res = await this.fetchImpl(current, { ...options, headers, redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS) });
res = await this.fetchImpl(current, { ...options, headers, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) });
} catch (err) {
throw new TransportError(`zerozero: ${fetchFailure(err)}`, true);
}
@@ -263,6 +267,78 @@ export class ZerozeroClient {
return new URL(url).pathname.split("/").filter(Boolean).pop()!;
}
/**
* Puts an uploaded photo on the public game. The desk keeps it first (`sync_status` pending); without this call
* it never leaves the photographer's page. One photo when the desk allows it, otherwise the whole game.
* `synced-<file name>` is not an image id (the desk already had the file), so the game is published.
*/
async publish(gameId: string, imageId: string): Promise<void> {
const placeholder = imageId.startsWith("synced-");
if (!placeholder) {
const one = await this.postApi(`/photo-sync/${encodeURIComponent(imageId)}`, PUBLISH_TIMEOUT_MS);
// 404/405: this desk has no single-photo publish. 403: this account may still publish the game.
if (one.status !== 404 && one.status !== 405 && one.status !== 403) {
this.assertPublished(one, imageId);
return;
}
}
const match = await this.postApi(`/photo-sync/match/${encodeURIComponent(gameId)}`, PUBLISH_TIMEOUT_MS);
// A photographer account may upload but not publish ("Insufficient permissions"). The file is already on
// the desk; failing the delivery here only blocks the queue. The desk publishes those itself.
if (match.status === 403) return;
const ours = placeholder ? null : imageId;
this.assertPublished(match, ours);
}
private async postApi(path: string, timeoutMs: number, retry = true): Promise<{ status: number; body: unknown }> {
await this.login();
// The desk's own client posts JSON. An empty object is what "send now" sends when it has no extra fields.
const { res } = await this.request(
`${this.base}/api${path}`,
{
method: "POST",
headers: { "content-type": "application/json", accept: "application/json" },
body: "{}",
},
10,
timeoutMs,
);
// 401: logged out. 403 "Insufficient permissions": the cookie is still sent, but the session is no longer
// the photographer. One fresh sign-in. The same refusal after that is the account, not a stale login.
if (res.status === 401 && retry) {
this.account = null;
this.jar.clear();
return this.postApi(path, timeoutMs, false);
}
if (res.status === 403 && retry) {
this.account = null;
this.jar.clear();
return this.postApi(path, timeoutMs, false);
}
const text = await res.text();
let body: unknown = null;
if (text) {
try {
body = JSON.parse(text) as unknown;
} catch {
body = null;
}
}
return { status: res.status, body };
}
private assertPublished(result: { status: number; body: unknown }, imageId: string | null): void {
if (result.status >= 200 && result.status < 300) {
assertSyncBody(result.body, imageId);
return;
}
const detail = errorText(result.body);
const transient = result.status >= 500 || result.status === 429 || result.status === 404;
let message = `zerozero publish: ${result.status}`;
if (detail) message = `${message} ${detail}`;
throw new TransportError(message, transient);
}
/** Takes an uploaded image back. Already gone (or no longer this account's to remove) is not an error. */
async remove(imageId: string): Promise<void> {
// "synced-<file name>" (from `upload`, when the desk already had the file) is not a real image id: there was
@@ -275,6 +351,31 @@ export class ZerozeroClient {
}
}
function errorText(body: unknown): string | null {
if (!body || typeof body !== "object") return null;
const error = (body as { error?: unknown }).error;
if (typeof error !== "string" || !error) return null;
return error.replace(/\s+/g, " ").slice(0, 180);
}
function assertSyncBody(body: unknown, imageId: string | null): void {
if (!body || typeof body !== "object") return;
const record = body as { sync_status?: unknown; syncStatus?: unknown; failures?: unknown; error?: unknown };
const status = record.sync_status ?? record.syncStatus;
if (status === "failed") {
const message = typeof record.error === "string" && record.error ? record.error : "the desk could not publish the photo";
throw new TransportError(`zerozero publish: ${message}`, true);
}
if (!imageId || !Array.isArray(record.failures)) return;
for (const failure of record.failures) {
if (!failure || typeof failure !== "object") continue;
const row = failure as { id?: unknown; error?: unknown };
if (row.id !== imageId) continue;
const message = typeof row.error === "string" && row.error ? row.error : "the desk could not publish the photo";
throw new TransportError(`zerozero publish: ${message}`, true);
}
}
function toGame(r: Record<string, unknown> | null | undefined): ZerozeroGame | null {
if (!r) return null;
const s = (v: unknown) => (typeof v === "string" || typeof v === "number" ? String(v) : null);
+11
View File
@@ -388,6 +388,17 @@ export async function registerShopAdminRoutes(app: FastifyInstance, deps: { db:
return { orders: views };
});
/** Payment collected outside the shop. Delivery starts; the admin owns handing the work over. */
app.post("/v1/orders/:id/payment-received", { preHandler: authenticate }, async (req) => {
const { id } = IdParams.parse(req.params);
const order = await db.order.findUnique({ where: { id } });
if (!order) throw notFound("order_not_found");
await requireMembership(db, req, order.organizationId, "ADMIN");
if (order.status !== "PENDING") throw badRequest("order_not_pending");
await shop.markPaid(id, "manual");
return shop.orderView(id, null);
});
app.post("/v1/orders/:id/items/:itemId/shipped", { preHandler: authenticate }, async (req) => {
const { id, itemId } = z.object({ id: z.uuid(), itemId: z.uuid() }).parse(req.params);
const order = await db.order.findUnique({ where: { id }, include: { items: { where: { id: itemId } } } });
+6 -1
View File
@@ -497,7 +497,12 @@ export class ShopService {
await this.markPaid(order.id, press ? "press" : "free");
return { order: await this.orderView(order.id, order.accessToken), checkoutUrl: null, token: order.accessToken };
}
if (!org.stripeSecretSealed || !secrets) throw new ShopError("payments_not_configured", 503);
// No payment method: the order is still accepted. An admin collects the money out of band
// and only then does delivery start. Invoicing stays off until a provider is connected.
if (!org.stripeSecretSealed || !secrets) {
this.deps.log.info({ orderId: order.id }, "shop: order accepted without a payment method");
return { order: await this.orderView(order.id, order.accessToken), checkoutUrl: null, token: order.accessToken };
}
const checkout = await createCheckout(
secrets.open(org.stripeSecretSealed),
{
+9
View File
@@ -75,6 +75,8 @@ class FakeNextcloud {
class FakeZerozero {
logins = 0;
removed: string[] = [];
/** Paths of POST /api/photo-sync/… after each upload (the public game, not only the desk). */
syncs: string[] = [];
uploads = new Map<string, { gameId: string; meta: Record<string, string>; data: Buffer; length: number }>();
password = "zz-pass";
@@ -129,6 +131,10 @@ class FakeZerozero {
this.uploads.set(id, { gameId: url.searchParams.get("match_id")!, meta, data: Buffer.alloc(0), length: Number(h.get("upload-length")) });
return new Response(null, { status: 201, headers: { location: `/upload/${id}` } });
}
if (method === "POST" && url.pathname.startsWith("/api/photo-sync/")) {
this.syncs.push(url.pathname);
return Response.json({ synced: 1, failed: 0, failures: [] });
}
const gone = /^\/api\/images\/(.+)$/.exec(url.pathname);
if (gone && method === "DELETE") {
this.removed.push(gone[1]!);
@@ -622,6 +628,8 @@ describe("delivery", () => {
expect(first.meta).toMatchObject({ match_id: "12627747", artist: "Peter Spark / Kapta+", filename: "PS_SC Torreense x Sunderland_1.jpg", filetype: "image/jpeg" });
expect(first.data.length).toBe(first.length);
expect((await sharp(first.data).metadata()).width).toBe(3000);
// The desk upload is not the public game: each photo is published there before the delivery is done.
expect(zz.syncs).toEqual(["/api/photo-sync/img-1", "/api/photo-sync/img-2"]);
// Signed in once for the whole batch.
expect(zz.logins).toBe(1);
@@ -644,6 +652,7 @@ describe("delivery", () => {
expect(zz.removed).toEqual([itemA.remotePath!.split("/")[1]]);
// Same name ({n} kept), shown once in the game.
expect(zz.uploads.get(resent.remotePath!.split("/")[1]!)!.meta.filename).toBe(zz.uploads.get(itemA.remotePath!.split("/")[1]!)!.meta.filename);
expect(zz.syncs.at(-1)).toBe(`/api/photo-sync/${resent.remotePath!.split("/")[1]}`);
expect(await delivery.queueEdited()).toBe(0);
// A reject that bypassed the library PATCH (flag flipped in the DB) is still taken back on the next sweep.
+25
View File
@@ -212,6 +212,31 @@ describe("shop", () => {
expect((await ctx.db.order.findUniqueOrThrow({ where: { id: order.id } })).status).toBe("FULFILLED");
});
it("accepts an order when Stripe is off, and delivery waits until an admin records the payment", async () => {
const s = await setup();
expect((await s.api("PUT", `/v1/orgs/${s.orgId}/shop-settings`, { stripeSecretKey: "", stripeWebhookSecret: "" })).statusCode).toBe(200);
const g = await gallery(s, { title: "Sem Stripe" });
const created = await pub("POST", "/v1/public/orders", {
gallery: g.slug,
email: "[email protected]",
name: "Ana Costa",
country: "PT",
items: [{ photoId: s.photos[0], productId: s.digital.id, quantity: 1 }],
});
expect(created.statusCode).toBe(201);
const body = created.json() as { order: { id: string; status: string; totalCents: number }; checkoutUrl: string | null };
expect(body.checkoutUrl).toBeNull();
expect(body.order).toMatchObject({ status: "PENDING" });
expect(body.order.totalCents).toBeGreaterThan(0);
expect(await shop.claimDownloads(5)).toEqual([]);
const paid = await s.api("POST", `/v1/orders/${body.order.id}/payment-received`);
expect(paid.statusCode).toBe(200);
expect(paid.json()).toMatchObject({ status: "PAID" });
const [itemId] = await shop.claimDownloads(5);
expect(itemId).toEqual(expect.any(String));
});
it("reverse-charges VAT for EU businesses with a valid number, and gives free galleries away", async () => {
const s = await setup();
const g = await gallery(s, { title: "Clube" });
+2
View File
@@ -1113,6 +1113,8 @@ export const t = {
orderStatus: { PENDING: "por pagar", PAID: "paga", FULFILLED: "concluída", CANCELLED: "cancelada", REFUNDED: "reembolsada" },
itemStatus: { PENDING: "a preparar", RUNNING: "a preparar", READY: "pronto", SHIPPED: "enviado", FAILED: "falhou" },
markShipped: "Marcar enviada",
collectPayment: "Pagamento recebido",
confirmCollectPayment: "Recebeste o pagamento fora da loja? A encomenda passa a paga e ficas responsável por entregar o trabalho.",
reverseCharge: "Autoliquidação",
noOrders: "Sem encomendas.",
productsHelp: "Preços com IVA incluído. JPEG: tamanho do lado maior (0 = original). Impressões: tamanho e prazo de envio.",
+7 -3
View File
@@ -5,6 +5,10 @@ import { EventsPanel } from "./EventsPanel.js";
import { PhotoContextMenu } from "./PhotoContextMenu.js";
function event(id: string, title: string): EventSummary {
const startsAt = new Date(Date.now() - 86_400_000);
const iso = startsAt.toISOString();
const at = (offsetMs: number) =>
new Date(startsAt.getTime() + offsetMs).toISOString();
return {
id,
organizationId: "org",
@@ -20,9 +24,9 @@ function event(id: string, title: string): EventSummary {
competitionCode: null,
round: null,
matchNumber: null,
startsAt: "2026-11-21T10:56:00.000Z",
ingestFrom: "2026-11-21T08:56:00.000Z",
ingestUntil: "2026-11-21T14:56:00.000Z",
startsAt: iso,
ingestFrom: at(-2 * 3_600_000),
ingestUntil: at(4 * 3_600_000),
iptcTemplate: {},
archivedAt: null,
photographers: [],
+12 -3
View File
@@ -3,7 +3,7 @@ import type { EventSummary } from "@photoreport/sdk";
import { useAuth } from "../auth.js";
import { planLocalAutopilot } from "../offline/autopilot.js";
import { cache } from "../offline/cache.js";
import { eventForArrival, exifDateTime, exifLens, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
import { eventForArrival, exifDateTime, exifLens, lisbonDay, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
import { localId, offlineQueue } from "../offline/queue.js";
import { useCallback, useEffect, useRef, useState } from "react";
import { t } from "../i18n.js";
@@ -89,6 +89,12 @@ type Add = (
export const eventLabel = (e: Pick<EventSummary, "title" | "home" | "away">) => e.title || [e.home, e.away].filter(Boolean).join(" x ");
/** The pin's own ingest window, when the agenda no longer lists that event. */
export function pinWindow(to: FtpTarget | null): { ingestFrom: string; ingestUntil: string } | null {
if (!to?.ingestFrom || !to.ingestUntil) return null;
return { ingestFrom: to.ingestFrom, ingestUntil: to.ingestUntil };
}
function savedTarget(): FtpTarget | null {
try {
const v = JSON.parse(prefs.get("ftp.target") ?? "null") as FtpTarget | null;
@@ -177,7 +183,7 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
const events = cached?.events ?? [];
const capturedAt = lisbonInstant(exifDateTime(preview));
// Open FTP target always; eventForArrival drops an archived leftover and keeps shots inside the window.
const eventId = eventForArrival(to?.id ?? null, events, capturedAt);
const eventId = eventForArrival(to?.id ?? null, events, capturedAt, pinWindow(to));
const filed = events.find((e) => e.id === eventId);
if (!localPhotos.bySha(info.sha256)) {
let url = "";
@@ -239,9 +245,12 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
sentEvent = eventLabel(filed);
sentDate = filed.startsAt.slice(0, 10);
} else if (to && eventId === to.id) {
// The pin is not in the cached list (no capture time, or this computer has not seen the event).
// The pin is not in the cached list and its window still covers this shot.
sentEvent = to.title;
sentDate = to.date;
} else if (capturedAt) {
// No event for this time: file under the shoot day (Desktop/2026/20261126), not the expired pin.
sentDate = lisbonDay(capturedAt);
}
invoke("ftp_sent", { path: f.path, event: sentEvent, date: sentDate })
.then(() => {
+16 -5
View File
@@ -2,10 +2,10 @@ import type { EventSummary } from "@photoreport/sdk";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { t } from "../i18n.js";
import { cache } from "../offline/cache.js";
import { eventForArrival, exifDateTime, lisbonInstant } from "../offline/local.js";
import { eventForArrival, exifDateTime, lisbonDay, lisbonInstant } from "../offline/local.js";
import { retryPhotoFile } from "../desktop/lightroomSidecar.js";
import { asArrayBuffer, prefs } from "../platform.js";
import { type FtpTarget, type IncomingFile, type Invoke, eventLabel } from "./LocalFtp.js";
import { type FtpTarget, type IncomingFile, type Invoke, eventLabel, pinWindow } from "./LocalFtp.js";
import type { PreviewOf, UploadStatus } from "./uploads.js";
/** What the desktop shell reports for a PTP body on the USB cable (`camera.rs`). */
@@ -103,16 +103,27 @@ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | nul
const events = cached?.events ?? [];
const capturedAt = lisbonInstant(exifDateTime(bytes));
// Always the open USB target — never drop a live pull into Sem evento because the agenda cache is stale.
const eventId = eventForArrival(to?.id ?? null, events, capturedAt);
const eventId = eventForArrival(to?.id ?? null, events, capturedAt, pinWindow(to));
const filed = events.find((e) => e.id === eventId);
let sentEvent = "";
let sentDate = "";
if (filed) {
sentEvent = eventLabel(filed);
sentDate = filed.startsAt.slice(0, 10);
} else if (to && eventId === to.id) {
sentEvent = to.title;
sentDate = to.date;
} else if (capturedAt) {
sentDate = lisbonDay(capturedAt);
}
add([file], eventId ?? undefined, (_file, result) => {
inFlight.current--;
if (result === "done" || result === "duplicate") {
setCounts((c) => ({ ...c, sent: c.sent + 1 }));
invoke("ftp_sent", {
path: f.path,
event: filed ? eventLabel(filed) : (to?.title ?? ""),
date: filed ? filed.startsAt.slice(0, 10) : (to?.date ?? ""),
event: sentEvent,
date: sentDate,
})
.then(() => {
retryPhotoFile(original.sha256);
+29 -3
View File
@@ -102,6 +102,16 @@ function readTiff(v: DataView, start: number, end: number): { date: string | nul
};
}
/** Lisbon calendar day of an ISO instant, "YYYY-MM-DD" (the work-folder date). */
export function lisbonDay(iso: string): string {
return new Intl.DateTimeFormat("en-CA", {
timeZone: "Europe/Lisbon",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).format(new Date(iso));
}
/** "2026:10:09 20:26:47" (Lisbon wall time, as the API reads it) to an ISO instant. */
export function lisbonInstant(exif: string | null): string | null {
const m = exif?.match(/^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})/);
@@ -137,19 +147,35 @@ export function routeLocally(events: RoutedEvent[], at: string | null): string |
return bestEventForCapture(events, at)?.id ?? null;
}
function windowCovers(window: { ingestFrom: string; ingestUntil: string } | null | undefined, at: string): boolean {
if (!window) return true;
const t = Date.parse(at);
const from = Date.parse(window.ingestFrom);
const until = Date.parse(window.ingestUntil);
if (!Number.isFinite(t) || !Number.isFinite(from) || !Number.isFinite(until)) return true;
return from <= t && t <= until;
}
/**
* Where a photo arrives on this computer. With a capture time, the pin (FTP target / open event) wins only
* inside that event's window — leftover pins from the morning studio must not swallow the afternoon training.
* Without a capture time, keep the pin (same as the server): USB auto-pull already filtered by the window via
* the card clock, and inventing "now" is what we must not do.
* A pin missing from the agenda is kept only while its own window still covers the shot. An expired pin
* (the event dropped off the list) must not keep filing the next day into that folder.
*/
export function eventForArrival(pinnedId: string | null, events: RoutedEvent[], at: string | null): string | null {
export function eventForArrival(
pinnedId: string | null,
events: RoutedEvent[],
at: string | null,
pinWindow?: { ingestFrom: string; ingestUntil: string } | null,
): string | null {
if (!at) return pinnedId;
if (!pinnedId) return routeLocally(events, at);
const pinned = events.find((e) => e.id === pinnedId);
if (!pinned) {
// Agenda cache miss: keep the open pin so USB/FTP does not dump live shots into Sem evento.
return pinnedId;
if (windowCovers(pinWindow, at)) return pinnedId;
return routeLocally(events, at);
}
if (pinned.archivedAt) return routeLocally(events, at);
const t = Date.parse(at);
+20 -1
View File
@@ -150,8 +150,27 @@ describe("photos arriving on this computer", () => {
// No capture time: keep the pin (USB already filtered by the card clock; server keeps the named folder too).
expect(eventForArrival("braga", events, null)).toBe("braga");
expect(eventForArrival(null, events, null)).toBeNull();
// Cache miss for the pin id: keep it (do not dump into Sem evento); archived pins fall through to the clock.
// Cache miss for the pin id: keep it while its window is unknown or still open.
expect(eventForArrival("missing", events, "2026-10-10T15:30:00Z")).toBe("missing");
expect(
eventForArrival("missing", events, "2026-10-09T19:26:47.000Z", {
ingestFrom: "2026-10-09T17:15:00Z",
ingestUntil: "2026-10-09T23:15:00Z",
}),
).toBe("missing");
// The pin left the agenda and its window has closed: file by the clock, not into that old folder.
expect(
eventForArrival("studio", events, "2026-11-26T20:20:00Z", {
ingestFrom: "2026-11-24T11:08:00.000Z",
ingestUntil: "2026-11-24T17:08:00.000Z",
}),
).toBeNull();
expect(
eventForArrival("studio", events, "2026-10-10T15:30:00Z", {
ingestFrom: "2026-10-09T17:15:00Z",
ingestUntil: "2026-10-09T23:15:00Z",
}),
).toBe("other");
expect(eventForArrival("braga", [{ ...events[0]!, archivedAt: "2026-10-10T00:00:00Z" }, events[1]!], "2026-10-10T15:30:00Z")).toBe("other");
});
+10
View File
@@ -387,6 +387,16 @@ function Orders({ orgId, isAdmin }: { orgId: string; isAdmin: boolean }) {
{o.invoice.number}
</a>
)}
{isAdmin && o.status === "PENDING" && !o.checkoutUrl && o.totalCents > 0 && (
<button
className="ml-3 underline"
onClick={() => {
if (window.confirm(t.shop.confirmCollectPayment)) void api.recordPayment(o.id).then(replace);
}}
>
{t.shop.collectPayment}
</button>
)}
{isAdmin && (o.status === "PAID" || o.status === "FULFILLED") && (
<button
className="ml-3 underline"
+6 -4
View File
@@ -12,9 +12,9 @@ What the shell adds today:
- Refresh token in the OS keychain (macOS Keychain, Windows Credential Manager, Linux Secret Service).
Without a keychain the session stays in memory and ends when the app closes.
- Local FTP server for cameras (`src/ftp.rs`, Library → **FTP local**). See below.
- USB tether (`src/camera.rs` + `camera_mac.m`, Library → **USB**): pulses the PTP session so the body stays
shootable (no permanent computer/busy screen), pulls new shots to the open event, syncs the clock. EOS Utility
must not hold the cable.
- USB tether (Library → **USB**): a short PTP session lists the card and downloads what was asked, then
closes so the body can shoot. macOS uses Image Capture (`camera_mac.m`). Linux uses libgphoto2. Windows uses
the portable-device API. EOS Utility must not hold the cable. The Mac build is the one that sets the camera clock.
- Local catalogue (`src/catalog.rs`, Preferências → **Catálogo local**). See below.
- Works without network: when the server can't be reached at start-up, the window opens the copy of the web app
bundled in the installer (photo engine included), so the catalogue, local FTP and editing originals on disk go on;
@@ -41,7 +41,9 @@ signed shell at once; the API reads the latest
installer through, so the private repository stays private. Installers are signed with the release key
(`tauri signer generate`): the private key and its password are the Gitea secrets `TAURI_SIGNING_PRIVATE_KEY` and
`TAURI_SIGNING_PRIVATE_KEY_PASSWORD`, the public key is the variable `TAURI_UPDATER_PUBKEY` (compiled into the app
as `PHOTOREPORT_UPDATER_PUBKEY`). A build without the public key never updates itself.
as `PHOTOREPORT_UPDATER_PUBKEY`). A release build also reads that same public key from `updater-pubkey.txt` when the
variable is unset, and checks again in the background, so the installed app replaces itself. A debug build without
the variable never updates itself.
## Local FTP (camera → this computer → event)
+9256
View File
File diff suppressed because it is too large. Load diff
+22
View File
@@ -9,6 +9,13 @@ description = "PhotoReport desktop: the web app in a native shell, with keychain
name = "photoreport_desktop_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
# Production serves the interface from this computer. Without this feature Tauri treats every
# build as development and the window opens http://localhost:5173, which stays blank unless
# `tauri dev` is running. `tauri dev` turns the feature off and uses the dev server.
[features]
default = ["custom-protocol"]
custom-protocol = ["tauri/custom-protocol"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
cc = "1"
@@ -44,6 +51,21 @@ rustls = { version = "0.23", default-features = false, features = ["ring"] }
[target.'cfg(all(target_os = "macos", target_arch = "aarch64"))'.dependencies]
ort = { version = "=2.0.0-rc.14", default-features = false, features = ["std", "download-binaries", "copy-dylibs", "api-31", "tls-native", "coreml"] }
# Linux USB: libgphoto2 (PTP). The Mac build keeps Image Capture and does not link this.
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
gphoto2 = "=3.4.1"
# Windows USB: the portable-device API, which speaks PTP through the driver Windows already loaded.
[target.'cfg(target_os = "windows")'.dependencies]
windows = { version = "0.61", features = [
"Win32_Devices_PortableDevices",
"Win32_Foundation",
"Win32_System_Com",
"Win32_System_Com_StructuredStorage",
"Win32_System_Ole",
"Win32_System_Variant",
] }
# Release builds: no symbols or debug info, whole-program optimisation, no unwinding tables. The binary only tells
# a disassembler what machine code does, not what the functions were called.
[profile.release]
+28 -1
View File
@@ -1,4 +1,5 @@
fn main() {
publish_updater_key();
let target = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
if target == "macos" {
// ImageCaptureCore: PTP cameras (they never mount as a volume).
@@ -87,6 +88,27 @@ fn main() {
link_coreml_compiler_rt();
}
/// Release builds always carry the official update key, so an installed app can replace itself from the API.
/// `option_env!` is not a cargo fingerprint: the key has to be passed with `cargo:rustc-env` or a later compile
/// keeps the previous value. A debug build stays without it unless the variable is set for that compile.
fn publish_updater_key() {
println!("cargo:rerun-if-env-changed=PHOTOREPORT_UPDATER_PUBKEY");
let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
let path = std::path::Path::new(&manifest).join("updater-pubkey.txt");
println!("cargo:rerun-if-changed={}", path.display());
let from_env = std::env::var("PHOTOREPORT_UPDATER_PUBKEY").unwrap_or_default();
let mut key = from_env.trim().to_string();
let profile = std::env::var("PROFILE").unwrap_or_default();
if key.is_empty() && profile == "release" {
let from_file = std::fs::read_to_string(&path).unwrap_or_default();
key = from_file.trim().to_string();
}
if key.is_empty() {
return;
}
println!("cargo:rustc-env=PHOTOREPORT_UPDATER_PUBKEY={key}");
}
/// ONNX Runtime's Core ML objects call `___isPlatformVersionAtLeast`. That helper lives in compiler-rt, which Rust's
/// linker does not pull in, so the desktop build (deployment target 11) fails on the arm64 slice.
fn link_coreml_compiler_rt() {
@@ -96,7 +118,12 @@ fn link_coreml_compiler_rt() {
return;
}
let Ok(output) = std::process::Command::new("xcrun")
.args(["--sdk", "macosx", "clang", "-print-file-name=libclang_rt.osx.a"])
.args([
"--sdk",
"macosx",
"clang",
"-print-file-name=libclang_rt.osx.a",
])
.output()
else {
return;
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- The bundled ONNX runtime is not an Apple-signed library. Notarisation requires the hardened runtime, and that runtime refuses the library unless this is set. -->
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
</dict>
</plist>
+109 -21
View File
@@ -1,13 +1,17 @@
//! USB tether (macOS). A Canon (or any PTP body) does not show up as a disk; ImageCaptureCore
//! (`camera_mac.m`) briefly opens a PTP session to list/download, then closes it so the body can
//! shoot (a held session + `requestEnableTethering` put many cameras on the computer/busy screen).
//! The session stays off until the photographer turns the cable on. Nothing is copied until they
//! pick files (`camera_import`) or auto-ingest asks. Chosen files land in `<ingest>/.usb` and the
//! web app polls `camera_take` to file them like a local-FTP photo.
//! USB tether. A PTP body does not show up as a disk.
//! macOS uses Image Capture (`camera_mac.m`): a short session lists and downloads, then closes so
//! the body can shoot. Linux uses libgphoto2 and Windows the portable-device API (`camera_link`),
//! with the same open-then-close rhythm. Nothing is copied until the photographer picks files
//! (`camera_import`) or auto-ingest asks. Chosen files land in `<ingest>/.usb`.
use std::collections::HashSet;
use std::path::Path;
use std::sync::{Mutex, OnceLock};
#[cfg(not(target_os = "macos"))]
#[path = "camera_link.rs"]
mod link;
use serde::{Deserialize, Serialize};
use crate::ftp::{FtpState, IncomingFile};
@@ -51,7 +55,7 @@ pub struct CameraFile {
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CameraStatus {
/// False on systems without ImageCaptureCore (the button stays hidden).
/// False only when this build has no USB backend (the button stays hidden).
pub supported: bool,
pub tether: bool,
pub devices: Vec<CameraDevice>,
@@ -74,7 +78,11 @@ enum CameraEvent {
files: Vec<CameraFile>,
},
#[serde(rename = "file")]
File { path: String, name: String, size: u64 },
File {
path: String,
name: String,
size: u64,
},
}
struct Inner {
@@ -111,6 +119,47 @@ fn queue() -> &'static Mutex<Vec<String>> {
Q.get_or_init(|| Mutex::new(Vec::new()))
}
#[cfg_attr(target_os = "macos", allow(dead_code))]
pub(crate) fn enqueue_line(line: String) {
if let Ok(mut q) = queue().lock() {
q.push(line);
}
}
/// One still on the card, before it is marked new or already fetched.
pub(crate) struct ListedShot {
pub name: String,
pub size: u64,
pub created_ms: Option<i64>,
}
/// The first listing of a tether session is the baseline (nothing is "new"). Later listings mark
/// names that were not on that baseline. `fetched` is what this computer already copied.
pub(crate) fn files_on_card(
shots: &[ListedShot],
known: &HashSet<String>,
fetched: &HashSet<String>,
listing_is_live: bool,
) -> Vec<CameraFile> {
let mut files = Vec::new();
for shot in shots {
let is_new = if listing_is_live {
!known.contains(&shot.name)
} else {
false
};
let imported = fetched.contains(&shot.name);
files.push(CameraFile {
name: shot.name.clone(),
size: shot.size,
created_ms: shot.created_ms,
is_new,
imported,
});
}
files
}
impl CameraState {
fn drain(&self) {
let pending = match queue().lock() {
@@ -211,7 +260,10 @@ fn apply_event(inner: &mut Inner, line: &str) {
};
match event {
CameraEvent::Devices { devices } => inner.devices = devices,
CameraEvent::Catalog { camera_id: _, files } => {
CameraEvent::Catalog {
camera_id: _,
files,
} => {
inner.files = files;
inner.catalog_gen = inner.catalog_gen.wrapping_add(1);
}
@@ -223,16 +275,10 @@ fn apply_event(inner: &mut Inner, line: &str) {
}
}
#[cfg(target_os = "macos")]
fn supported() -> bool {
true
}
#[cfg(not(target_os = "macos"))]
fn supported() -> bool {
false
}
#[cfg(target_os = "macos")]
unsafe extern "C" fn on_camera_json(json: *const std::ffi::c_char) {
use std::ffi::CStr;
@@ -266,7 +312,9 @@ fn set_download_dir(dir: &str) {
}
#[cfg(not(target_os = "macos"))]
fn set_download_dir(_dir: &str) {}
fn set_download_dir(dir: &str) {
link::set_dir(dir);
}
#[cfg(target_os = "macos")]
fn set_tether_native(on: bool) {
@@ -274,7 +322,9 @@ fn set_tether_native(on: bool) {
}
#[cfg(not(target_os = "macos"))]
fn set_tether_native(_on: bool) {}
fn set_tether_native(on: bool) {
link::set_tether(on);
}
#[cfg(target_os = "macos")]
fn sync_native() {
@@ -282,7 +332,9 @@ fn sync_native() {
}
#[cfg(not(target_os = "macos"))]
fn sync_native() {}
fn sync_native() {
link::request_sync();
}
#[cfg(target_os = "macos")]
fn import_native(names_json: &str) {
@@ -293,7 +345,9 @@ fn import_native(names_json: &str) {
}
#[cfg(not(target_os = "macos"))]
fn import_native(_names_json: &str) {}
fn import_native(names_json: &str) {
link::import_json(names_json);
}
#[cfg(target_os = "macos")]
fn refresh_catalog_native() {
@@ -301,7 +355,9 @@ fn refresh_catalog_native() {
}
#[cfg(not(target_os = "macos"))]
fn refresh_catalog_native() {}
fn refresh_catalog_native() {
link::refresh();
}
/// Starts the browser once. Safe to call at launch; callbacks only enqueue a string.
pub fn start(ftp: &FtpState) {
@@ -313,6 +369,8 @@ pub fn start(ftp: &FtpState) {
}
unsafe { pr_camera_start(on_camera_json) }
}
#[cfg(not(target_os = "macos"))]
link::start();
let dir = ftp.ingest_dir();
let _ = std::fs::create_dir_all(dir.join(".usb"));
set_download_dir(&dir.join(".usb").to_string_lossy());
@@ -364,6 +422,33 @@ pub fn camera_refresh(cam: tauri::State<'_, CameraState>) -> CameraStatus {
mod tests {
use super::*;
#[test]
fn the_first_listing_is_not_a_new_shot_and_a_later_one_is() {
let shots = vec![
ListedShot {
name: "old.JPG".into(),
size: 10,
created_ms: Some(1),
},
ListedShot {
name: "new.JPG".into(),
size: 20,
created_ms: Some(2),
},
];
let mut known = HashSet::new();
known.insert("old.JPG".to_string());
let mut fetched = HashSet::new();
fetched.insert("old.JPG".to_string());
let first = files_on_card(&shots[..1], &known, &fetched, false);
assert!(!first[0].is_new);
assert!(first[0].imported);
let live = files_on_card(&shots, &known, &fetched, true);
assert!(!live[0].is_new);
assert!(live[1].is_new);
assert!(!live[1].imported);
}
#[test]
fn a_chosen_shot_queues_the_jpeg_and_the_raw() {
let mut inner = Inner {
@@ -424,7 +509,10 @@ mod tests {
catalog_gen: 1,
};
apply_event(&mut inner, r#"{"kind":"devices","devices":[]}"#);
apply_event(&mut inner, r#"{"kind":"catalog","cameraId":"abc","files":[]}"#);
apply_event(
&mut inner,
r#"{"kind":"catalog","cameraId":"abc","files":[]}"#,
);
assert!(inner.devices.is_empty());
assert!(inner.files.is_empty());
assert_eq!(inner.catalog_gen, 2);
+182
View File
@@ -0,0 +1,182 @@
//! Linux USB via libgphoto2. The camera is opened for this pass only and dropped before we return,
//! which closes the PTP session.
use std::path::Path;
pub struct Shot {
pub folder: String,
pub name: String,
pub size: u64,
pub created_ms: Option<i64>,
}
pub struct Report {
pub model: Option<String>,
pub id: String,
pub error: Option<String>,
pub shots: Vec<Shot>,
pub downloaded: Vec<(String, u64)>,
pub clock: Option<String>,
pub clock_unsupported: bool,
}
pub fn pulse(dir: &Path, wanted: &[String], _sync_clock: bool) -> Result<Report, String> {
let context = gphoto2::Context::new().map_err(|err| err.to_string())?;
let mut listed = context
.list_cameras()
.wait()
.map_err(|err| err.to_string())?;
let Some(desc) = listed.next() else {
return Ok(empty());
};
let camera = context
.get_camera(&desc)
.wait()
.map_err(|err| err.to_string())?;
let model = camera.abilities().model().to_string();
let roots = card_roots(&camera);
let fs = camera.fs();
let mut shots = Vec::new();
for root in roots {
walk(&fs, &root, 0, &mut shots)?;
}
let mut downloaded = Vec::new();
let mut error = None;
for shot in &shots {
let asked = wanted.iter().any(|name| name == &shot.name);
if !asked {
continue;
}
match copy_one(&fs, dir, shot) {
Ok(size) => downloaded.push((shot.name.clone(), size)),
Err(err) => error = Some(err),
}
}
// Dropping `camera` closes the session before the caller waits.
drop(fs);
drop(camera);
Ok(Report {
model: Some(model),
id: "gphoto".into(),
error,
shots,
downloaded,
clock: None,
// libgphoto2 clock widgets differ per body; the panel says the clock was not set.
clock_unsupported: true,
})
}
fn empty() -> Report {
Report {
model: None,
id: "gphoto".into(),
error: None,
shots: Vec::new(),
downloaded: Vec::new(),
clock: None,
clock_unsupported: false,
}
}
fn card_roots(camera: &gphoto2::Camera) -> Vec<String> {
let mut roots = Vec::new();
if let Ok(storages) = camera.storages().wait() {
for storage in storages {
let Some(base) = storage.base_directory() else {
continue;
};
let text = base.to_string();
if text.is_empty() {
continue;
}
if !roots.iter().any(|have| have == &text) {
roots.push(text);
}
}
}
if roots.is_empty() {
roots.push("/".to_string());
}
roots
}
fn walk(
fs: &gphoto2::filesys::CameraFS<'_>,
folder: &str,
depth: u32,
shots: &mut Vec<Shot>,
) -> Result<(), String> {
if depth > 12 {
return Ok(());
}
let files = match fs.list_files(folder).wait() {
Ok(files) => files,
Err(err) if folder != "/" => {
let _ = err;
return Ok(());
}
Err(err) => return Err(err.to_string()),
};
for name in files {
if !is_still(&name) {
continue;
}
let info = fs.file_info(folder, &name).wait().ok();
let size = info
.as_ref()
.and_then(|info| info.file().size())
.unwrap_or(0);
let created_ms = info
.as_ref()
.and_then(|info| info.file().mtime())
.map(|mtime| {
let seconds = mtime as i64;
seconds.saturating_mul(1000)
});
shots.push(Shot {
folder: folder.to_string(),
name,
size,
created_ms,
});
}
let folders = match fs.list_folders(folder).wait() {
Ok(folders) => folders,
Err(_) => return Ok(()),
};
for name in folders {
let child = child_folder(folder, &name);
walk(fs, &child, depth + 1, shots)?;
}
Ok(())
}
fn copy_one(fs: &gphoto2::filesys::CameraFS<'_>, dir: &Path, shot: &Shot) -> Result<u64, String> {
let dest = dir.join(&shot.name);
if let Ok(meta) = std::fs::metadata(&dest) {
if meta.len() > 0 {
return Ok(meta.len());
}
}
let _ = std::fs::create_dir_all(dir);
fs.download_to(&shot.folder, &shot.name, &dest)
.wait()
.map_err(|err| err.to_string())?;
let meta = std::fs::metadata(&dest).map_err(|err| err.to_string())?;
Ok(meta.len())
}
fn child_folder(parent: &str, name: &str) -> String {
if name.starts_with('/') {
return name.to_string();
}
if parent == "/" {
return format!("/{name}");
}
format!("{parent}/{name}")
}
fn is_still(name: &str) -> bool {
crate::ftp::is_jpeg_name(name) || crate::ftp::is_raw_name(name)
}
+298
View File
@@ -0,0 +1,298 @@
//! USB on Linux (libgphoto2) and Windows (portable devices). Same rhythm as the Mac: open, list,
//! download what was asked, drop the session so the shutter is free, then wait before the next open.
//! The Mac path stays in `camera_mac.m` and is not used here.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use serde::Serialize;
use super::{CameraDevice, ListedShot, enqueue_line, files_on_card};
#[cfg(all(unix, not(target_os = "macos")))]
#[path = "camera_gphoto.rs"]
mod backend;
#[cfg(target_os = "windows")]
#[path = "camera_wpd.rs"]
mod backend;
/// How long the body stays free between card reads. Matches the Mac poll.
const FREE_MS: u64 = 2500;
const STEP_MS: u64 = 200;
struct Link {
tether: AtomicBool,
sync: AtomicBool,
refresh: AtomicBool,
dir: Mutex<String>,
pending: Mutex<Vec<String>>,
/// Names on the card the first time this tether session listed it. `None` until that pass.
known: Mutex<Option<HashSet<String>>>,
fetched: Mutex<HashSet<String>>,
}
fn link() -> &'static Link {
static LINK: OnceLock<Link> = OnceLock::new();
LINK.get_or_init(|| Link {
tether: AtomicBool::new(false),
sync: AtomicBool::new(false),
refresh: AtomicBool::new(false),
dir: Mutex::new(String::new()),
pending: Mutex::new(Vec::new()),
known: Mutex::new(None),
fetched: Mutex::new(HashSet::new()),
})
}
pub fn start() {
static STARTED: AtomicBool = AtomicBool::new(false);
if STARTED.swap(true, Ordering::SeqCst) {
return;
}
std::thread::Builder::new()
.name("photoreport-usb".into())
.spawn(|| {
#[cfg(target_os = "windows")]
backend::init_thread();
loop {
if !link().tether.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(STEP_MS));
continue;
}
pulse_once();
let mut waited = 0u64;
while waited < FREE_MS && link().tether.load(Ordering::SeqCst) {
if link().refresh.swap(false, Ordering::SeqCst) {
break;
}
let waiting = link()
.pending
.lock()
.map(|p| !p.is_empty())
.unwrap_or(false);
if waiting {
break;
}
std::thread::sleep(Duration::from_millis(STEP_MS));
waited += STEP_MS;
}
}
})
.ok();
}
pub fn set_dir(dir: &str) {
if let Ok(mut slot) = link().dir.lock() {
*slot = dir.to_string();
}
load_fetched(Path::new(dir));
}
pub fn set_tether(on: bool) {
link().tether.store(on, Ordering::SeqCst);
if !on {
if let Ok(mut known) = link().known.lock() {
*known = None;
}
publish_idle();
return;
}
link().refresh.store(true, Ordering::SeqCst);
}
pub fn request_sync() {
link().sync.store(true, Ordering::SeqCst);
link().refresh.store(true, Ordering::SeqCst);
}
pub fn refresh() {
link().refresh.store(true, Ordering::SeqCst);
}
pub fn import_json(names_json: &str) {
let Ok(names) = serde_json::from_str::<Vec<String>>(names_json) else {
return;
};
if let Ok(mut pending) = link().pending.lock() {
for name in names {
if !pending.iter().any(|have| have == &name) {
pending.push(name);
}
}
}
link().refresh.store(true, Ordering::SeqCst);
}
fn pulse_once() {
let dir = link().dir.lock().map(|d| d.clone()).unwrap_or_default();
if dir.is_empty() {
return;
}
let wanted = link().pending.lock().map(|p| p.clone()).unwrap_or_default();
let sync = link().sync.swap(false, Ordering::SeqCst);
let report = backend::pulse(Path::new(&dir), &wanted, sync);
match report {
Ok(report) => apply_report(&dir, report),
Err(err) => publish_busy(&err),
}
}
fn apply_report(dir: &str, report: backend::Report) {
let Some(model) = report.model else {
publish_devices(Vec::new());
publish_files("usb", Vec::new());
return;
};
let shots: Vec<ListedShot> = report
.shots
.iter()
.map(|shot| ListedShot {
name: shot.name.clone(),
size: shot.size,
created_ms: shot.created_ms,
})
.collect();
let listing_is_live = {
let Ok(mut known) = link().known.lock() else {
return;
};
if known.is_none() {
let mut names = HashSet::new();
for shot in &shots {
names.insert(shot.name.clone());
}
*known = Some(names);
false
} else {
true
}
};
let known = link()
.known
.lock()
.ok()
.and_then(|k| k.clone())
.unwrap_or_default();
let fetched = link().fetched.lock().map(|f| f.clone()).unwrap_or_default();
let files = files_on_card(&shots, &known, &fetched, listing_is_live);
let mut clock = report.clock;
if clock.is_none() && report.clock_unsupported {
clock = Some("unsupported".to_string());
}
let id = report.id.clone();
publish_devices(vec![CameraDevice {
id: id.clone(),
name: model,
vendor_id: 0,
product_id: 0,
state: "tethered".to_string(),
error: report.error,
clock,
clock_offset: None,
catalog_ready: true,
}]);
publish_files(&id, files);
remember_downloaded(dir, &report.downloaded);
}
fn remember_downloaded(dir: &str, downloaded: &[(String, u64)]) {
if downloaded.is_empty() {
return;
}
let Ok(mut fetched) = link().fetched.lock() else {
return;
};
let Ok(mut pending) = link().pending.lock() else {
return;
};
for (name, size) in downloaded {
if *size == 0 {
continue;
}
fetched.insert(name.clone());
pending.retain(|want| want != name);
let path = PathBuf::from(dir).join(name);
let line = serde_json::json!({
"kind": "file",
"path": path,
"name": name,
"size": size,
});
enqueue_line(line.to_string());
}
write_fetched(Path::new(dir), &fetched);
}
fn publish_idle() {
publish_devices(Vec::new());
publish_files("usb", Vec::new());
}
fn publish_busy(err: &str) {
publish_devices(vec![CameraDevice {
id: "usb".into(),
name: "USB".into(),
vendor_id: 0,
product_id: 0,
state: "busy".into(),
error: Some(err.to_string()),
clock: None,
clock_offset: None,
catalog_ready: false,
}]);
}
fn publish_devices(devices: Vec<CameraDevice>) {
let line = serde_json::json!({ "kind": "devices", "devices": devices });
enqueue_line(line.to_string());
}
fn publish_files(camera_id: &str, files: Vec<super::CameraFile>) {
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Catalog<'a> {
kind: &'static str,
camera_id: &'a str,
files: &'a [super::CameraFile],
}
let line = serde_json::to_string(&Catalog {
kind: "catalog",
camera_id,
files: &files,
});
if let Ok(line) = line {
enqueue_line(line);
}
}
fn fetched_path(dir: &Path) -> PathBuf {
dir.join(".fetched")
}
fn load_fetched(dir: &Path) {
let text = std::fs::read_to_string(fetched_path(dir)).unwrap_or_default();
let Ok(mut fetched) = link().fetched.lock() else {
return;
};
fetched.clear();
for line in text.lines() {
if !line.is_empty() {
fetched.insert(line.to_string());
}
}
}
fn write_fetched(dir: &Path, fetched: &HashSet<String>) {
let mut names: Vec<&String> = fetched.iter().collect();
names.sort();
let mut text = String::new();
for name in names {
text.push_str(name);
text.push('\n');
}
let _ = std::fs::write(fetched_path(dir), text);
}
+325
View File
@@ -0,0 +1,325 @@
//! Windows USB via the portable-device API (the PTP driver Windows already owns). The device is
//! opened for this pass and released before we return, so the body is not left on the computer screen.
// The whole module is COM. Edition 2024 does not treat an `unsafe fn` body as an unsafe block.
#![allow(unsafe_op_in_unsafe_fn)]
use std::path::Path;
use windows::{
Win32::{
Devices::PortableDevices::{
IEnumPortableDeviceObjectIDs, IPortableDevice, IPortableDeviceContent,
IPortableDeviceKeyCollection, IPortableDeviceManager, IPortableDeviceValues,
PortableDevice, PortableDeviceKeyCollection, PortableDeviceManager,
PortableDeviceValues, WPD_CLIENT_MAJOR_VERSION, WPD_CLIENT_MINOR_VERSION,
WPD_CLIENT_NAME, WPD_CLIENT_REVISION, WPD_DEVICE_OBJECT_ID, WPD_OBJECT_DATE_CREATED,
WPD_OBJECT_ORIGINAL_FILE_NAME, WPD_OBJECT_SIZE, WPD_RESOURCE_DEFAULT,
},
System::Com::{
CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx,
CoTaskMemFree, IStream, STGM_READ,
StructuredStorage::{PROPVARIANT, PropVariantClear},
},
System::Variant::VT_FILETIME,
},
core::{PCWSTR, PWSTR, w},
};
pub struct Shot {
pub name: String,
pub size: u64,
pub created_ms: Option<i64>,
object_id: String,
}
pub struct Report {
pub model: Option<String>,
pub id: String,
pub error: Option<String>,
pub shots: Vec<Shot>,
pub downloaded: Vec<(String, u64)>,
pub clock: Option<String>,
pub clock_unsupported: bool,
}
pub fn init_thread() {
unsafe {
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
}
}
pub fn pulse(dir: &Path, wanted: &[String], _sync_clock: bool) -> Result<Report, String> {
unsafe { read_card(dir, wanted) }
}
unsafe fn read_card(dir: &Path, wanted: &[String]) -> Result<Report, String> {
let manager: IPortableDeviceManager =
CoCreateInstance(&PortableDeviceManager, None, CLSCTX_INPROC_SERVER)
.map_err(|err| err.to_string())?;
let mut count = 0u32;
manager
.GetDevices(std::ptr::null_mut(), &mut count)
.map_err(|err| err.to_string())?;
if count == 0 {
return Ok(empty());
}
let mut ids = vec![PWSTR::null(); count as usize];
manager
.GetDevices(ids.as_mut_ptr(), &mut count)
.map_err(|err| err.to_string())?;
let device_id = ids.first().copied().unwrap_or(PWSTR::null());
let id_text = if device_id.is_null() {
String::new()
} else {
device_id.to_string().unwrap_or_default()
};
for id in &ids {
if !id.is_null() && id.0 != device_id.0 {
CoTaskMemFree(Some(id.0 as *const _));
}
}
if id_text.is_empty() {
return Ok(empty());
}
let device: IPortableDevice = CoCreateInstance(&PortableDevice, None, CLSCTX_INPROC_SERVER)
.map_err(|err| err.to_string())?;
let client: IPortableDeviceValues =
CoCreateInstance(&PortableDeviceValues, None, CLSCTX_INPROC_SERVER)
.map_err(|err| err.to_string())?;
client
.SetStringValue(&WPD_CLIENT_NAME, w!("PhotoReport"))
.map_err(|err| err.to_string())?;
client
.SetUnsignedIntegerValue(&WPD_CLIENT_MAJOR_VERSION, 1)
.map_err(|err| err.to_string())?;
client
.SetUnsignedIntegerValue(&WPD_CLIENT_MINOR_VERSION, 0)
.map_err(|err| err.to_string())?;
client
.SetUnsignedIntegerValue(&WPD_CLIENT_REVISION, 0)
.map_err(|err| err.to_string())?;
let wide_id = wide(&id_text);
let device_name = friendly_name(&manager, PCWSTR(wide_id.as_ptr()));
device
.Open(PCWSTR(wide_id.as_ptr()), &client)
.map_err(|err| err.to_string())?;
let content = device.Content().map_err(|err| err.to_string())?;
let mut shots = Vec::new();
collect(&content, WPD_DEVICE_OBJECT_ID, 0, &mut shots).map_err(|err| err.to_string())?;
let mut downloaded = Vec::new();
let mut error = None;
for shot in &shots {
let asked = wanted.iter().any(|name| name == &shot.name);
if !asked {
continue;
}
match copy_one(&content, dir, shot) {
Ok(size) => downloaded.push((shot.name.clone(), size)),
Err(err) => error = Some(err),
}
}
if !device_id.is_null() {
CoTaskMemFree(Some(device_id.0 as *const _));
}
// `device` drops here, which closes the PTP session.
Ok(Report {
model: Some(device_name),
id: "wpd".into(),
error,
shots,
downloaded,
clock: None,
clock_unsupported: true,
})
}
fn empty() -> Report {
Report {
model: None,
id: "wpd".into(),
error: None,
shots: Vec::new(),
downloaded: Vec::new(),
clock: None,
clock_unsupported: false,
}
}
unsafe fn friendly_name(manager: &IPortableDeviceManager, id: PCWSTR) -> String {
let mut chars = 0u32;
if manager
.GetDeviceFriendlyName(id, PWSTR::null(), &mut chars)
.is_err()
|| chars <= 1
{
return "USB camera".to_string();
}
let mut buf = vec![0u16; chars as usize];
if manager
.GetDeviceFriendlyName(id, PWSTR(buf.as_mut_ptr()), &mut chars)
.is_err()
{
return "USB camera".to_string();
}
let end = (chars as usize).saturating_sub(1).min(buf.len());
let name = String::from_utf16_lossy(&buf[..end]);
if name.is_empty() {
return "USB camera".to_string();
}
name
}
unsafe fn collect(
content: &IPortableDeviceContent,
parent: PCWSTR,
depth: u32,
shots: &mut Vec<Shot>,
) -> windows::core::Result<()> {
if depth > 12 {
return Ok(());
}
let enumerator: IEnumPortableDeviceObjectIDs = content.EnumObjects(0, parent, None)?;
loop {
let mut batch = [PWSTR::null(); 32];
let mut fetched = 0u32;
let hr = enumerator.Next(&mut batch, &mut fetched);
if hr.is_err() || fetched == 0 {
break;
}
for id in batch.iter().take(fetched as usize) {
if id.is_null() {
continue;
}
let object_id = id.to_string().unwrap_or_default();
CoTaskMemFree(Some(id.0 as *const _));
if object_id.is_empty() {
continue;
}
if let Some(shot) = shot_of(content, &object_id)? {
shots.push(shot);
}
let child = wide(&object_id);
collect(content, PCWSTR(child.as_ptr()), depth + 1, shots)?;
}
}
Ok(())
}
unsafe fn shot_of(
content: &IPortableDeviceContent,
object_id: &str,
) -> windows::core::Result<Option<Shot>> {
let keys: IPortableDeviceKeyCollection =
CoCreateInstance(&PortableDeviceKeyCollection, None, CLSCTX_INPROC_SERVER)?;
keys.Add(&WPD_OBJECT_ORIGINAL_FILE_NAME)?;
keys.Add(&WPD_OBJECT_SIZE)?;
keys.Add(&WPD_OBJECT_DATE_CREATED)?;
let properties = content.Properties()?;
let object_wide = wide(object_id);
let values = properties.GetValues(PCWSTR(object_wide.as_ptr()), &keys)?;
let name_ptr = values
.GetStringValue(&WPD_OBJECT_ORIGINAL_FILE_NAME)
.unwrap_or(PWSTR::null());
if name_ptr.is_null() {
return Ok(None);
}
let name = name_ptr.to_string().unwrap_or_default();
CoTaskMemFree(Some(name_ptr.0 as *const _));
if !is_still(&name) {
return Ok(None);
}
let size = values
.GetUnsignedLargeIntegerValue(&WPD_OBJECT_SIZE)
.unwrap_or(0);
let created_ms = filetime_ms(&values);
Ok(Some(Shot {
name,
size,
created_ms,
object_id: object_id.to_string(),
}))
}
unsafe fn filetime_ms(values: &IPortableDeviceValues) -> Option<i64> {
let mut variant = values.GetValue(&WPD_OBJECT_DATE_CREATED).ok()?;
let ms = filetime_of(&variant);
let _ = PropVariantClear(&mut variant);
ms
}
/// 100-nanosecond ticks since 1601-01-01, which is how a portable device stores a capture time.
unsafe fn filetime_of(variant: &PROPVARIANT) -> Option<i64> {
let header = &variant.Anonymous.Anonymous;
if header.vt != VT_FILETIME {
return None;
}
let filetime = header.Anonymous.filetime;
let ticks = (u64::from(filetime.dwHighDateTime) << 32) | u64::from(filetime.dwLowDateTime);
const EPOCH_DIFF: u64 = 116_444_736_000_000_000;
if ticks < EPOCH_DIFF {
return None;
}
let unix_100ns = ticks - EPOCH_DIFF;
Some((unix_100ns / 10_000) as i64)
}
unsafe fn copy_one(
content: &IPortableDeviceContent,
dir: &Path,
shot: &Shot,
) -> Result<u64, String> {
let dest = dir.join(&shot.name);
if let Ok(meta) = std::fs::metadata(&dest) {
if meta.len() > 0 {
return Ok(meta.len());
}
}
std::fs::create_dir_all(dir).map_err(|err| err.to_string())?;
let resources = content.Transfer().map_err(|err| err.to_string())?;
let object_wide = wide(&shot.object_id);
let mut stream: Option<IStream> = None;
let mut optimal = 0u32;
resources
.GetStream(
PCWSTR(object_wide.as_ptr()),
&WPD_RESOURCE_DEFAULT,
STGM_READ.0 as u32,
&mut optimal,
&mut stream,
)
.map_err(|err| err.to_string())?;
let stream = stream.ok_or("no_stream")?;
let mut file = std::fs::File::create(&dest).map_err(|err| err.to_string())?;
let mut buffer = vec![0u8; 1024 * 256];
loop {
let mut read = 0u32;
let hr = stream.Read(
buffer.as_mut_ptr() as *mut _,
buffer.len() as u32,
Some(&mut read),
);
if hr.is_err() {
let _ = std::fs::remove_file(&dest);
return Err(hr.to_string());
}
if read == 0 {
break;
}
use std::io::Write;
file.write_all(&buffer[..read as usize])
.map_err(|err| err.to_string())?;
}
let meta = std::fs::metadata(&dest).map_err(|err| err.to_string())?;
Ok(meta.len())
}
fn is_still(name: &str) -> bool {
crate::ftp::is_jpeg_name(name) || crate::ftp::is_raw_name(name)
}
fn wide(text: &str) -> Vec<u16> {
text.encode_utf16().chain(std::iter::once(0)).collect()
}
+4 -1
View File
@@ -932,7 +932,10 @@ mod tests {
let (take, held) = days_that_fit(days, Some(55));
assert_eq!(take.len(), 1);
assert_eq!(take[0].key, "2026-11-03");
assert_eq!(held, vec!["2026-11-04".to_string(), "2026-11-05".to_string()]);
assert_eq!(
held,
vec!["2026-11-04".to_string(), "2026-11-05".to_string()]
);
let (all, none) = days_that_fit(
vec![DayPlan {
key: "2026-11-04".into(),
+1 -5
View File
@@ -126,11 +126,7 @@ impl Deliveries {
Path::new(f)
.canonicalize()
.ok()
.and_then(|root| {
canon
.parent()
.map(|p| p.starts_with(&root))
})
.and_then(|root| canon.parent().map(|p| p.starts_with(&root)))
.unwrap_or(false)
});
if !allowed && !allowed_xmp {
+70 -8
View File
@@ -266,6 +266,7 @@ fn jpeg_paths(dir: &Path, out: &mut Vec<PathBuf>) {
}
}
#[cfg(not(target_os = "windows"))]
fn memory_gb() -> f64 {
let pages = unsafe { libc::sysconf(libc::_SC_PHYS_PAGES) };
let size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
@@ -275,6 +276,34 @@ fn memory_gb() -> f64 {
(pages as f64) * (size as f64) / 1e9
}
#[cfg(target_os = "windows")]
fn memory_gb() -> f64 {
#[repr(C)]
struct MemoryStatus {
length: u32,
memory_load: u32,
total_phys: u64,
avail_phys: u64,
total_page: u64,
avail_page: u64,
total_virtual: u64,
avail_virtual: u64,
avail_extended_virtual: u64,
}
#[link(name = "kernel32")]
unsafe extern "system" {
fn GlobalMemoryStatusEx(status: *mut MemoryStatus) -> i32;
}
unsafe {
let mut status = std::mem::zeroed::<MemoryStatus>();
status.length = std::mem::size_of::<MemoryStatus>() as u32;
if GlobalMemoryStatusEx(&mut status) == 0 || status.total_phys == 0 {
return 8.0;
}
status.total_phys as f64 / 1e9
}
}
/// One engine per core, and only as many as memory can hold (each copy of the model is large).
/// `extra_gb` is RAM already taken by the accelerator, so the CPU copies leave room for it.
fn engine_cap(extra_gb: f64) -> usize {
@@ -334,21 +363,47 @@ fn cpu_ticks() -> Option<(u64, u64)> {
}
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
/// `GetSystemTimes`: kernel time already includes idle, so the total is kernel plus user.
#[cfg(target_os = "windows")]
fn cpu_ticks() -> Option<(u64, u64)> {
#[link(name = "kernel32")]
unsafe extern "system" {
fn GetSystemTimes(idle: *mut u64, kernel: *mut u64, user: *mut u64) -> i32;
}
unsafe {
let mut idle = 0u64;
let mut kernel = 0u64;
let mut user = 0u64;
if GetSystemTimes(&mut idle, &mut kernel, &mut user) == 0 {
return None;
}
let total = kernel.saturating_add(user);
if total == 0 {
return None;
}
Some((idle, total))
}
}
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
fn cpu_ticks() -> Option<(u64, u64)> {
None
}
/// Share of the CPU that was busy between two samples. `idle` is included in `total`.
fn cpu_fraction(idle_delta: u64, total_delta: u64) -> Option<f64> {
if total_delta == 0 {
return None;
}
Some(1.0 - (idle_delta as f64) / (total_delta as f64))
}
fn cpu_used(prev: &mut Option<(u64, u64)>) -> Option<f64> {
let now = cpu_ticks()?;
let used = prev.and_then(|(idle, total)| {
let idle_d = now.0.saturating_sub(idle);
let total_d = now.1.saturating_sub(total);
if total_d == 0 {
None
} else {
Some(1.0 - (idle_d as f64) / (total_d as f64))
}
let idle_delta = now.0.saturating_sub(idle);
let total_delta = now.1.saturating_sub(total);
cpu_fraction(idle_delta, total_delta)
});
*prev = Some(now);
used
@@ -747,6 +802,13 @@ pub fn faces_read(path: String) -> Result<tauri::ipc::Response, String> {
mod tests {
use super::*;
#[test]
fn cpu_fraction_counts_idle_inside_the_total() {
let busy = cpu_fraction(25, 100);
assert_eq!(busy, Some(0.75));
assert_eq!(cpu_fraction(0, 0), None);
}
#[test]
fn base64_round_trip_of_a_short_buffer() {
let raw = b"faces";
+11 -2
View File
@@ -1598,9 +1598,18 @@ pub fn ftp_sent(
event: String,
date: String,
) -> Result<String, String> {
// Canonical path while the file is still in ingest: that is the string `ftp_info` stored.
let source = std::fs::canonicalize(&path)
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|_| path.clone());
let target = state.sent(&path, &event, &date)?;
if let Ok(sha) = crate::local::sha256_file(Path::new(&target)) {
index.record(&sha, Path::new(&target));
let filed = PathBuf::from(&target);
index.retarget(&source, &filed);
if source != path {
index.retarget(&path, &filed);
}
if let Ok(sha) = crate::local::sha256_file(&filed) {
index.record(&sha, &filed);
}
Ok(target)
}
+1
View File
@@ -102,6 +102,7 @@ pub fn run() {
// `tauri dev` serves the dev server: nothing to update.
if !cfg!(debug_assertions) {
ui::watch(app.handle().clone());
updater::watch(app.handle().clone());
}
// Always the interface on this computer (`tauri dev`: the dev server). No download to start, and it
// works without a network; new versions arrive in the background (see `ui`).
+112 -3
View File
@@ -95,9 +95,68 @@ impl LocalIndex {
impl LocalIndex {
/// The file recorded for this hash, even if it changed since it arrived (another app, Photo Mechanic, wrote
/// captions into it): the same photo, with other metadata. Never handed out as the fingerprinted original.
///
/// Filing moves the photo out of the ingest folder and a later rewrite changes its hash, so the arrival
/// hash can still point at a path that is gone. The copy filed under the same name is that photo.
pub fn find_changed(&self, sha256: &str) -> Option<PathBuf> {
let path = PathBuf::from(self.with(|m| m.get(sha256).cloned())?);
path.is_file().then_some(path)
let recorded = PathBuf::from(self.with(|m| m.get(sha256).cloned())?);
if recorded.is_file() {
return Some(recorded);
}
let name = recorded.file_name()?.to_owned();
let mut found = self.with(|m| {
let mut hits = Vec::new();
for (other, path) in m.iter() {
if other == sha256 {
continue;
}
let candidate = Path::new(path);
if candidate.file_name() != Some(name.as_os_str()) {
continue;
}
if !candidate.is_file() {
continue;
}
hits.push(PathBuf::from(path));
}
hits
});
// Two different shoots can reuse a camera name. One remaining file is the one that was filed.
if found.len() != 1 {
return None;
}
let path = found.pop()?;
self.record(sha256, &path);
Some(path)
}
/// The arrival hash keeps pointing at the file after it leaves the ingest folder. The bytes at the
/// destination may already differ (captions written in), so recording only the new hash would lose it.
pub fn retarget(&self, from: &str, to: &Path) {
let to_owned = to.to_string_lossy().into_owned();
if from == to_owned {
return;
}
let file = self.file();
let snapshot = self.with(|m| {
let mut changed = false;
for path in m.values_mut() {
if path == from {
*path = to_owned.clone();
changed = true;
}
}
if !changed {
return None;
}
serde_json::to_vec(m).ok()
});
if let Some(bytes) = snapshot {
if let Some(dir) = file.parent() {
let _ = std::fs::create_dir_all(dir);
}
let _ = std::fs::write(file, bytes);
}
}
}
@@ -187,7 +246,9 @@ pub async fn local_stat(
sha256: String,
) -> Result<LocalStat, String> {
let path = index.find_changed(&sha256).ok_or("not_found")?;
let meta = tokio::fs::metadata(&path).await.map_err(|e| e.to_string())?;
let meta = tokio::fs::metadata(&path)
.await
.map_err(|e| e.to_string())?;
let mut size = meta.len();
let mut mtime_ms = meta
.modified()
@@ -350,6 +411,54 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn finds_the_filed_copy_when_the_ingest_path_is_gone() {
let dir = std::env::temp_dir().join(format!("pr-local-filed-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let ingest = dir.join("ingest");
let work = dir.join("work");
std::fs::create_dir_all(&ingest).unwrap();
std::fs::create_dir_all(&work).unwrap();
let arrived = ingest.join("PSR14526.JPG");
std::fs::write(&arrived, b"camera jpeg").unwrap();
let arrival = sha256_file(&arrived).unwrap();
let filed = work.join("PSR14526.JPG");
std::fs::write(&filed, b"camera jpeg plus captions").unwrap();
let rewritten = sha256_file(&filed).unwrap();
let index = LocalIndex {
file: Some(dir.join("index.json")),
..Default::default()
};
index.record(&arrival, &arrived);
index.record(&rewritten, &filed);
std::fs::remove_file(&arrived).unwrap();
assert_eq!(index.find_changed(&arrival), Some(filed.clone()));
assert_eq!(index.find(&arrival), None);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn retarget_keeps_the_arrival_hash_on_the_filed_path() {
let dir = std::env::temp_dir().join(format!("pr-local-retarget-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let arrived = dir.join("from.JPG");
let filed = dir.join("to.JPG");
std::fs::write(&arrived, b"same").unwrap();
std::fs::write(&filed, b"same").unwrap();
let sha = sha256_file(&arrived).unwrap();
let index = LocalIndex {
file: Some(dir.join("index.json")),
..Default::default()
};
index.record(&sha, &arrived);
index.retarget(arrived.to_str().unwrap(), &filed);
assert_eq!(index.find_changed(&sha), Some(filed));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_filed_jpeg_becomes_a_filmstrip_thumbnail() {
let dir = std::env::temp_dir().join(format!("pr-film-{}", std::process::id()));
+53 -3
View File
@@ -4,8 +4,10 @@
//!
//! The app asks the API (`/v1/desktop/update/{target}/{arch}/{version}`), which reads the latest `desktop-v*`
//! release. Installers are signed at build time with the release key; the matching public key is compiled in
//! (`PHOTOREPORT_UPDATER_PUBKEY`). A build without it (a developer's) never updates itself: there is nothing to
//! check a download against.
//! (`PHOTOREPORT_UPDATER_PUBKEY`, from the environment or `updater-pubkey.txt` on a release build). A debug build
//! without that variable never updates itself: there is nothing to check a download against.
use std::sync::atomic::{AtomicBool, Ordering};
use serde::Serialize;
use tauri_plugin_updater::UpdaterExt;
@@ -61,9 +63,22 @@ pub async fn update_check(app: tauri::AppHandle) -> Result<Option<UpdateInfo>, S
}
/// Downloads the new shell, checks its signature, installs it and restarts the app.
/// The page and the background check both call this; only one download runs.
#[tauri::command]
pub async fn update_install(app: tauri::AppHandle) -> Result<(), String> {
let update = updater(&app)?
let started = INSTALLING.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst);
if started.is_err() {
return Ok(());
}
let result = install_now(&app).await;
if result.is_err() {
INSTALLING.store(false, Ordering::SeqCst);
}
result
}
async fn install_now(app: &tauri::AppHandle) -> Result<(), String> {
let update = updater(app)?
.check()
.await
.map_err(|e| e.to_string())?
@@ -75,6 +90,33 @@ pub async fn update_install(app: tauri::AppHandle) -> Result<(), String> {
app.restart();
}
static INSTALLING: AtomicBool = AtomicBool::new(false);
const FIRST: std::time::Duration = std::time::Duration::from_secs(3);
const EVERY: std::time::Duration = std::time::Duration::from_secs(60);
/// Checks for a newer shell while the app runs and installs it. The window does not have to ask.
pub fn watch(app: tauri::AppHandle) {
if PUBKEY.is_none() {
return;
}
tauri::async_runtime::spawn(async move {
tokio::time::sleep(FIRST).await;
loop {
match update_check(app.clone()).await {
Ok(Some(_)) => {
if let Err(err) = update_install(app.clone()).await {
eprintln!("shell update: {err}");
}
}
Ok(None) => {}
Err(err) => eprintln!("shell update: {err}"),
}
tokio::time::sleep(EVERY).await;
}
});
}
#[cfg(test)]
mod tests {
use super::*;
@@ -88,4 +130,12 @@ mod tests {
);
assert!(url.starts_with("http"));
}
#[test]
fn release_builds_ship_the_update_key() {
let key = include_str!("../updater-pubkey.txt").trim();
assert!(key.starts_with("dW50cnVzdGVk"));
assert!(key.len() > 80);
assert!(!key.chars().any(|c| c.is_whitespace()));
}
}
@@ -0,0 +1 @@
dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEExODYxQ0JERTgzQzIwMTkKUldRWklEem92UnlHb2RUc0RRN2plalV0bndQVTVySFJQOGtuM3pQNDFtaDZFSld6ZnZya1FCeFEK
+3 -1
View File
@@ -39,7 +39,9 @@ export default async function OrderPage({ params, searchParams }: { params: Prom
</header>
{order.status === "PENDING" && (
<p className="notice" style={{ marginTop: 24 }}>
Assim que o pagamento for confirmado (por Multibanco pode demorar algumas horas) as fotos aparecem aqui e enviamos-te um email.
{order.checkoutUrl
? "Assim que o pagamento for confirmado (por Multibanco pode demorar algumas horas) as fotos aparecem aqui e enviamos-te um email."
: "A encomenda ficou registada. O pagamento combina-se à parte; quando estiver confirmado, as fotos aparecem aqui e enviamos-te um email."}
{order.checkoutUrl && (
<>
{" "}
+8 -3
View File
@@ -474,9 +474,14 @@ The same queue also delivers to SFTP, FTP/FTPS and Dropbox (`delivery/transports
- **ZeroZero** (`fotos.zerozero.pt`, `delivery/zerozero.ts`): the photographer's zerozero.pt account. The server
signs in through zerozero.pt's OAuth (`/api/auth/login` → `oauth.php` → `ax_login.php` → `/api/auth/callback`,
cookies kept in a small jar), and uploads with tus to `/api/upload?match_id=<game>` with the file name and the
author (`artist`: the photographer's name from the IPTC creator). The "folder" is the game: chosen for the
event by pasting the game's link (kept in `events.zerozero_game_id`), or found among the desk's upcoming games
by both teams and kick-off within 3 hours. The delivered item's remote path is `<game>/<image id>`
author (`artist`: the photographer's name from the IPTC creator). The upload only reaches the photographer's
desk. The public game shows the photo after publish: `POST /api/photo-sync/<image id>`, or
`POST /api/photo-sync/match/<game>` when the desk has no single-image publish (the same call as
"Sincronizar com zerozero"). A 403 signs in again once (a stale session uses that status, not 401). The same
refusal after the new login still counts as delivered: the file is on the desk. Any other publish failure fails
the delivery. The "folder" is the game:
chosen for the event by pasting the game's link (kept in `events.zerozero_game_id`), or found among the desk's
upcoming games by both teams and kick-off within 3 hours. The delivered item's remote path is `<game>/<image id>`
(`DELETE /api/images/<id>` takes it back).
Each target also has Photo Mechanic's uploader output options: fit-in-box size, JPEG quality, output
+13 -3
View File
@@ -131,9 +131,19 @@ downloads only the files that changed, checks each hash and uses the new version
photographer reloads). The installer's own copy is the fallback, and wins when it is newer.
macOS builds on a Mac registered once as a runner (`bash infra/desktop/macos-runner.sh`, with a registration token
from Gitea → Actions → Runners; label `macos`, a launchd service of that user). Its builds carry the updater key, so
apps installed from a release update themselves; an app compiled by hand without the key never does. A release made
while the Mac is off waits for it.
from Gitea → Actions → Runners; label `macos`, a launchd service of that user). Release builds carry the updater
public key (`updater-pubkey.txt`, or `TAURI_UPDATER_PUBKEY` when CI sets it), so an installed app replaces itself
from the next signed `desktop-v*` release. A debug build without the variable never does. A release made while the
Mac is off waits for it.
Windows `.msi` builds on a runner labelled `windows` (Git bash, and the WebView2 step in the workflow). None is
registered yet, so a `desktop-v*` tag waits for that job until one is online. Linux installs `libgphoto2-dev`
for the USB camera.
Notarisation uses a Developer ID in `APPLE_SIGNING_IDENTITY` plus either `APPLE_ID`, `APPLE_PASSWORD` and
`APPLE_TEAM_ID`, or `APPLE_API_ISSUER`, `APPLE_API_KEY` and `APPLE_API_KEY_PATH`. Those secrets are not on this
Gitea yet, so Mac builds stay signed without notarisation. When the identity is set, the hardened runtime is on
and `apps/desktop/src-tauri/entitlements.plist` lets the bundled ONNX library load.
## Importing the old app.photoreport.pt
+4
View File
@@ -84,6 +84,10 @@ CFG
export APPLE_SIGNING_IDENTITY="$local_id"
# Not a Developer ID: no notarisation, so no hardened runtime (it would refuse the bundled ONNX library).
extra+=(--config '{"bundle":{"macOS":{"hardenedRuntime":false}}}')
else
# Developer ID. Notarisation (when APPLE_ID / APPLE_PASSWORD / APPLE_TEAM_ID, or the API key, are set)
# requires the hardened runtime. The entitlements let the bundled ONNX library load.
extra+=(--config '{"bundle":{"macOS":{"hardenedRuntime":true,"entitlements":"entitlements.plist"}}}')
fi
echo "Signing as: $APPLE_SIGNING_IDENTITY"
+10
View File
@@ -0,0 +1,10 @@
# WebView2 is the window engine of the Windows installer. Windows 11 already has it.
# A desktop-v tag on a Windows runner installs the evergreen runtime when this key is missing.
$ErrorActionPreference = "Stop"
$key = "HKLM:\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"
if (Test-Path $key) {
exit 0
}
$dest = Join-Path $env:TEMP "webview2-bootstrapper.exe"
Invoke-WebRequest -Uri "https://go.microsoft.com/fwlink/p/?LinkId=2124703" -OutFile $dest
Start-Process $dest -ArgumentList "/silent", "/install" -Wait
+5
View File
@@ -591,6 +591,11 @@ export class ApiClient {
return this.request<OrderView>("POST", `/v1/orders/${orderId}/items/${itemId}/shipped`);
}
/** Payment taken outside the shop. The caller is responsible for delivering the work. */
recordPayment(orderId: string) {
return this.request<OrderView>("POST", `/v1/orders/${orderId}/payment-received`);
}
retryOrder(orderId: string) {
return this.request<OrderView>("POST", `/v1/orders/${orderId}/retry`);
}