Compare commits

..
Author SHA1 Message Date
spark a1a8c74a70 fix(usb): auto-ingest only shots inside the event ingest window
ci / rust (pull_request) Successful in 7m43s
ci / typescript (pull_request) Successful in 10m57s
A full-card pull (other days included) must never happen automatically.
Auto-ingest is opt-in and limited to new JPEGs whose camera time falls
between the event's ingestFrom and ingestUntil; the rest stay manual.
2026-11-03 11:49:10 +00:00
spark ef35c2e569 Desktop 0.3.26: USB card list with chosen downloads only (#141)
ci / rust (push) Successful in 7m57s
ci / typescript (push) Successful in 10m32s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 24m0s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 28m9s
Desktop 0.3.26: USB card list with chosen downloads only
2026-11-03 11:46:20 +00:00
spark 107e4be5e3 Desktop 0.3.26: USB card list with chosen downloads only
ci / rust (pull_request) Successful in 3m54s
ci / typescript (pull_request) Successful in 7m54s
Stop auto-pulling tethered shots. List the card (and new frames as they
appear) and download only what the photographer selects, including RAW
sidecars. Open the PTP session after deviceDidBecomeReady so Canon bodies
do not hang on “A ligar…”.
2026-11-03 11:33:51 +00:00
spark d9ca281706 Merge pull request 'fix(delivery): sweep rejected photos left on destinations' (#137) from task/BIT-retract-orphan-reconcile into main
ci / rust (push) Successful in 3m53s
ci / typescript (push) Successful in 8m7s
2026-11-03 00:32:55 +00:00
spark 0afa84c211 Merge branch 'main' into task/BIT-retract-orphan-reconcile
ci / rust (pull_request) Successful in 3m55s
ci / typescript (pull_request) Successful in 7m38s
2026-11-03 00:16:33 +00:00
spark 0ef50c98cd Merge pull request 'fix(desktop): reject update manifests whose signature version disagrees' (#139) from task/BIT-desktop-update-sig-guard into main
ci / rust (push) Successful in 3m59s
ci / typescript (push) Successful in 7m25s
2026-11-02 23:02:35 +00:00
spark 985188812a fix(desktop): reject update manifests whose signature version disagrees
ci / rust (pull_request) Successful in 4m4s
ci / typescript (pull_request) Successful in 8m25s
A retagged desktop-v* on the wrong commit announced 0.3.25 while the
binary was still signed as 0.3.24. Prefer the newest asset, skip mismatched
releases, and refuse to write such a manifest at build time.
2026-11-02 22:37:35 +00:00
spark 3751589db0 fix(delivery): sweep rejected photos left on destinations
ci / rust (pull_request) Failing after 1m44s
ci / typescript (pull_request) Successful in 9m7s
A REJECT that bypasses the library PATCH (or races the upload) could leave
the file on Nextcloud; reclaim those on the worker tick and cover reject/un-pick in tests.
2026-11-02 21:57:05 +00:00
spark 0179e2bd86 Desktop 0.3.25: USB tether and FTP machine labels (BIT-134) (#135)
ci / rust (push) Successful in 6m35s
ci / typescript (push) Successful in 11m23s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 28m22s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 25m53s
Desktop 0.3.25: USB tether and FTP machine labels (BIT-134)
2026-11-02 21:46:58 +00:00
spark 73b3b65925 Desktop 0.3.25: USB tether for PTP cameras and machine labels on local FTP (BIT-134).
ci / rust (pull_request) Successful in 5m36s
ci / typescript (pull_request) Successful in 10m26s
When a body is on the cable, new shots go to the open event and the clock syncs to
this Mac; FTP local shows one connection per machine. EOS Utility must release the
cable first.
2026-11-02 21:32:57 +00:00
spark 7a552e2c81 Merge pull request 'fix(desktop): dont 500 the installer download when Gitea releases is unreachable (BIT-31961)' (#133) from fix/BIT-31961-desktop-download-fetch-failed into main
ci / rust (push) Successful in 4m22s
ci / typescript (push) Successful in 7m42s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 23m14s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 31m17s
2026-11-01 01:02:46 +00:00
paula-alves c652715707 fix(desktop): don't 500 the installer download when Gitea releases is unreachable (BIT-31961)
ci / rust (pull_request) Successful in 3m54s
ci / typescript (pull_request) Successful in 8m1s
GET /v1/desktop/download/:releaseId/:name called DesktopReleases.file()
with no try/catch, unlike the sibling update-check route. A transient
network failure fetching the release/asset from Gitea threw a bare
undici TypeError (no file/line in its stack, since it originates
inside undici) straight through the route handler, landing on the
error hub as an unlocatable "TypeError: fetch failed" and a 500 to the
desktop app instead of a graceful retry signal.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31961
Paperclip-Run: 431a287c-0cb3-4f73-9288-ac8d20e18df8
2026-11-01 00:24:18 +00:00
spark b1561da69a Merge pull request 'fix(archive): classify libvips sequential-JPEG SOS errors as corrupt source (BIT-31700)' (#132) from task/BIT-31700-vips-sos-corrupt-source into main
ci / rust (push) Successful in 3m49s
ci / typescript (push) Successful in 7m8s
2026-10-29 11:12:25 +00:00
jos-alves b540ab447b fix(archive): classify libvips sequential-JPEG SOS errors as corrupt source (BIT-31700)
ci / rust (pull_request) Successful in 3m51s
ci / typescript (pull_request) Successful in 7m31s
VipsJpeg: Invalid SOS parameters for sequential JPEG is another shape of the
same truncated/corrupted cloud-archive JPEG that premature end and corrupt
header already cover; isCorruptSourceMessage didn't match it, so it fell
through to the generic failure path and reached the error hub as a warning
instead of being marked corrupt_source at info level.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31700
Paperclip-Run: 6435a4c4-0daa-41c4-8641-a0431c981ee8
2026-10-29 11:03:19 +00:00
spark 0b7af4f992 Merge pull request 'fix(sports): tell FPA homonyms apart by licence instead of a 409 (BIT-31898)' (#131) from fix/BIT-31898-fpa-associate-name-collision into main
ci / rust (push) Successful in 4m50s
ci / typescript (push) Successful in 8m50s
2026-10-28 02:02:58 +00:00
paula-alves 018cefaf7a fix(sports): tell FPA homonyms apart by licence instead of a 409 (BIT-31898)
ci / rust (pull_request) Successful in 4m3s
ci / typescript (pull_request) Successful in 7m58s
Two different people can share the exact same full name in the FPA
register; personFromFpaAssociate (full club register sync) and
personFromFpaLicence (add-by-licence) both threw person_name_taken in
that case, which fpaAssociates only logged and swallowed, but which
silently dropped that associate from the sync. The federation's
licence number is always free for this, so suffix it onto the name
instead of giving up.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31898
Paperclip-Run: aa809c11-1594-449d-bc49-93e96efbe4e5
2026-10-28 01:49:30 +00:00
spark f847cbff56 Site: câmara in-page para Tirar foto (iPhone) (#130)
ci / rust (push) Successful in 3m47s
ci / typescript (push) Successful in 7m27s
Site: câmara in-page para Tirar foto (iPhone) (#130)
2026-10-28 01:21:27 +00:00
spark 1b1dadda6c Site: open the front camera in-page for Tirar foto
ci / rust (pull_request) Successful in 5m30s
ci / typescript (pull_request) Successful in 8m27s
iPhone file+capture often returns HEIC or fails the hidden input.
Use getUserMedia like the kiosk so the probe is always JPEG.
2026-10-28 01:10:29 +00:00
spark 1dbd4156df Merge pull request 'Arquivo: procura pela ficha FPA (registo do clube) e câmara no telemóvel' (#129) from task/126-find-registry-first into main
ci / rust (push) Successful in 5m2s
ci / typescript (push) Successful in 9m34s
2026-10-28 01:02:24 +00:00
37 changed files with 2290 additions and 117 deletions

No files matched your search

@@ -26,6 +26,7 @@ describe("corrupt / incomplete archive sources (BIT-31621)", () => {
expect(isCorruptSourceMessage("premature end of JPEG")).toBe(true);
expect(isCorruptSourceMessage("Input file contains unsupported image format")).toBe(true);
expect(isCorruptSourceMessage("VipsForeignLoad: \"/tmp/x/original.jpg\" is not a known file format")).toBe(true);
expect(isCorruptSourceMessage("VipsJpeg: Invalid SOS parameters for sequential JPEG")).toBe(true);
expect(isCorruptSourceMessage("ffmpeg exited 234: Stream map '0:v:0' matches no streams")).toBe(false);
expect(isCorruptSourceMessage("GET /a failed: 503")).toBe(false);
});
+1 -1
View File
@@ -24,7 +24,7 @@ export class IncompleteDownload extends Error {
/** ffprobe/ffmpeg/sharp messages that mean the cloud file itself is damaged, not our pipeline. */
export function isCorruptSourceMessage(message: string): boolean {
return /moov atom not found|premature end|not a known file format|corrupt (?:jpeg )?header|Corrupt JPEG|Input file has corrupt header|Input file contains unsupported image format|unsupported image format|Invalid data found when processing input/i.test(
return /moov atom not found|premature end|not a known file format|corrupt (?:jpeg )?header|Corrupt JPEG|Input file has corrupt header|Input file contains unsupported image format|unsupported image format|Invalid data found when processing input|Invalid SOS parameters/i.test(
message,
);
}
+36 -1
View File
@@ -274,6 +274,28 @@ export class DeliveryService {
private editsCheckedAt = 0;
/**
* Deliveries still on a destination whose photo was rejected without going through the library PATCH (a direct
* DB update, an emergency script): queue them for removal. Un-picked (NONE) photos are not swept here — a
* destination may have been given a non-pick on purpose; only the library PATCH (PICK → NONE) retracts those.
*/
async queueOrphanRetracts(): Promise<number> {
const rows = await this.deps.db.$queryRaw<{ id: string; organization_id: string }[]>`
UPDATE delivery_items di SET status = 'QUEUED', retract = true, attempts = 0, next_attempt_at = now(),
last_error = NULL, finished_at = NULL, updated_at = now()
FROM photos p
WHERE p.id = di.photo_id
AND di.status IN ('DONE', 'WAITING') AND di.retract = false
AND p.flag = 'REJECT'
RETURNING di.id, di.organization_id`;
for (const r of rows) {
const item = await this.deps.db.deliveryItem.findUnique({ where: { id: r.id } });
if (item) this.deps.broadcaster.library(item.organizationId, { type: "delivery.updated", item: toItemSummary(item) });
}
if (rows.length) this.deps.log.info({ count: rows.length }, "delivery: rejected photos still on a destination, taken back");
return rows.length;
}
/**
* Delivered photos edited again since (a crop put right, a colour fixed), once the edits have paused for a
* minute: sent again to where they went, with the same name (a file is replaced; on ZeroZero the new one goes up
@@ -321,10 +343,11 @@ export class DeliveryService {
/** Atomically takes up to `limit` due items (safe with several workers). */
async claim(limit: number): Promise<string[]> {
// Every half minute: delivered photos edited again join the queue.
// Every half minute: edited re-sends and rejected photos left on a destination join the queue.
if (Date.now() - this.editsCheckedAt > 30_000) {
this.editsCheckedAt = Date.now();
await this.queueEdited().catch((err) => this.deps.log.warn({ err }, "delivery: edited photos not checked"));
await this.queueOrphanRetracts().catch((err) => this.deps.log.warn({ err }, "delivery: orphan retracts not checked"));
}
if (limit <= 0) return [];
const rows = await this.deps.db.$queryRaw<{ id: string }[]>`
@@ -424,6 +447,18 @@ export class DeliveryService {
this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) });
return saved;
}
// Rejected after this item was queued (or a flag flip that skipped retractPhotos): never upload; the next claim
// removes anything already on the destination.
if (item.photo.flag === "REJECT") {
const saved = await db.deliveryItem.update({
where: { id: itemId },
data: item.remotePath || item.target.kind === "LOCAL"
? { status: "QUEUED", retract: true, attempts: Math.max(0, item.attempts - 1), nextAttemptAt: new Date(), lastError: null, finishedAt: null }
: { status: "RETRACTED", retract: false, finishedAt: new Date() },
});
this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) });
return saved;
}
let update: Partial<DeliveryItem>;
// The players' names come from the faces (who is where, face and shirt number): give their reading a moment,
// so a photo does not leave without names. Waiting does not count as an attempt.
+50 -28
View File
@@ -62,6 +62,27 @@ export function newer(candidate: string, current: string): boolean {
/** The full installer a person downloads and opens, per platform. */
const INSTALLER: Record<string, RegExp> = { darwin: /\.dmg$/, windows: /\.msi$|-setup\.exe$/, linux: /\.AppImage$/ };
/** Version embedded in a Tauri minisign trusted comment, if any (`file:…\tversion:X.Y.Z`). */
export function signedVersion(signature: string): string | null {
for (const line of signature.split(/\r?\n/)) {
let raw: Buffer;
try {
raw = Buffer.from(line, "base64");
} catch {
continue;
}
const text = raw.toString("utf8");
const m = /\bversion:([0-9]+\.[0-9]+\.[0-9]+(?:[-.+][\w.-]+)?)/.exec(text);
if (m) return m[1]!;
}
return null;
}
/** Newest asset with this name (Gitea keeps duplicates when a tag is rebuilt). */
function latestAsset(assets: GiteaAsset[], name: string): GiteaAsset | undefined {
return assets.filter((a) => a.name === name).sort((a, b) => b.id - a.id)[0];
}
export class DesktopReleases {
private cache: { at: number; releases: GiteaRelease[] } | null = null;
@@ -85,17 +106,6 @@ export class DesktopReleases {
return all;
}
/** The newest release that has this platform's update (a newer one may still be building, or wait for its Mac). */
private async forPlatform(target: string, arch: string): Promise<{ release: GiteaRelease; manifest: GiteaAsset } | null> {
// Universal macOS builds serve both Apple chips.
const names = [`update-${target}-${arch}.json`, ...(target === "darwin" ? ["update-darwin-universal.json"] : [])];
for (const release of await this.releases()) {
const manifest = names.map((n) => release.assets.find((a) => a.name === n)).find(Boolean);
if (manifest) return { release, manifest };
}
return null;
}
private async download(asset: GiteaAsset): Promise<Response> {
const res = await this.fetchImpl(asset.browser_download_url, { headers: { authorization: `token ${this.config.token}` } });
if (!res.ok) throw new Error(`gitea asset ${asset.name}: ${res.status}`);
@@ -111,28 +121,34 @@ export class DesktopReleases {
arch: string,
current: string,
): Promise<{ version: string; notes: string; pub_date?: string; url: string; signature: string; installer?: string } | null> {
const found = await this.forPlatform(target, arch);
if (!found) return null;
const { release } = found;
const manifest = Manifest.parse(await (await this.download(found.manifest)).json());
if (!newer(manifest.version, current)) return null;
if (!release.assets.some((a) => a.name === manifest.file)) return null;
const installer = release.assets.find((a) => INSTALLER[target]?.test(a.name));
return {
version: manifest.version,
notes: manifest.notes ?? release.body ?? "",
...(manifest.pub_date ?? release.published_at ? { pub_date: (manifest.pub_date ?? release.published_at)! } : {}),
url: `/v1/desktop/download/${release.id}/${encodeURIComponent(manifest.file)}`,
signature: manifest.signature,
...(installer ? { installer: `/v1/desktop/download/${release.id}/${encodeURIComponent(installer.name)}` } : {}),
};
// Walk newest → older: a release whose manifest/signature disagree (re-tagged build) is skipped.
const names = [`update-${target}-${arch}.json`, ...(target === "darwin" ? ["update-darwin-universal.json"] : [])];
for (const release of await this.releases()) {
const manifestAsset = names.map((n) => latestAsset(release.assets, n)).find(Boolean);
if (!manifestAsset) continue;
const manifest = Manifest.parse(await (await this.download(manifestAsset)).json());
if (!newer(manifest.version, current)) return null;
const signed = signedVersion(manifest.signature);
if (signed && signed !== manifest.version) continue;
if (!latestAsset(release.assets, manifest.file)) continue;
const installer = [...release.assets].filter((a) => INSTALLER[target]?.test(a.name)).sort((a, b) => b.id - a.id)[0];
return {
version: manifest.version,
notes: manifest.notes ?? release.body ?? "",
...(manifest.pub_date ?? release.published_at ? { pub_date: (manifest.pub_date ?? release.published_at)! } : {}),
url: `/v1/desktop/download/${release.id}/${encodeURIComponent(manifest.file)}`,
signature: manifest.signature,
...(installer ? { installer: `/v1/desktop/download/${release.id}/${encodeURIComponent(installer.name)}` } : {}),
};
}
return null;
}
/** The installer itself, streamed from a desktop release. */
async file(releaseId: number, name: string): Promise<{ body: Readable; size: string | null } | null> {
const release = (await this.releases()).find((r) => r.id === releaseId);
if (!release) return null;
const asset = release.assets.find((a) => a.name === name);
const asset = latestAsset(release.assets, name);
if (!asset || /\.json$/.test(name)) return null;
const res = await this.download(asset);
if (!res.body) return null;
@@ -165,7 +181,13 @@ export async function registerDesktopRoutes(app: FastifyInstance, deps: { releas
app.get("/v1/desktop/download/:releaseId/:name", async (req, reply) => {
const { releaseId, name } = z.object({ releaseId: z.coerce.number().int().positive(), name: z.string().min(1).max(200) }).parse(req.params);
const file = releases ? await releases.file(releaseId, name) : null;
let file: { body: Readable; size: string | null } | null;
try {
file = releases ? await releases.file(releaseId, name) : null;
} catch (err) {
req.log.warn({ err }, "desktop download failed");
return reply.code(503).send({ error: "download_unavailable" });
}
if (!file) return reply.code(404).send({ error: "not_found" });
if (file.size) reply.header("content-length", file.size);
return reply.header("content-type", "application/octet-stream").header("content-disposition", `attachment; filename="${name.replace(/[^\w.-]+/g, "_")}"`).send(file.body);
+17 -8
View File
@@ -5,7 +5,7 @@ import type { Db } from "../db.js";
import type { SportsCompetition, SportsPlayer, SportsProvider } from "../generated/prisma/client.js";
import type { IngestLogger } from "../ingest/service.js";
import { DEFAULT_CODE_LIST } from "../library/iptc.js";
import { AppError, badRequest, notFound } from "../lib/errors.js";
import { badRequest, notFound } from "../lib/errors.js";
import { waitUntil } from "../lib/idle.js";
import type { LocalStorage } from "../storage/storage.js";
import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js";
@@ -1268,10 +1268,14 @@ export class SportsService {
if (!person) {
const short = fpaShortName(member.name);
const same = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: short } } });
// A name taken by someone else (another licence, another club): the full name.
const name = !same ? short : member.name;
const other = same ? await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } }) : null;
if (other && other.licence && other.licence !== member.licence) throw new AppError(409, "person_name_taken");
// A name taken by someone else: the full name, and if that is taken too (by another licence), the licence
// number — guaranteed free — tells the two apart for sure.
let name = !same ? short : member.name;
let other = same ? await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } }) : null;
if (other && other.licence && other.licence !== member.licence) {
name = `${member.name} (${member.licence})`;
other = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } });
}
person = other ?? (await db.person.create({ data: { organizationId: orgId, name, club, licence: member.licence } }));
created = !other;
}
@@ -1353,9 +1357,14 @@ export class SportsService {
if (!person) {
const short = fpaShortName(a.name);
const same = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: short } } });
const name = !same ? short : a.name;
const other = same ? await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } }) : null;
if (other && other.licence && other.licence !== a.licence) throw new AppError(409, "person_name_taken");
// A name taken by someone else: the full name, and if that is taken too (by another licence), the licence
// number — guaranteed free — tells the two apart for sure.
let name = !same ? short : a.name;
let other = same ? await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } }) : null;
if (other && other.licence && other.licence !== a.licence) {
name = `${a.name} (${a.licence})`;
other = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } });
}
person = other ?? (await db.person.create({ data: { organizationId: orgId, name, club: clubName, licence: a.licence } }));
created = !other;
}
+6
View File
@@ -571,6 +571,12 @@ describe("delivery", () => {
expect(zz.uploads.get(resent.remotePath!.split("/")[1]!)!.meta.filename).toBe(zz.uploads.get(itemA.remotePath!.split("/")[1]!)!.meta.filename);
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.
await ctx.db.photo.update({ where: { id: b }, data: { flag: "REJECT" } });
expect(await delivery.queueOrphanRetracts()).toBe(1);
expect(await ctx.db.deliveryItem.findFirstOrThrow({ where: { photoId: b } })).toMatchObject({ status: "QUEUED", retract: true });
expect(await delivery.queueOrphanRetracts()).toBe(0);
// A wrong password stops at once, with the desk's message.
await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}`, headers: bearer(token), payload: { password: "errada" } });
const failed = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/test`, headers: bearer(token) });
+59 -1
View File
@@ -1,5 +1,6 @@
import Fastify from "fastify";
import { describe, expect, it } from "vitest";
import { DesktopReleases, newer } from "../src/desktop/updates.js";
import { DesktopReleases, newer, registerDesktopRoutes, signedVersion } from "../src/desktop/updates.js";
const API = "https://git.example/api/v1/repos/o/r";
@@ -27,6 +28,51 @@ describe("desktop updates", () => {
expect(newer("1.0.0", "1.0.0-beta.2")).toBe(true);
});
it("reads the version Tauri embeds in a signature trusted comment", () => {
const sig = Buffer.from("trusted comment: timestamp:1\tfile:PhotoReport.app.tar.gz\tversion:0.3.24\n").toString("base64");
expect(signedVersion(sig)).toBe("0.3.24");
expect(signedVersion("dW50cnVzdGVkIGNvbW1lbnQ6IHNpZw==")).toBeNull();
});
it("skips a release whose manifest version disagrees with the signature (re-tagged build)", async () => {
const badSig = Buffer.from("trusted comment: timestamp:1\tfile:PhotoReport.app.tar.gz\tversion:0.3.24\n").toString("base64");
const goodSig = Buffer.from("trusted comment: timestamp:2\tfile:PhotoReport.app.tar.gz\tversion:0.3.25\n").toString("base64");
const releases = [
{
id: 20,
tag_name: "desktop-v0.3.25",
draft: false,
prerelease: false,
body: "",
published_at: null,
assets: [asset(1, "update-darwin-universal.json"), asset(2, "PhotoReport.app.tar.gz"), asset(3, "PhotoReport_0.3.24_universal.dmg")],
},
{
id: 19,
tag_name: "desktop-v0.3.24",
draft: false,
prerelease: false,
body: "ok",
published_at: null,
assets: [asset(10, "update-darwin-universal.json"), asset(11, "PhotoReport.app.tar.gz"), asset(12, "PhotoReport_0.3.24_universal.dmg")],
},
];
const files: Record<string, unknown> = {
// First download is the bad 0.3.25 manifest (same filename across releases; fake fetch keys by basename).
"update-darwin-universal.json": { version: "0.3.25", file: "PhotoReport.app.tar.gz", signature: badSig },
"PhotoReport.app.tar.gz": "bytes",
};
const r = new DesktopReleases({ api: API, token: "t" }, fakeGitea(releases, files).impl);
// Bad newest release is skipped; nothing older matches 0.3.25 either with this stub, so null — then swap to good.
expect(await r.updateFor("darwin", "aarch64", "0.3.24")).toBeNull();
files["update-darwin-universal.json"] = { version: "0.3.25", file: "PhotoReport.app.tar.gz", signature: goodSig };
const r2 = new DesktopReleases({ api: API, token: "t" }, fakeGitea(releases, files).impl);
expect(await r2.updateFor("darwin", "aarch64", "0.3.24")).toMatchObject({
version: "0.3.25",
installer: "/v1/desktop/download/20/PhotoReport_0.3.24_universal.dmg",
});
});
it("answers with the newest desktop release for the platform, through the API, and nothing when up to date", async () => {
const releases = [
{ id: 7, tag_name: "desktop-v0.3.0", draft: false, prerelease: false, body: "Catálogo local", published_at: "2026-10-13T09:00:00Z", assets: [asset(1, "update-darwin-universal.json"), asset(2, "PhotoReport_universal.app.tar.gz"), asset(4, "PhotoReport_0.3.0_universal.dmg")] },
@@ -70,4 +116,16 @@ describe("desktop updates", () => {
expect(await r.updateFor("darwin", "aarch64", "0.3.2")).toMatchObject({ version: "0.3.4", url: "/v1/desktop/download/11/PhotoReport.app.tar.gz" });
expect(await r.file(11, "PhotoReport.app.tar.gz")).not.toBeNull();
});
it("answers 503 instead of crashing the route when Gitea is unreachable (BIT-31961)", async () => {
const releases = new DesktopReleases({ api: API, token: "t" }, async () => {
throw new TypeError("fetch failed");
});
const app = Fastify({ logger: false });
await registerDesktopRoutes(app, { releases, publicApiUrl: "https://app.example" });
const res = await app.inject({ method: "GET", url: "/v1/desktop/download/7/PhotoReport_universal.app.tar.gz" });
expect(res.statusCode).toBe(503);
expect(res.json()).toEqual({ error: "download_unavailable" });
});
});
+21
View File
@@ -388,6 +388,27 @@ describe("library", () => {
expect((await ctx.db.photo.findUnique({ where: { id: photoId } }))?.eventId).toBe(otherId);
});
it("takes a delivered file back when the photo is rejected or un-picked", async () => {
const { orgId, admin, event } = await setup();
const a = (await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#111111" })))) as { photoId: string };
const b = (await service.ingestFile(await drop("foto.r1", "b.jpg", await jpeg({ color: "#222222" })))) as { photoId: string };
await ctx.db.photo.updateMany({ where: { id: { in: [a.photoId, b.photoId] } }, data: { eventId: event.id, flag: "PICK" } });
const target = await ctx.db.deliveryTarget.create({
data: { organizationId: orgId, name: "FPA", kind: "NEXTCLOUD", baseUrl: "https://cloud.photoreport.pt", username: "fpa", secretEnc: "sealed", folderTemplate: "/{event}/", fileNameTemplate: "{n}.jpg" },
});
const [itemA, itemB] = await Promise.all(
[a.photoId, b.photoId].map((photoId, i) =>
ctx.db.deliveryItem.create({
data: { organizationId: orgId, targetId: target.id, photoId, eventId: event.id, sequence: i + 1, status: "DONE", remotePath: `/${i + 1}.jpg` },
}),
),
);
expect((await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/photos`, headers: bearer(admin), payload: { ids: [a.photoId], patch: { flag: "REJECT" } } })).statusCode).toBe(200);
expect(await ctx.db.deliveryItem.findUnique({ where: { id: itemA.id } })).toMatchObject({ status: "QUEUED", retract: true });
expect((await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/photos`, headers: bearer(admin), payload: { ids: [b.photoId], patch: { flag: "NONE" } } })).statusCode).toBe(200);
expect(await ctx.db.deliveryItem.findUnique({ where: { id: itemB.id } })).toMatchObject({ status: "QUEUED", retract: true });
});
it("previews the IPTC a delivery will write, with codes and identified players", async () => {
const { orgId, admin } = await setup();
const saved = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/code-list`, headers: bearer(admin), payload: { content: "v7\tMiguel Silva (VSC)\nbad\n" } });
+14
View File
@@ -526,6 +526,20 @@ describe("sports data service", () => {
expect(coach!.referenceKey).toBeTruthy();
});
it("FPA: two associates with the exact same name get told apart by licence, instead of a person_name_taken error", async () => {
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa-homonimos", role: "OWNER" });
const first = await sports.personFromFpaAssociate(org!.id, { licence: "900001", internalId: null, name: "Maria Silva", photo: null, kind: "athlete" });
expect(first).toMatchObject({ created: true, person: { name: "Maria Silva" } });
const second = await sports.personFromFpaAssociate(org!.id, { licence: "900002", internalId: null, name: "Maria Silva", photo: null, kind: "athlete" });
expect(second).toMatchObject({ created: true, person: { name: "Maria Silva (900002)" } });
expect(second.person.id).not.toBe(first.person.id);
const people = await ctx.db.person.findMany({ where: { organizationId: org!.id }, orderBy: { licence: "asc" } });
expect(people.map((p) => [p.name, p.licence])).toEqual([
["Maria Silva", "900001"],
["Maria Silva (900002)", "900002"],
]);
});
it("keeps sports data to members and FPF links to admins", async () => {
const { user } = await seedUser(ctx.db, "[email protected]", { org: "abola", role: "PHOTOGRAPHER" });
const token = (await login(ctx.app, user.email)).body.accessToken;
+46 -1
View File
@@ -134,7 +134,11 @@ export const t = {
stop: "Desligar",
help: "A câmara envia por FTP para este computador (mesma rede). Cada foto que chega sobe logo para o evento abaixo e o original passa para a pasta de trabalho do evento.",
camera: "Na câmara",
edit: "Configurar",
edit: "Ligações",
connections: "Máquinas",
connectionsHelp: "Uma ligação por corpo. No menu FTP da câmara escreves o servidor, a porta, o utilizador e a palavra-passe. O cabo USB não usa isto: liga sozinho.",
machine: "Máquina",
addMachine: "+ Outra máquina",
server: "Servidor",
port: "Porta",
user: "Utilizador",
@@ -186,6 +190,47 @@ export const t = {
},
outdated: "Esta versão da app de computador ainda não tem FTP local. Instala a versão nova (0.2 ou mais recente).",
},
usbCamera: {
button: "USB",
title: "Câmara por USB",
help: "Com a câmara ligada por cabo, vês o cartão e cada foto nova. Nada sobe sozinho: escolhes o que descarregar para o evento abaixo.",
none: "Nenhuma câmara ligada por cabo.",
tetherOn: "Cabo ligado",
tetherOff: "Cabo desligado",
turnOn: "Ligar cabo",
turnOff: "Desligar cabo",
opening: "A ligar à câmara…",
tethered: "Câmara pronta — escolhe o que descarregar",
busy: "A câmara está ocupada por outra app (o EOS Utility, por exemplo). Fecha-a: o cabo só pode estar com uma de cada vez. A tentar outra vez sozinho.",
idle: "Cabo desligado",
listing: "A ler o cartão…",
rawKept: "O RAW fica na pasta de trabalho, ao lado do JPEG.",
outdated: "Esta versão da app de computador ainda não lê a câmara por USB. Instala a versão nova.",
received: (n: number) => (n === 1 ? "1 foto recebida" : `${n} fotos recebidas`),
sent: (n: number) => `${n} enviadas`,
failed: (n: number) => (n === 1 ? "1 falhou" : `${n} falharam`),
clockOk: "Relógio acertado com este computador.",
clockAhead: (n: number) => `A câmara estava ${n} s adiantada. O relógio ficou igual ao deste computador.`,
clockBehind: (n: number) => `A câmara estava ${n} s atrasada. O relógio ficou igual ao deste computador.`,
clockUnsupported: "Esta câmara não deixa acertar o relógio pelo cabo.",
clockSync: "Acertar relógio outra vez",
card: "Cartão",
files: (n: number) => (n === 1 ? "1 ficheiro" : `${n} ficheiros`),
newShot: "nova",
imported: "já puxada",
selectNew: "Seleccionar novas",
selectEvent: "Do evento",
selectAll: "Todas",
selectNone: "Nenhuma",
refresh: "Actualizar lista",
download: (n: number) => (n === 1 ? "Descarregar 1" : `Descarregar ${n}`),
emptyCard: "O cartão ainda não tem fotos listadas.",
outsideEvent: "fora do evento",
windowHint: (inWin: number, total: number) => `${inWin} de ${total} na janela do evento`,
autoIngest: "Puxar automaticamente (só na janela do evento)",
autoIngestHelp: "Só fotos novas cuja hora da câmara cai entre o início e o fim de ingestão do evento. O resto do cartão fica por escolher.",
autoNeedsEvent: "Escolhe um evento com janela de ingestão para o automático.",
},
squad: {
title: "Pessoas",
help: "Quem pode ser identificado nas fotos, por clube. Os plantéis das competições que segues entram sozinhos; aqui juntas outras pessoas e as fotos oficiais (com a foto, a pessoa é sugerida logo no primeiro jogo).",
+32 -15
View File
@@ -15,7 +15,7 @@ import type { DesktopOrigin, PreviewOf, UploadStatus } from "./uploads.js";
export interface FtpSettings {
port: number;
/** `enabled` missing (older desktop app): on. */
users: { name: string; password: string; enabled?: boolean }[];
users: { name: string; password: string; enabled?: boolean; label?: string }[];
ingest: string;
workFolder: string;
autoStart: boolean;
@@ -47,6 +47,9 @@ export interface FtpTarget {
id: string;
title: string;
date: string;
/** Event ingest window (ISO). USB auto-ingest only pulls shots inside this range. */
ingestFrom?: string;
ingestUntil?: string;
}
export type Invoke = <T>(cmd: string, args?: Record<string, unknown>) => Promise<T>;
@@ -120,7 +123,15 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
originalsRef.current = !!status?.settings.uploadOriginals;
const setTarget = useCallback((e: EventSummary | null) => {
const next = e ? { id: e.id, title: eventLabel(e), date: e.startsAt.slice(0, 10) } : null;
const next = e
? {
id: e.id,
title: eventLabel(e),
date: e.startsAt.slice(0, 10),
ingestFrom: e.ingestFrom,
ingestUntil: e.ingestUntil,
}
: null;
setTargetState(next);
prefs.set("ftp.target", JSON.stringify(next));
}, []);
@@ -382,21 +393,25 @@ function SettingsForm({ ftp, initial, onDone }: { ftp: LocalFtpState; initial: F
<input className={field} type="number" min={1024} max={65535} value={s.port} onChange={(e) => setS({ ...s, port: Number(e.target.value) })} />
</label>
<div>
<span className="text-[11px] uppercase tracking-wide text-faint">{L.logins}</span>
<span className="text-[11px] uppercase tracking-wide text-faint">{L.connections}</span>
<p className="mb-1 text-[11px] text-faint">{L.connectionsHelp}</p>
{s.users.map((u, i) => (
<div key={i} className="mt-1 flex items-center gap-1">
<input type="checkbox" aria-label={`${L.loginOn}: ${u.name || L.user}`} title={L.loginOn} checked={u.enabled !== false} onChange={(e) => setUser(i, { enabled: e.target.checked })} />
<input className={field} aria-label={L.user} placeholder={L.user} value={u.name} onChange={(e) => setUser(i, { name: e.target.value })} autoComplete="off" />
<input className={field} aria-label={L.password} placeholder={L.password} value={u.password} onChange={(e) => setUser(i, { password: e.target.value })} autoComplete="off" />
{s.users.length > 1 && (
<button type="button" aria-label={L.removeLogin} onClick={() => setS({ ...s, users: s.users.filter((_, j) => j !== i) })} className="px-1 text-faint hover:text-ink">
×
</button>
)}
<div key={i} className="mb-2 border border-line bg-[#161617] p-2">
<input className={field} aria-label={L.machine} placeholder={L.machine} value={u.label ?? ""} onChange={(e) => setUser(i, { label: e.target.value })} autoComplete="off" />
<div className="mt-1 flex items-center gap-1">
<input type="checkbox" aria-label={`${L.loginOn}: ${u.name || L.user}`} title={L.loginOn} checked={u.enabled !== false} onChange={(e) => setUser(i, { enabled: e.target.checked })} />
<input className={field} aria-label={L.user} placeholder={L.user} value={u.name} onChange={(e) => setUser(i, { name: e.target.value })} autoComplete="off" />
<input className={field} aria-label={L.password} placeholder={L.password} value={u.password} onChange={(e) => setUser(i, { password: e.target.value })} autoComplete="off" />
{s.users.length > 1 && (
<button type="button" aria-label={L.removeLogin} onClick={() => setS({ ...s, users: s.users.filter((_, j) => j !== i) })} className="px-1 text-faint hover:text-ink">
×
</button>
)}
</div>
</div>
))}
<button type="button" onClick={() => setS({ ...s, users: [...s.users, { name: "", password: "", enabled: true }] })} className="mt-1 text-accent underline">
{L.addLogin}
<button type="button" onClick={() => setS({ ...s, users: [...s.users, { name: "", password: "", enabled: true, label: "" }] })} className="text-accent underline">
{L.addMachine}
</button>
</div>
<label className="block">
@@ -492,8 +507,10 @@ export function LocalFtpButton({ ftp, events, openEventId }: { ftp: LocalFtpStat
<dd className="select-all text-ink">{status.settings.port}</dd>
{status.settings.users.map((u) => (
<div key={u.name} className="contents">
<dt className="text-faint">{L.user}</dt>
<dt className="text-faint">{u.label || L.machine}</dt>
<dd className={`select-all ${u.enabled === false ? "text-faint line-through" : "text-ink"}`}>
<span className="font-sans">{u.label || u.name}</span>
<span className="text-faint"> · </span>
{u.name} <span className="text-faint">/</span> {u.password}
{u.enabled === false && <span className="ml-1 font-sans no-underline">({L.loginOff})</span>}
</dd>
+97
View File
@@ -0,0 +1,97 @@
import { render, renderHook, screen, waitFor } from "@testing-library/react";
import type { EventSummary } from "@photoreport/sdk";
import { describe, expect, it, vi } from "vitest";
import type { Invoke } from "./LocalFtp.js";
import type { UploadStatus } from "./uploads.js";
import { UsbCameraButton, type UsbStatus, inEventWindow, useUsbCamera, withSidecars } from "./UsbCamera.js";
const camera: UsbStatus = {
supported: true,
tether: true,
devices: [{ id: "abc", name: "Canon Digital Camera", vendorId: 1193, productId: 13075, state: "tethered", error: null, catalogReady: true }],
files: [
{ name: "IMG_0001.JPG", size: 10, isNew: true, imported: false },
{ name: "IMG_0001.CR3", size: 20, isNew: true, imported: false },
{ name: "IMG_0002.JPG", size: 10, isNew: false, imported: false },
],
};
function shell(files: { path: string; name: string; size: number; modifiedMs: number }[]) {
const sent: unknown[] = [];
const invoke = vi.fn(async (cmd: string, args?: Record<string, unknown>) => {
if (cmd === "camera_status") return camera;
if (cmd === "camera_take") return files.splice(0);
if (cmd === "ftp_preview") return [...new TextEncoder().encode(`preview of ${String(args?.path)}`)];
if (cmd === "ftp_info") return { sha256: "sha", size: 5_000_000, width: 6000, height: 4000 };
if (cmd === "ftp_sent") {
sent.push(args);
return null;
}
return null;
}) as unknown as Invoke;
return { invoke, sent };
}
const event = { id: "ev1", title: "", home: "Portugal", away: "Suíça", startsAt: "2026-11-04T19:00:00Z" } as EventSummary;
const usbStub = {
status: camera,
outdated: false,
counts: { received: 0, sent: 0, failed: 0 },
setTether: vi.fn(),
syncClock: vi.fn(),
importFiles: vi.fn(),
refresh: vi.fn(),
autoIngest: false,
setAutoIngest: vi.fn(),
};
describe("usb tether", () => {
it("pulls only files the shell already downloaded (chosen on the camera panel)", async () => {
const { invoke, sent } = shell([{ path: "/ingest/.usb/IMG_0001.JPG", name: "IMG_0001.JPG", size: 10, modifiedMs: 1 }]);
const added: { name: string; eventId: string | undefined }[] = [];
const add = (files: Iterable<File>, eventId?: string, onSettled?: (f: File, s: UploadStatus) => void) => {
for (const f of files) {
added.push({ name: f.name, eventId });
onSettled?.(f, "done");
}
};
renderHook(() => useUsbCamera(add, true, { id: "ev1", title: "Portugal x Suíça", date: "2026-11-04" }, invoke));
await waitFor(() => expect(added).toEqual([{ name: "IMG_0001.JPG", eventId: "ev1" }]));
await waitFor(() => expect(sent).toEqual([{ path: "/ingest/.usb/IMG_0001.JPG", event: "Portugal x Suíça", date: "2026-11-04" }]));
});
it("uses the open event when a camera is plugged in and none is chosen", async () => {
const setTarget = vi.fn();
render(<UsbCameraButton usb={usbStub} target={null} setTarget={setTarget} openEvent={event} />);
await waitFor(() => expect(setTarget).toHaveBeenCalledWith(event));
expect(screen.getByRole("button", { name: /USB/ })).toBeTruthy();
});
it("leaves a chosen event alone", () => {
const setTarget = vi.fn();
render(
<UsbCameraButton
usb={usbStub}
target={{ id: "other", title: "ABC x Benfica", date: "2026-10-12" }}
setTarget={setTarget}
openEvent={event}
/>,
);
expect(setTarget).not.toHaveBeenCalled();
});
it("adds the RAW sidecar when a JPEG is selected for download", () => {
expect(withSidecars(["IMG_0001.JPG"], camera.files).sort()).toEqual(["IMG_0001.CR3", "IMG_0001.JPG"]);
expect(withSidecars(["IMG_0002.JPG"], camera.files)).toEqual(["IMG_0002.JPG"]);
});
it("only treats shots inside the event ingest window as auto-eligible", () => {
const from = "2026-11-03T18:00:00.000Z";
const until = "2026-11-03T23:00:00.000Z";
expect(inEventWindow({ createdMs: Date.parse("2026-11-03T19:30:00Z") }, from, until)).toBe(true);
expect(inEventWindow({ createdMs: Date.parse("2026-11-02T19:30:00Z") }, from, until)).toBe(false);
expect(inEventWindow({ createdMs: null }, from, until)).toBe(false);
expect(inEventWindow({ createdMs: Date.parse("2026-11-03T19:30:00Z") }, undefined, until)).toBe(false);
});
});
+430
View File
@@ -0,0 +1,430 @@
import type { EventSummary } from "@photoreport/sdk";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { t } from "../i18n.js";
import { asArrayBuffer, prefs } from "../platform.js";
import { type FtpTarget, type IncomingFile, type Invoke, eventLabel } 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`). */
export interface UsbCamera {
id: string;
name: string;
vendorId: number;
productId: number;
/** opening: session starting; tethered: ready to pick files; busy: another app holds the cable; idle: off. */
state: "opening" | "tethered" | "busy" | "idle";
error: string | null;
/** synced: clock set to this Mac; unsupported: the body refuses; null: not tried yet. */
clock?: "synced" | "unsupported" | null;
/** Seconds the camera was ahead of the Mac before the sync. */
clockOffset?: number | null;
/** True once the card listing is available. */
catalogReady?: boolean;
}
export interface UsbFile {
name: string;
size: number;
createdMs?: number | null;
isNew?: boolean;
imported?: boolean;
}
export interface UsbStatus {
supported: boolean;
tether: boolean;
devices: UsbCamera[];
files: UsbFile[];
}
const tauriInvoke: Invoke = async (cmd, args) => (await import("@tauri-apps/api/core")).invoke(cmd, args);
const IN_FLIGHT = 6;
const POLL_MS = 1000;
type Add = (files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus) => void, original?: PreviewOf) => void;
/**
* USB camera: the shell lists the card (and each new shot). Chosen files are downloaded into the
* ingest folder; this hook then uploads them to the target event like local FTP.
*/
export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | null, invoke: Invoke = tauriInvoke) {
const [status, setStatus] = useState<UsbStatus | null>(null);
const [outdated, setOutdated] = useState(false);
const [counts, setCounts] = useState({ received: 0, sent: 0, failed: 0 });
/** Auto-pull only new shots whose camera time sits inside the event's ingest window. */
const [autoIngest, setAutoIngestState] = useState(savedAutoIngest);
const backlog = useRef<IncomingFile[]>([]);
const inFlight = useRef(0);
const autoAsked = useRef<Set<string>>(new Set());
const targetRef = useRef(target);
targetRef.current = target;
const autoIngestRef = useRef(autoIngest);
autoIngestRef.current = autoIngest;
const pump = useCallback(() => {
while (inFlight.current < IN_FLIGHT && backlog.current.length) {
const f = backlog.current.shift()!;
const to = targetRef.current;
inFlight.current++;
void (async () => {
try {
const [bytes, original] = await Promise.all([
invoke<unknown>("ftp_preview", { path: f.path }).then(asArrayBuffer),
invoke<PreviewOf>("ftp_info", { path: f.path }),
]);
const file = new File([bytes], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
add([file], to?.id, (_file, result) => {
inFlight.current--;
if (result === "done" || result === "duplicate") {
setCounts((c) => ({ ...c, sent: c.sent + 1 }));
invoke("ftp_sent", { path: f.path, event: to?.title ?? "", date: to?.date ?? "" }).catch(() => {});
} else {
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
}
pump();
}, original);
} catch {
inFlight.current--;
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
pump();
}
})();
}
}, [add, invoke]);
useEffect(() => {
if (!enabled) return;
let alive = true;
const tick = async () => {
try {
const s = await invoke<UsbStatus>("camera_status");
if (!alive) return;
setStatus(s);
if (!s.supported || !s.tether) return;
const files = await invoke<IncomingFile[]>("camera_take");
if (!alive || !files.length) return;
const to = targetRef.current;
const photos = files.filter((f) => /\.jpe?g$/i.test(f.name));
for (const raw of files) {
if (/\.jpe?g$/i.test(raw.name)) continue;
void invoke("ftp_sent", { path: raw.path, event: to?.title ?? "", date: to?.date ?? "" }).catch(() => {});
}
if (!photos.length) return;
backlog.current.push(...photos);
setCounts((c) => ({ ...c, received: c.received + photos.length }));
pump();
} catch {
if (alive) setOutdated(true);
}
};
void tick();
const timer = setInterval(() => void tick(), POLL_MS);
return () => {
alive = false;
clearInterval(timer);
};
}, [enabled, invoke, pump]);
const syncClock = useCallback(async () => {
try {
setStatus(await invoke<UsbStatus>("camera_sync"));
} catch {
setOutdated(true);
}
}, [invoke]);
const setTether = useCallback(
async (on: boolean) => {
try {
setStatus(await invoke<UsbStatus>("camera_tether", { enabled: on }));
} catch {
setOutdated(true);
}
},
[invoke],
);
const importFiles = useCallback(
async (names: string[]) => {
if (!names.length) return;
try {
setStatus(await invoke<UsbStatus>("camera_import", { names }));
} catch {
setOutdated(true);
}
},
[invoke],
);
const refresh = useCallback(async () => {
try {
setStatus(await invoke<UsbStatus>("camera_refresh"));
} catch {
setOutdated(true);
}
}, [invoke]);
const setAutoIngest = useCallback((on: boolean) => {
setAutoIngestState(on);
prefs.set("usb.autoIngest", on ? "1" : "0");
if (!on) autoAsked.current.clear();
}, []);
// New tethered shots inside the event window only — never the rest of the card / other days.
useEffect(() => {
if (!autoIngest || !status?.tether || !target?.ingestFrom || !target.ingestUntil) return;
const due = status.files.filter(
(f) => /\.jpe?g$/i.test(f.name) && f.isNew && !f.imported && inEventWindow(f, target.ingestFrom, target.ingestUntil) && !autoAsked.current.has(f.name),
);
if (!due.length) return;
for (const f of due) autoAsked.current.add(f.name);
void importFiles(withSidecars(due.map((f) => f.name), status.files));
}, [autoIngest, status, target, importFiles]);
return { status, outdated, counts, setTether, syncClock, importFiles, refresh, autoIngest, setAutoIngest };
}
export type UsbCameraState = ReturnType<typeof useUsbCamera>;
const live = (d: UsbCamera) => d.state === "tethered" || d.state === "opening" || d.state === "busy";
function stemOf(name: string) {
return name.replace(/\.[^.]+$/, "").toLowerCase();
}
/** JPEG names plus any RAW that shares the same stem (Canon CR3 beside the JPG, etc.). */
export function withSidecars(selected: Iterable<string>, files: UsbFile[]): string[] {
const want = new Set([...selected].map(stemOf));
return files.filter((f) => want.has(stemOf(f.name))).map((f) => f.name);
}
/**
* True when the shot's camera time falls inside the event ingest window. No capture time → not auto-eligible
* (a full card without dates must not flood the event; the photographer picks those by hand).
*/
export function inEventWindow(file: Pick<UsbFile, "createdMs">, fromIso: string | undefined, untilIso: string | undefined): boolean {
if (!fromIso || !untilIso) return false;
if (file.createdMs == null || !Number.isFinite(file.createdMs)) return false;
const from = Date.parse(fromIso);
const until = Date.parse(untilIso);
if (!Number.isFinite(from) || !Number.isFinite(until)) return false;
return file.createdMs >= from && file.createdMs <= until;
}
function savedAutoIngest(): boolean {
return prefs.get("usb.autoIngest") === "1";
}
/** Button + panel in the Library toolbar. Hidden where the shell has no USB cameras (Windows, Linux). */
export function UsbCameraButton({
usb,
target,
setTarget,
openEvent,
}: {
usb: UsbCameraState;
target: FtpTarget | null;
setTarget: (e: EventSummary | null) => void;
openEvent: EventSummary | undefined;
}) {
const [open, setOpen] = useState(false);
const [picked, setPicked] = useState<Set<string>>(() => new Set());
const { status, counts, autoIngest, setAutoIngest } = usb;
const L = t.usbCamera;
const devices = status?.devices ?? [];
const files = status?.files ?? [];
const connected = devices.filter(live);
const on = connected.some((d) => d.state === "tethered" || d.state === "opening");
const catalogReady = devices.some((d) => d.catalogReady);
const jpegs = useMemo(() => files.filter((f) => /\.jpe?g$/i.test(f.name)), [files]);
const inWindow = useMemo(
() => jpegs.filter((f) => inEventWindow(f, target?.ingestFrom, target?.ingestUntil)),
[jpegs, target?.ingestFrom, target?.ingestUntil],
);
const hasWindow = !!(target?.ingestFrom && target.ingestUntil);
useEffect(() => {
if (connected.length && !target && openEvent) setTarget(openEvent);
}, [connected.length, target, openEvent, setTarget]);
// Drop selections that left the catalog (unplug / refresh).
useEffect(() => {
const names = new Set(files.map((f) => f.name));
setPicked((prev) => {
let changed = false;
const next = new Set<string>();
for (const n of prev) {
if (names.has(n)) next.add(n);
else changed = true;
}
return changed ? next : prev;
});
}, [files]);
if (status && !status.supported && !usb.outdated) return null;
const toggle = (name: string) => {
setPicked((prev) => {
const next = new Set(prev);
if (next.has(name)) next.delete(name);
else next.add(name);
return next;
});
};
const download = () => {
const names = withSidecars(picked, files);
void usb.importFiles(names);
};
return (
<div className="relative">
<button
onClick={() => setOpen((o) => !o)}
aria-expanded={open}
className="flex h-6 items-center gap-1.5 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
>
<span className={`inline-block h-1.5 w-1.5 rounded-full ${on ? "bg-[#4cc38a]" : connected.some((d) => d.state === "busy") ? "bg-[#f0a35a]" : "bg-faint"}`} />
{L.button}
{connected.length > 0 && <span className="max-w-40 truncate font-mono text-[11px] text-muted">{connected[0]?.name}</span>}
{jpegs.length > 0 && <span className="font-mono text-[11px] text-muted">{jpegs.length}</span>}
</button>
{open && (
<div className="absolute left-0 top-7 z-30 w-[420px] border border-black bg-panel p-3 text-[12px] shadow-xl" role="dialog" aria-label={L.title}>
<div className="mb-2 flex items-center justify-between">
<span className="font-semibold uppercase tracking-wide text-ink">{L.title}</span>
<span className={on ? "text-[#4cc38a]" : "text-faint"}>{status?.tether ? L.tetherOn : L.tetherOff}</span>
</div>
{usb.outdated && <p className="text-[#f0a35a]">{L.outdated}</p>}
{!usb.outdated && (
<>
<p className="mb-3 text-faint">{L.help}</p>
<div className="mb-3">
<div className="mb-1 text-[11px] uppercase tracking-wide text-faint">{t.localFtp.target}</div>
<div className="text-ink">{target ? `${target.date} · ${target.title}` : t.localFtp.noTarget}</div>
{hasWindow && (
<div className="mt-1 font-mono text-[11px] text-muted">
{L.windowHint(inWindow.length, jpegs.length)}
</div>
)}
{openEvent && openEvent.id !== target?.id && (
<button onClick={() => setTarget(openEvent)} className="mt-1 text-left text-accent underline">
{t.localFtp.useOpen(eventLabel(openEvent))}
</button>
)}
{on && hasWindow && (
<label className="mt-2 flex cursor-pointer items-center gap-2 text-ink">
<input type="checkbox" checked={autoIngest} onChange={(e) => setAutoIngest(e.target.checked)} className="accent-accent" />
{L.autoIngest}
</label>
)}
{autoIngest && !hasWindow && <p className="mt-1 text-[#f0a35a]">{L.autoNeedsEvent}</p>}
{autoIngest && hasWindow && <p className="mt-1 text-[11px] text-faint">{L.autoIngestHelp}</p>}
</div>
{devices.length === 0 && <p className="text-faint">{L.none}</p>}
{devices.map((d) => (
<div key={d.id} className="mb-2 border border-line bg-[#161617] p-2">
<div className="font-mono text-ink">{d.name}</div>
<div className={d.state === "busy" ? "text-[#f0a35a]" : "text-muted"}>
{d.state === "opening" && L.opening}
{d.state === "tethered" && (d.catalogReady ? L.tethered : L.listing)}
{d.state === "idle" && L.idle}
{d.state === "busy" && L.busy}
</div>
{d.error && d.state === "busy" && <div className="mt-1 font-mono text-[11px] text-faint">{d.error}</div>}
{d.clock === "unsupported" && <div className="mt-1 text-[#f0a35a]">{L.clockUnsupported}</div>}
{d.clock === "synced" && (
<div className="mt-1 text-[#4cc38a]">
{d.clockOffset == null || Math.abs(d.clockOffset) < 2
? L.clockOk
: d.clockOffset > 0
? L.clockAhead(Math.round(d.clockOffset))
: L.clockBehind(Math.round(Math.abs(d.clockOffset)))}
</div>
)}
</div>
))}
{on && (
<div className="mb-3 border border-line bg-[#161617] p-2">
<div className="mb-2 flex items-center justify-between gap-2">
<span className="text-[11px] uppercase tracking-wide text-faint">
{L.card}
{jpegs.length > 0 && <span className="ml-2 font-mono normal-case text-muted">{L.files(jpegs.length)}</span>}
</span>
<div className="flex flex-wrap gap-2">
{hasWindow && (
<button type="button" className="text-accent underline" onClick={() => setPicked(new Set(inWindow.filter((f) => !f.imported).map((f) => f.name)))}>
{L.selectEvent}
</button>
)}
<button type="button" className="text-accent underline" onClick={() => setPicked(new Set(jpegs.filter((f) => f.isNew && !f.imported).map((f) => f.name)))}>
{L.selectNew}
</button>
<button type="button" className="text-accent underline" onClick={() => setPicked(new Set(jpegs.filter((f) => !f.imported).map((f) => f.name)))}>
{L.selectAll}
</button>
<button type="button" className="text-accent underline" onClick={() => setPicked(new Set())}>
{L.selectNone}
</button>
<button type="button" className="text-accent underline" onClick={() => void usb.refresh()}>
{L.refresh}
</button>
</div>
</div>
{!catalogReady && <p className="text-faint">{L.listing}</p>}
{catalogReady && jpegs.length === 0 && <p className="text-faint">{L.emptyCard}</p>}
{jpegs.length > 0 && (
<ul className="max-h-48 overflow-auto border border-line">
{jpegs.map((f) => {
const checked = picked.has(f.name);
const matches = inEventWindow(f, target?.ingestFrom, target?.ingestUntil);
return (
<li key={f.name} className="flex items-center gap-2 border-b border-line px-2 py-1 last:border-b-0 hover:bg-cell">
<input type="checkbox" checked={checked} disabled={!!f.imported} onChange={() => toggle(f.name)} className="accent-accent" />
<button type="button" className="min-w-0 flex-1 truncate text-left font-mono text-ink disabled:text-faint" disabled={!!f.imported} onClick={() => toggle(f.name)}>
{f.name}
</button>
{f.isNew && !f.imported && <span className="text-[10px] uppercase text-[#4cc38a]">{L.newShot}</span>}
{f.imported && <span className="text-[10px] uppercase text-faint">{L.imported}</span>}
{hasWindow && !matches && !f.imported && <span className="text-[10px] uppercase text-[#f0a35a]">{L.outsideEvent}</span>}
</li>
);
})}
</ul>
)}
{picked.size > 0 && (
<button type="button" onClick={download} className="mt-2 h-7 w-full border border-black bg-cell px-3 text-ink hover:bg-cell-on">
{L.download(picked.size)}
</button>
)}
</div>
)}
{counts.received > 0 && (
<div className="mb-3 font-mono text-[11px] text-muted">
{L.received(counts.received)} · {L.sent(counts.sent)}
{counts.failed > 0 && <span className="text-[#f0a35a]"> · {L.failed(counts.failed)}</span>}
</div>
)}
<p className="mb-3 text-[11px] text-faint">{L.rawKept}</p>
{status && (
<div className="flex gap-2">
<button onClick={() => void usb.setTether(!status.tether)} className="h-7 border border-black bg-cell px-3 text-ink hover:bg-cell-on">
{status.tether ? L.turnOff : L.turnOn}
</button>
{on && (
<button onClick={() => void usb.syncClock()} className="h-7 border border-black bg-cell px-3 text-ink hover:bg-cell-on">
{L.clockSync}
</button>
)}
</div>
)}
</>
)}
</div>
)}
</div>
);
}
+9 -2
View File
@@ -7,8 +7,14 @@ import { useLocalFtp } from "./LocalFtp.js";
import { useLibraryLive } from "./realtime.js";
import { useUploadQueue } from "./uploads.js";
import { useOfflineSync } from "../offline/sync.js";
import { useUsbCamera } from "./UsbCamera.js";
type Ingest = { uploads: ReturnType<typeof useUploadQueue>; localFtp: ReturnType<typeof useLocalFtp>; desktop: boolean };
type Ingest = {
uploads: ReturnType<typeof useUploadQueue>;
localFtp: ReturnType<typeof useLocalFtp>;
usb: ReturnType<typeof useUsbCamera>;
desktop: boolean;
};
const IngestContext = createContext<Ingest | null>(null);
@@ -29,9 +35,10 @@ function IngestState({ api, orgId, children }: { api: ReturnType<typeof useAuth>
const desktop = isDesktop();
const uploads = useUploadQueue(api, orgId);
const localFtp = useLocalFtp(uploads.add, desktop && !!orgId, undefined, orgId);
const usb = useUsbCamera(uploads.add, desktop && !!orgId, localFtp.target);
useOfflineSync(api, orgId);
return (
<IngestContext.Provider value={{ uploads, localFtp, desktop }}>
<IngestContext.Provider value={{ uploads, localFtp, usb, desktop }}>
{desktop && !!orgId && <OriginalResponder api={api} add={uploads.add} />}
{desktop && !!orgId && <FailedRepair api={api} orgId={orgId} add={uploads.add} />}
{children}
+3 -1
View File
@@ -24,6 +24,7 @@ import { IptcInfo } from "../library/IptcInfo.js";
import { useLibraryLive } from "../library/realtime.js";
import { useIngest } from "../library/ingest.js";
import { LocalFtpButton } from "../library/LocalFtp.js";
import { UsbCameraButton } from "../library/UsbCamera.js";
import { CardIngestButton, CardOverallStatus } from "../library/CardIngest.js";
import { MergeButton } from "../library/MergeButton.js";
import { AutopilotButton } from "../library/Autopilot.js";
@@ -269,7 +270,7 @@ export function LibraryPage() {
dispatch({ type: "local", photos: localPhotos.list() });
}, [localVersion]);
const waitingChanges = useQueueSize(orgId);
const { uploads, localFtp, desktop } = useIngest();
const { uploads, localFtp, usb, desktop } = useIngest();
const fileInput = useRef<HTMLInputElement>(null);
const [dragging, setDragging] = useState(false);
const [sheet, setSheet] = useState<FolderListing | null>(null);
@@ -529,6 +530,7 @@ export function LibraryPage() {
{t.cardScan.button}
</button>
)}
{desktop && <UsbCameraButton usb={usb} target={localFtp.target} setTarget={localFtp.setTarget} openEvent={openEvent} />}
{desktop && <LocalFtpButton ftp={localFtp} events={events} openEventId={uploadInto} />}
{desktop && <CardIngestButton />}
{openEvent && (
+2
View File
@@ -12,6 +12,8 @@ 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**): a PTP body on the cable sends new shots
to the open event and syncs its clock to this Mac. EOS Utility must not hold the cable.
- 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;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@photoreport/desktop",
"version": "0.3.24",
"version": "0.3.26",
"private": true,
"type": "module",
"scripts": {
+2 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "photoreport-desktop"
version = "0.3.24"
version = "0.3.26"
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."
@@ -11,6 +11,7 @@ crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
cc = "1"
[dependencies]
tauri = { version = "2", features = [] }
+20 -2
View File
@@ -1,6 +1,18 @@
fn main() {
// The keychain and local FTP commands get ACL permissions, so the web app loaded from the server (a remote origin) can be
// granted them explicitly in capabilities/default.json.
let target = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
if target == "macos" {
// ImageCaptureCore: PTP cameras (they never mount as a volume).
cc::Build::new()
.file("src/camera_mac.m")
.flag("-fobjc-arc")
.compile("camera_mac");
println!("cargo:rustc-link-lib=framework=Foundation");
println!("cargo:rustc-link-lib=framework=ImageCaptureCore");
println!("cargo:rustc-link-lib=framework=IOKit");
println!("cargo:rerun-if-changed=src/camera_mac.m");
}
// The keychain, local FTP and USB camera commands get ACL permissions, so the web app loaded from the server
// (a remote origin) can be granted them explicitly in capabilities/default.json.
tauri_build::try_build(tauri_build::Attributes::new().app_manifest(
tauri_build::AppManifest::new().commands(&[
"refresh_token_get",
@@ -55,6 +67,12 @@ fn main() {
"delivery_folder_pick",
"delivery_write",
"import_upload_profiles",
"camera_status",
"camera_take",
"camera_tether",
"camera_sync",
"camera_import",
"camera_refresh",
]),
))
.expect("failed to run tauri-build");
@@ -69,7 +69,13 @@
"allow-delivery-folders",
"allow-delivery-folder-pick",
"allow-delivery-write",
"allow-import-upload-profiles"
"allow-import-upload-profiles",
"allow-camera-status",
"allow-camera-take",
"allow-camera-tether",
"allow-camera-sync",
"allow-camera-import",
"allow-camera-refresh"
],
"remote": {
"urls": [
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-camera-import"
description = "Enables the camera_import command without any pre-configured scope."
commands.allow = ["camera_import"]
[[permission]]
identifier = "deny-camera-import"
description = "Denies the camera_import command without any pre-configured scope."
commands.deny = ["camera_import"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-camera-refresh"
description = "Enables the camera_refresh command without any pre-configured scope."
commands.allow = ["camera_refresh"]
[[permission]]
identifier = "deny-camera-refresh"
description = "Denies the camera_refresh command without any pre-configured scope."
commands.deny = ["camera_refresh"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-camera-status"
description = "Enables the camera_status command without any pre-configured scope."
commands.allow = ["camera_status"]
[[permission]]
identifier = "deny-camera-status"
description = "Denies the camera_status command without any pre-configured scope."
commands.deny = ["camera_status"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-camera-sync"
description = "Enables the camera_sync command without any pre-configured scope."
commands.allow = ["camera_sync"]
[[permission]]
identifier = "deny-camera-sync"
description = "Denies the camera_sync command without any pre-configured scope."
commands.deny = ["camera_sync"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-camera-take"
description = "Enables the camera_take command without any pre-configured scope."
commands.allow = ["camera_take"]
[[permission]]
identifier = "deny-camera-take"
description = "Denies the camera_take command without any pre-configured scope."
commands.deny = ["camera_take"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-camera-tether"
description = "Enables the camera_tether command without any pre-configured scope."
commands.allow = ["camera_tether"]
[[permission]]
identifier = "deny-camera-tether"
description = "Denies the camera_tether command without any pre-configured scope."
commands.deny = ["camera_tether"]
+392
View File
@@ -0,0 +1,392 @@
//! USB tether (macOS). A Canon (or any PTP body) does not show up as a disk; ImageCaptureCore
//! (`camera_mac.m`) lists the card and each new shot. Nothing is copied until the photographer
//! picks files (`camera_import`). Chosen files land in `<ingest>/.usb` and the web app polls
//! `camera_take` to file them like a local-FTP photo. The dot folder is skipped by the FTP scan.
use std::path::Path;
use std::sync::{Mutex, OnceLock};
use serde::{Deserialize, Serialize};
use crate::ftp::{FtpState, IncomingFile};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CameraDevice {
pub id: String,
pub name: String,
pub vendor_id: i32,
pub product_id: i32,
/// "opening", "tethered", "busy" (another app holds the PTP session) or "idle".
pub state: String,
pub error: Option<String>,
/// "synced" after the body clock is set to this Mac, "unsupported" when it refuses.
#[serde(default)]
pub clock: Option<String>,
/// Seconds the camera was ahead of the Mac before the sync. Positive means the camera was fast.
#[serde(default)]
pub clock_offset: Option<f64>,
/// True once the card listing is complete (and keeps updating as new shots appear).
#[serde(default)]
pub catalog_ready: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CameraFile {
pub name: String,
pub size: u64,
#[serde(default)]
pub created_ms: Option<i64>,
/// True when the file appeared after this session opened (a tethered shot).
#[serde(default)]
pub is_new: bool,
/// Already pulled into the ingest folder in this session.
#[serde(default)]
pub imported: bool,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CameraStatus {
/// False on systems without ImageCaptureCore (the button stays hidden).
pub supported: bool,
pub tether: bool,
pub devices: Vec<CameraDevice>,
pub files: Vec<CameraFile>,
}
#[derive(Debug, Deserialize)]
#[serde(tag = "kind")]
enum CameraEvent {
#[serde(rename = "devices")]
Devices { devices: Vec<CameraDevice> },
#[serde(rename = "catalog")]
Catalog {
#[serde(rename = "cameraId")]
#[allow(dead_code)]
camera_id: String,
files: Vec<CameraFile>,
},
#[serde(rename = "file")]
File { path: String, name: String, size: u64 },
}
struct Inner {
devices: Vec<CameraDevice>,
files: Vec<CameraFile>,
pending: Vec<IncomingFile>,
tether: bool,
dir: String,
}
pub struct CameraState {
inner: Mutex<Inner>,
}
impl Default for CameraState {
fn default() -> Self {
Self {
inner: Mutex::new(Inner {
devices: Vec::new(),
files: Vec::new(),
pending: Vec::new(),
tether: true,
dir: String::new(),
}),
}
}
}
fn queue() -> &'static Mutex<Vec<String>> {
static Q: OnceLock<Mutex<Vec<String>>> = OnceLock::new();
Q.get_or_init(|| Mutex::new(Vec::new()))
}
impl CameraState {
fn drain(&self) {
let pending = match queue().lock() {
Ok(mut q) => std::mem::take(&mut *q),
Err(_) => return,
};
let Ok(mut inner) = self.inner.lock() else {
return;
};
for line in pending {
apply_event(&mut inner, &line);
}
}
/// `<ingest>/.usb`, created if needed. Hidden so the FTP folder scan leaves these files alone.
pub fn sync_dir(&self, ingest: &Path) {
let dir = ingest.join(".usb");
let _ = std::fs::create_dir_all(&dir);
let text = dir.to_string_lossy().into_owned();
let changed = self
.inner
.lock()
.map(|mut i| {
let changed = i.dir != text;
i.dir = text.clone();
changed
})
.unwrap_or(false);
if changed {
set_download_dir(&text);
}
}
pub fn status(&self) -> CameraStatus {
self.drain();
let inner = self.inner.lock().ok();
CameraStatus {
supported: supported(),
tether: inner.as_ref().is_none_or(|i| i.tether),
devices: inner.as_ref().map(|i| i.devices.clone()).unwrap_or_default(),
files: inner.map(|i| i.files.clone()).unwrap_or_default(),
}
}
pub fn take(&self) -> Vec<IncomingFile> {
self.drain();
self.inner
.lock()
.map(|mut i| std::mem::take(&mut i.pending))
.unwrap_or_default()
}
pub fn set_tether(&self, on: bool) {
if let Ok(mut inner) = self.inner.lock() {
inner.tether = on;
if !on {
inner.files.clear();
}
}
set_tether_native(on);
}
pub fn import(&self, names: &[String]) {
if names.is_empty() {
return;
}
let Ok(json) = serde_json::to_string(names) else {
return;
};
import_native(&json);
}
}
fn apply_event(inner: &mut Inner, line: &str) {
let Ok(event) = serde_json::from_str::<CameraEvent>(line) else {
return;
};
match event {
CameraEvent::Devices { devices } => inner.devices = devices,
CameraEvent::Catalog { camera_id: _, files } => inner.files = files,
CameraEvent::File { path, name, size } => {
if size > 0 && (crate::ftp::is_jpeg_name(&name) || crate::ftp::is_raw_name(&name)) {
inner.pending.push(IncomingFile::at(path, name, size));
}
}
}
}
#[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;
if json.is_null() {
return;
}
let Ok(text) = unsafe { CStr::from_ptr(json) }.to_str() else {
return;
};
if let Ok(mut q) = queue().lock() {
q.push(text.to_string());
}
}
#[cfg(target_os = "macos")]
unsafe extern "C" {
fn pr_camera_start(cb: unsafe extern "C" fn(*const std::ffi::c_char));
fn pr_camera_set_dir(dir: *const std::ffi::c_char);
fn pr_camera_set_tether(on: i32);
fn pr_camera_sync();
fn pr_camera_import(names_json: *const std::ffi::c_char);
fn pr_camera_refresh_catalog();
}
#[cfg(target_os = "macos")]
fn set_download_dir(dir: &str) {
let Ok(c) = std::ffi::CString::new(dir) else {
return;
};
unsafe { pr_camera_set_dir(c.as_ptr()) }
}
#[cfg(not(target_os = "macos"))]
fn set_download_dir(_dir: &str) {}
#[cfg(target_os = "macos")]
fn set_tether_native(on: bool) {
unsafe { pr_camera_set_tether(i32::from(on)) }
}
#[cfg(not(target_os = "macos"))]
fn set_tether_native(_on: bool) {}
#[cfg(target_os = "macos")]
fn sync_native() {
unsafe { pr_camera_sync() }
}
#[cfg(not(target_os = "macos"))]
fn sync_native() {}
#[cfg(target_os = "macos")]
fn import_native(names_json: &str) {
let Ok(c) = std::ffi::CString::new(names_json) else {
return;
};
unsafe { pr_camera_import(c.as_ptr()) }
}
#[cfg(not(target_os = "macos"))]
fn import_native(_names_json: &str) {}
#[cfg(target_os = "macos")]
fn refresh_catalog_native() {
unsafe { pr_camera_refresh_catalog() }
}
#[cfg(not(target_os = "macos"))]
fn refresh_catalog_native() {}
/// Starts the browser once. Safe to call at launch; callbacks only enqueue a string.
pub fn start(ftp: &FtpState) {
#[cfg(target_os = "macos")]
{
static STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
if STARTED.swap(true, std::sync::atomic::Ordering::SeqCst) {
return;
}
unsafe { pr_camera_start(on_camera_json) }
}
let dir = ftp.ingest_dir();
let _ = std::fs::create_dir_all(dir.join(".usb"));
set_download_dir(&dir.join(".usb").to_string_lossy());
}
#[tauri::command]
pub fn camera_status(cam: tauri::State<'_, CameraState>, ftp: tauri::State<'_, FtpState>) -> CameraStatus {
cam.sync_dir(&ftp.ingest_dir());
cam.status()
}
#[tauri::command]
pub fn camera_take(cam: tauri::State<'_, CameraState>) -> Vec<IncomingFile> {
cam.take()
}
#[tauri::command]
pub fn camera_tether(cam: tauri::State<'_, CameraState>, enabled: bool) -> CameraStatus {
cam.set_tether(enabled);
cam.status()
}
/// Sets the open camera's clock to this computer's clock.
#[tauri::command]
pub fn camera_sync(cam: tauri::State<'_, CameraState>) -> CameraStatus {
sync_native();
cam.status()
}
/// Downloads the named files from the open camera into the ingest folder (JPEG + RAW sidecars if listed).
#[tauri::command]
pub fn camera_import(cam: tauri::State<'_, CameraState>, names: Vec<String>) -> CameraStatus {
cam.import(&names);
cam.status()
}
/// Re-reads the card listing (after a big burst the list can lag).
#[tauri::command]
pub fn camera_refresh(cam: tauri::State<'_, CameraState>) -> CameraStatus {
refresh_catalog_native();
cam.status()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_chosen_shot_queues_the_jpeg_and_the_raw() {
let mut inner = Inner {
devices: Vec::new(),
files: Vec::new(),
pending: Vec::new(),
tether: true,
dir: String::new(),
};
apply_event(
&mut inner,
r#"{"kind":"devices","devices":[{"id":"abc","name":"Canon Digital Camera","vendorId":1193,"productId":13075,"state":"tethered","error":null,"catalogReady":true}]}"#,
);
apply_event(
&mut inner,
r#"{"kind":"catalog","cameraId":"abc","files":[{"name":"IMG_0001.JPG","size":10,"isNew":true,"imported":false},{"name":"IMG_0001.CR3","size":20,"isNew":true,"imported":false}]}"#,
);
apply_event(
&mut inner,
r#"{"kind":"file","path":"/ingest/.usb/IMG_0001.JPG","name":"IMG_0001.JPG","size":10}"#,
);
apply_event(
&mut inner,
r#"{"kind":"file","path":"/ingest/.usb/IMG_0001.CR3","name":"IMG_0001.CR3","size":20}"#,
);
assert_eq!(inner.devices.len(), 1);
assert!(inner.devices[0].catalog_ready);
assert_eq!(inner.files.len(), 2);
assert_eq!(inner.pending.len(), 2);
}
#[test]
fn an_unplugged_camera_clears_the_list() {
let mut inner = Inner {
devices: vec![CameraDevice {
id: "abc".into(),
name: "Canon".into(),
vendor_id: 1193,
product_id: 1,
state: "tethered".into(),
error: None,
clock: None,
clock_offset: None,
catalog_ready: true,
}],
files: vec![CameraFile {
name: "a.jpg".into(),
size: 1,
created_ms: None,
is_new: false,
imported: false,
}],
pending: Vec::new(),
tether: true,
dir: String::new(),
};
apply_event(&mut inner, r#"{"kind":"devices","devices":[]}"#);
apply_event(&mut inner, r#"{"kind":"catalog","cameraId":"abc","files":[]}"#);
assert!(inner.devices.is_empty());
assert!(inner.files.is_empty());
}
}
+568
View File
@@ -0,0 +1,568 @@
// USB still cameras speak PTP, so macOS never mounts them as a disk. Image Capture (and this file)
// talks to them through ImageCaptureCore: open a session, list what is on the card (and each new
// shot as it appears), and download only the files the photographer picks. Nothing is copied on its
// own — that is deliberate: a full card would flood the ingest folder.
// One process can hold the PTP session; if EOS Utility has it, opening fails and we try again.
#import <Foundation/Foundation.h>
#import <IOKit/IOKitLib.h>
#import <ImageCaptureCore/ImageCaptureCore.h>
typedef void (*pr_camera_cb)(const char *json);
static pr_camera_cb g_callback = NULL;
static NSString *g_dir = nil;
static BOOL g_tether = YES;
static void emit(NSDictionary *obj) {
if (!g_callback || !obj) return;
NSData *data = [NSJSONSerialization dataWithJSONObject:obj options:0 error:nil];
if (!data) return;
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (s) g_callback(s.UTF8String);
}
static BOOL is_still(ICCameraItem *item) {
if (![item isKindOfClass:[ICCameraFile class]]) return NO;
NSString *ext = item.name.pathExtension.lowercaseString ?: @"";
NSSet *exts = [NSSet setWithArray:@[
@"jpg", @"jpeg", @"cr2", @"cr3", @"nef", @"arw", @"raf", @"rw2", @"dng", @"orf", @"pef", @"srw", @"heic", @"hif"
]];
if ([exts containsObject:ext]) return YES;
NSString *uti = item.UTI.lowercaseString ?: @"";
if ([uti containsString:@"movie"] || [uti containsString:@"video"] || [uti containsString:@"audio"]) return NO;
return [uti containsString:@"image"] || [uti containsString:@"raw"];
}
@interface PRCam : NSObject
@property (retain) ICCameraDevice *device;
@property (copy) NSString *uuid;
@property (copy) NSString *name;
@property (assign) int vendor;
@property (assign) int product;
@property (copy) NSString *state; // opening | tethered | busy | idle
@property (copy) NSString *errorText;
@property (assign) BOOL catalogReady;
@property (assign) BOOL openRequested;
@property (retain) NSMutableSet<NSString *> *fetched;
@property (retain) NSMutableSet<NSString *> *seenAtConnect;
@property (retain) NSMutableDictionary<NSString *, ICCameraFile *> *filesByName;
/// synced | unsupported. Nil until the session is ready.
@property (copy) NSString *clock;
@property (assign) double clockOffset;
@property (assign) BOOL clockOffsetKnown;
@property (assign) BOOL clockDone;
@end
@implementation PRCam
@end
@interface PRCameraHub : NSObject <ICDeviceBrowserDelegate, ICCameraDeviceDelegate, ICCameraDeviceDownloadDelegate>
@property (retain) ICDeviceBrowser *browser;
@property (retain) NSMutableDictionary<NSString *, PRCam *> *cams;
@property (copy) NSString *dir;
@property (assign) BOOL tether;
@property (assign) BOOL retryScheduled;
@property (retain) NSArray<NSDictionary *> *locked;
@end
@implementation PRCameraHub
- (void)start {
self.cams = [NSMutableDictionary dictionary];
self.tether = g_tether;
self.dir = g_dir;
self.locked = @[];
self.browser = [ICDeviceBrowser new];
self.browser.delegate = self;
self.browser.browsedDeviceTypeMask = (ICDeviceTypeMask)(ICDeviceTypeMaskCamera | ICDeviceLocationTypeLocal);
[self.browser start];
// EOS Utility takes exclusive USB ownership, and then Image Capture lists nothing. Poll the
// registry so the camera still shows up as busy until that app lets go.
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(refreshLocked) userInfo:nil repeats:YES];
[self refreshLocked];
}
- (void)refreshLocked {
[self scanLocked];
[self publish];
}
- (void)scanLocked {
NSMutableArray *found = [NSMutableArray array];
io_iterator_t iter = 0;
kern_return_t kr = IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOUSBHostDevice"), &iter);
if (kr != KERN_SUCCESS) {
self.locked = @[];
return;
}
io_object_t dev;
while ((dev = IOIteratorNext(iter))) {
NSString *name = CFBridgingRelease(IORegistryEntryCreateCFProperty(dev, CFSTR("USB Product Name"), kCFAllocatorDefault, 0));
NSNumber *vendor = CFBridgingRelease(IORegistryEntryCreateCFProperty(dev, CFSTR("idVendor"), kCFAllocatorDefault, 0));
NSNumber *product = CFBridgingRelease(IORegistryEntryCreateCFProperty(dev, CFSTR("idProduct"), kCFAllocatorDefault, 0));
NSString *owner = CFBridgingRelease(IORegistryEntryCreateCFProperty(dev, CFSTR("UsbExclusiveOwner"), kCFAllocatorDefault, 0));
BOOL camera = [name.lowercaseString containsString:@"camera"];
BOOL known = NO;
for (PRCam *cam in self.cams.allValues) {
if (cam.vendor == vendor.intValue && cam.product == product.intValue) known = YES;
}
if (camera && !known) {
NSString *who = owner;
NSRange comma = [who rangeOfString:@", "];
if (comma.location != NSNotFound) who = [who substringFromIndex:comma.location + 2];
[found addObject:@{
@"id": [NSString stringWithFormat:@"usb-%d-%d", vendor.intValue, product.intValue],
@"name": name ?: @"Câmara",
@"vendorId": vendor ?: @0,
@"productId": product ?: @0,
@"state": who.length ? @"busy" : @"opening",
@"error": who.length ? who : [NSNull null],
@"catalogReady": @NO,
}];
}
IOObjectRelease(dev);
}
IOObjectRelease(iter);
self.locked = found;
}
- (BOOL)accepts:(ICDevice *)device {
if (![device isKindOfClass:[ICCameraDevice class]]) return NO;
if (device.transportType && ![device.transportType isEqualToString:ICTransportTypeUSB]) return NO;
NSString *kind = device.productKind.lowercaseString ?: @"";
if ([kind isEqualToString:@"iphone"] || [kind isEqualToString:@"ipad"] || [kind isEqualToString:@"ipod"]) return NO;
return YES;
}
- (PRCam *)camFor:(ICDevice *)device {
NSString *uuid = device.UUIDString ?: device.name ?: @"camera";
PRCam *cam = self.cams[uuid];
if (!cam) {
cam = [PRCam new];
cam.uuid = uuid;
cam.fetched = [NSMutableSet set];
cam.seenAtConnect = [NSMutableSet set];
cam.filesByName = [NSMutableDictionary dictionary];
cam.clockDone = NO;
cam.openRequested = NO;
self.cams[uuid] = cam;
}
cam.device = (ICCameraDevice *)device;
cam.name = device.name ?: @"Câmara";
cam.vendor = device.usbVendorID;
cam.product = device.usbProductID;
return cam;
}
- (void)publish {
NSMutableArray *list = [NSMutableArray array];
for (NSString *key in self.cams) {
PRCam *cam = self.cams[key];
[list addObject:@{
@"id": cam.uuid ?: @"",
@"name": cam.name ?: @"Câmara",
@"vendorId": @(cam.vendor),
@"productId": @(cam.product),
@"state": cam.state ?: @"opening",
@"error": cam.errorText ?: [NSNull null],
@"clock": cam.clock ?: [NSNull null],
@"clockOffset": cam.clockOffsetKnown ? @(cam.clockOffset) : [NSNull null],
@"catalogReady": @(cam.catalogReady),
}];
}
if (self.locked) [list addObjectsFromArray:self.locked];
emit(@{@"kind": @"devices", @"devices": list});
}
- (void)publishCatalog:(PRCam *)cam {
NSMutableArray *files = [NSMutableArray array];
for (NSString *name in cam.filesByName) {
ICCameraFile *file = cam.filesByName[name];
BOOL isNew = ![cam.seenAtConnect containsObject:name];
NSDate *created = file.creationDate;
[files addObject:@{
@"name": name,
@"size": @(file.fileSize),
@"createdMs": created ? @((long long)(created.timeIntervalSince1970 * 1000.0)) : [NSNull null],
@"isNew": @(isNew),
@"imported": @([cam.fetched containsObject:name]),
}];
}
[files sortUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
NSNumber *ca = a[@"createdMs"];
NSNumber *cb = b[@"createdMs"];
if ([ca isKindOfClass:[NSNumber class]] && [cb isKindOfClass:[NSNumber class]] && ![ca isEqual:[NSNull null]] && ![cb isEqual:[NSNull null]]) {
NSComparisonResult byDate = [cb compare:ca];
if (byDate != NSOrderedSame) return byDate;
}
return [((NSString *)a[@"name"]) compare:b[@"name"]];
}];
emit(@{@"kind": @"catalog", @"cameraId": cam.uuid ?: @"", @"files": files});
}
- (void)indexItem:(ICCameraItem *)item cam:(PRCam *)cam {
if (!is_still(item) || !item.name) return;
cam.filesByName[item.name] = (ICCameraFile *)item;
}
- (void)rebuildCatalog:(PRCam *)cam {
[cam.filesByName removeAllObjects];
for (ICCameraItem *item in cam.device.mediaFiles) [self indexItem:item cam:cam];
[self publishCatalog:cam];
}
- (void)syncClock:(PRCam *)cam {
if (cam.clockDone || !cam.device.hasOpenSession) return;
if (cam.device.capabilities.count == 0) return;
cam.clockDone = YES;
if (![cam.device.capabilities containsObject:ICCameraDeviceCanSyncClock]) {
cam.clock = @"unsupported";
cam.clockOffsetKnown = NO;
[self publish];
return;
}
cam.clockOffset = cam.device.timeOffset;
cam.clockOffsetKnown = YES;
[cam.device requestSyncClock];
cam.clock = @"synced";
[self publish];
}
/// Apple: do not send requests until deviceDidBecomeReady. Opening earlier hangs some Canon bodies.
- (void)requestOpenIfReady:(PRCam *)cam {
if (!self.tether) {
cam.state = @"idle";
cam.errorText = nil;
[self publish];
return;
}
if (cam.device.hasOpenSession) {
cam.state = @"tethered";
cam.errorText = nil;
[self publish];
return;
}
if (cam.openRequested) return;
cam.openRequested = YES;
cam.state = @"opening";
cam.errorText = nil;
cam.device.delegate = self;
[cam.device requestOpenSession];
[self publish];
}
- (void)scheduleRetry {
if (self.retryScheduled || !self.tether) return;
self.retryScheduled = YES;
__weak PRCameraHub *weak = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
PRCameraHub *hub = weak;
if (!hub) return;
hub.retryScheduled = NO;
if (!hub.tether) return;
for (NSString *key in hub.cams.allKeys) {
PRCam *cam = hub.cams[key];
if ([cam.state isEqualToString:@"busy"] || [cam.state isEqualToString:@"opening"]) {
cam.openRequested = NO;
[hub requestOpenIfReady:cam];
}
}
});
}
- (NSString *)uniqueName:(NSString *)original {
NSString *base = original.lastPathComponent ?: @"photo.JPG";
NSString *stem = base.stringByDeletingPathExtension;
NSString *ext = base.pathExtension;
NSString *candidate = base;
NSFileManager *fm = [NSFileManager defaultManager];
for (int n = 1; n < 1000; n++) {
if (![fm fileExistsAtPath:[self.dir stringByAppendingPathComponent:candidate]]) return candidate;
candidate = ext.length
? [NSString stringWithFormat:@"%@-%d.%@", stem, n, ext]
: [NSString stringWithFormat:@"%@-%d", stem, n];
}
return candidate;
}
- (void)download:(ICCameraFile *)file cam:(PRCam *)cam {
if (self.dir.length == 0 || !file.name) return;
if ([cam.fetched containsObject:file.name]) return;
NSFileManager *fm = [NSFileManager defaultManager];
[fm createDirectoryAtPath:self.dir withIntermediateDirectories:YES attributes:nil error:nil];
NSString *save = [self uniqueName:file.name];
NSURL *url = [NSURL fileURLWithPath:self.dir isDirectory:YES];
if (!url) return;
[cam.fetched addObject:file.name];
NSDictionary *options = @{
ICDownloadsDirectoryURL: url,
ICSaveAsFilename: save,
ICOverwrite: @NO,
ICDeleteAfterSuccessfulDownload: @NO,
};
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[cam.device requestDownloadFile:file
options:options
downloadDelegate:self
didDownloadSelector:@selector(didDownloadFile:error:options:contextInfo:)
contextInfo:(void *)CFBridgingRetain(cam.uuid)];
#pragma clang diagnostic pop
}
- (void)importNames:(NSArray<NSString *> *)names {
if (self.dir.length == 0 || names.count == 0) return;
for (NSString *key in self.cams) {
PRCam *cam = self.cams[key];
if (!cam.device.hasOpenSession) continue;
for (NSString *name in names) {
ICCameraFile *file = cam.filesByName[name];
if (file) [self download:file cam:cam];
}
[self publishCatalog:cam];
}
}
#pragma mark ICDeviceBrowserDelegate
- (void)deviceBrowser:(ICDeviceBrowser *)browser didAddDevice:(ICDevice *)device moreComing:(BOOL)moreComing {
(void)browser;
(void)moreComing;
if (![self accepts:device]) return;
PRCam *cam = [self camFor:device];
cam.catalogReady = NO;
cam.openRequested = NO;
cam.device.delegate = self;
cam.state = self.tether ? @"opening" : @"idle";
[self publish];
// Session opens from deviceDidBecomeReady — not here.
}
- (void)deviceBrowser:(ICDeviceBrowser *)browser didRemoveDevice:(ICDevice *)device moreGoing:(BOOL)moreGoing {
(void)browser;
(void)moreGoing;
NSString *uuid = device.UUIDString ?: device.name;
if (uuid) [self.cams removeObjectForKey:uuid];
[self publish];
emit(@{@"kind": @"catalog", @"cameraId": uuid ?: @"", @"files": @[]});
}
#pragma mark ICDeviceDelegate
- (void)device:(ICDevice *)device didOpenSessionWithError:(NSError *)error {
PRCam *cam = [self camFor:device];
cam.openRequested = NO;
if (error) {
cam.state = @"busy";
cam.errorText = error.localizedDescription;
[self publish];
[self scheduleRetry];
return;
}
cam.state = @"tethered";
cam.errorText = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[cam.device requestEnableTethering];
#pragma clang diagnostic pop
[self syncClock:cam];
[self publish];
}
- (void)device:(ICDevice *)device didCloseSessionWithError:(NSError *)error {
(void)error;
PRCam *cam = self.cams[device.UUIDString ?: @""];
if (!cam) return;
cam.openRequested = NO;
cam.catalogReady = NO;
if (self.tether) {
cam.state = @"busy";
[self scheduleRetry];
} else {
cam.state = @"idle";
}
[self publish];
}
- (void)didRemoveDevice:(ICDevice *)device {
[self deviceBrowser:self.browser didRemoveDevice:device moreGoing:NO];
}
- (void)deviceDidBecomeReady:(ICDevice *)device {
PRCam *cam = [self camFor:device];
[self requestOpenIfReady:cam];
[self syncClock:cam];
[self publish];
}
- (void)deviceDidBecomeReadyWithCompleteContentCatalog:(ICCameraDevice *)device {
PRCam *cam = [self camFor:device];
// Snapshot what was already on the card so the UI can mark later shots as "new".
[cam.seenAtConnect removeAllObjects];
for (ICCameraItem *item in cam.device.mediaFiles) {
if (item.name && is_still(item)) [cam.seenAtConnect addObject:item.name];
}
cam.catalogReady = YES;
if ([cam.state isEqualToString:@"opening"]) cam.state = @"tethered";
cam.errorText = nil;
[self rebuildCatalog:cam];
[self syncClock:cam];
[self publish];
}
- (void)cameraDevice:(ICCameraDevice *)camera didAddItems:(NSArray<ICCameraItem *> *)items {
PRCam *cam = [self camFor:camera];
// List only — never auto-download. The photographer picks what to pull.
for (ICCameraItem *item in items) [self indexItem:item cam:cam];
[self publishCatalog:cam];
}
- (void)cameraDevice:(ICCameraDevice *)camera didRemoveItems:(NSArray<ICCameraItem *> *)items {
PRCam *cam = [self camFor:camera];
for (ICCameraItem *item in items) {
if (item.name) [cam.filesByName removeObjectForKey:item.name];
}
[self publishCatalog:cam];
}
- (void)cameraDevice:(ICCameraDevice *)camera didReceiveThumbnail:(CGImageRef)thumbnail forItem:(ICCameraItem *)item error:(NSError *)error {
(void)camera;
(void)thumbnail;
(void)item;
(void)error;
}
- (void)cameraDevice:(ICCameraDevice *)camera didReceiveMetadata:(NSDictionary *)metadata forItem:(ICCameraItem *)item error:(NSError *)error {
(void)camera;
(void)metadata;
(void)item;
(void)error;
}
- (void)cameraDevice:(ICCameraDevice *)camera didRenameItems:(NSArray<ICCameraItem *> *)items {
(void)camera;
(void)items;
}
- (void)cameraDeviceDidChangeCapability:(ICCameraDevice *)camera {
(void)camera;
}
- (void)cameraDevice:(ICCameraDevice *)camera didReceivePTPEvent:(NSData *)eventData {
(void)camera;
(void)eventData;
}
- (void)cameraDeviceDidRemoveAccessRestriction:(ICDevice *)device {
(void)device;
}
- (void)cameraDeviceDidEnableAccessRestriction:(ICDevice *)device {
(void)device;
}
- (void)didDownloadFile:(ICCameraFile *)file error:(NSError *)error options:(NSDictionary *)options contextInfo:(void *)contextInfo {
NSString *camId = contextInfo ? CFBridgingRelease(contextInfo) : nil;
if (error || self.dir.length == 0) {
if (camId && file.name) {
PRCam *cam = self.cams[camId];
[cam.fetched removeObject:file.name];
[self publishCatalog:cam];
}
return;
}
NSString *saved = options[ICSavedFilename];
if (![saved isKindOfClass:[NSString class]] || saved.length == 0) saved = file.name;
if (saved.length == 0) return;
NSString *path = [self.dir stringByAppendingPathComponent:saved];
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
unsigned long long size = [attrs fileSize];
if (size == 0) return;
emit(@{@"kind": @"file", @"path": path, @"name": saved, @"size": @(size)});
if (camId) {
PRCam *cam = self.cams[camId];
if (cam) [self publishCatalog:cam];
}
}
@end
static PRCameraHub *g_hub = nil;
static void on_main(void (^block)(void)) {
if ([NSThread isMainThread]) block();
else dispatch_async(dispatch_get_main_queue(), block);
}
void pr_camera_start(pr_camera_cb cb) {
g_callback = cb;
on_main(^{
if (g_hub) return;
g_hub = [PRCameraHub new];
[g_hub start];
});
}
void pr_camera_set_dir(const char *dir) {
NSString *path = dir ? [NSString stringWithUTF8String:dir] : @"";
on_main(^{
g_dir = [path copy];
g_hub.dir = g_dir;
});
}
void pr_camera_sync(void) {
on_main(^{
if (!g_hub) return;
for (NSString *key in g_hub.cams.allKeys) {
PRCam *cam = g_hub.cams[key];
cam.clockDone = NO;
[g_hub syncClock:cam];
}
});
}
void pr_camera_set_tether(int on) {
on_main(^{
g_tether = on ? YES : NO;
if (!g_hub) return;
g_hub.tether = g_tether;
for (NSString *key in g_hub.cams.allKeys) {
PRCam *cam = g_hub.cams[key];
if (g_hub.tether) {
cam.openRequested = NO;
[g_hub requestOpenIfReady:cam];
} else if (cam.device.hasOpenSession) {
cam.state = @"idle";
[cam.device requestCloseSession];
} else {
cam.state = @"idle";
}
}
[g_hub publish];
});
}
void pr_camera_import(const char *names_json) {
if (!names_json) return;
NSString *text = [NSString stringWithUTF8String:names_json];
NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
if (!data) return;
id parsed = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if (![parsed isKindOfClass:[NSArray class]]) return;
NSArray *names = (NSArray *)parsed;
on_main(^{
[g_hub importNames:names];
});
}
void pr_camera_refresh_catalog(void) {
on_main(^{
if (!g_hub) return;
for (NSString *key in g_hub.cams.allKeys) {
PRCam *cam = g_hub.cams[key];
if (cam.catalogReady) [g_hub rebuildCatalog:cam];
}
});
}
+152 -2
View File
@@ -39,6 +39,9 @@ pub struct FtpUser {
/// Switched off: the login stays saved but the server refuses it (one per camera body, like other FTP servers).
#[serde(default = "enabled_by_default")]
pub enabled: bool,
/// What you call this body ("R3", "1DX"). Empty: the login name is the label.
#[serde(default)]
pub label: String,
}
fn enabled_by_default() -> bool {
@@ -69,6 +72,7 @@ impl Default for FtpSettings {
name: "photoreport".into(),
password: new_password(),
enabled: true,
label: String::new(),
}],
ingest: "~/Desktop/ingest".into(),
work_folder: "~/Desktop/{year}/{date} - {event}".into(),
@@ -116,6 +120,17 @@ pub struct IncomingFile {
modified_ms: u64,
}
impl IncomingFile {
pub(crate) fn at(path: String, name: String, size: u64) -> Self {
Self {
path,
name,
size,
modified_ms: now_ms(),
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FtpStatus {
@@ -181,6 +196,52 @@ fn expand(p: &str) -> PathBuf {
}
}
const RAW_EXT: &[&str] = &[
"cr2", "cr3", "nef", "arw", "raf", "rw2", "dng", "orf", "pef", "srw", "heic", "hif",
];
/// RAW (and HEIC) files sitting next to a JPEG with the same stem.
fn raw_sidecars(jpeg: &Path) -> Vec<PathBuf> {
let Some(dir) = jpeg.parent() else {
return Vec::new();
};
let Some(stem) = jpeg.file_stem().and_then(|s| s.to_str()) else {
return Vec::new();
};
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
let mut out = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if path == jpeg {
continue;
}
let same = path
.file_stem()
.and_then(|s| s.to_str())
.is_some_and(|s| s.eq_ignore_ascii_case(stem));
if same && is_raw(&path) {
out.push(path);
}
}
out
}
pub(crate) fn is_jpeg_name(name: &str) -> bool {
is_photo(Path::new(name))
}
pub(crate) fn is_raw_name(name: &str) -> bool {
is_raw(Path::new(name))
}
fn is_raw(path: &Path) -> bool {
path.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| RAW_EXT.contains(&e.to_ascii_lowercase().as_str()))
}
fn is_photo(path: &Path) -> bool {
matches!(
path.extension()
@@ -457,7 +518,7 @@ impl FtpState {
Ok(())
}
fn ingest_dir(&self) -> PathBuf {
pub(crate) fn ingest_dir(&self) -> PathBuf {
expand(&self.settings().ingest)
}
@@ -477,6 +538,17 @@ impl FtpState {
}
}
/// JPEG or the RAW beside it, still inside the ingest tree. `ftp_read` stays JPEG-only.
fn inside_kept(&self, path: &str) -> Result<PathBuf, String> {
let root = self.ingest_dir().canonicalize().map_err(|e| e.to_string())?;
let p = Path::new(path).canonicalize().map_err(|_| "not_found".to_string())?;
if p.starts_with(&root) && (is_photo(&p) || is_raw(&p)) {
Ok(p)
} else {
Err("forbidden".into())
}
}
pub fn status(&self) -> FtpStatus {
let settings = self.settings();
let waiting = {
@@ -610,8 +682,17 @@ impl FtpState {
}
/// The server has the photo: move the original into the event's work folder (kept, never deleted).
/// A tethered RAW next to the JPEG (or a RAW-only shot) is filed the same way.
pub fn sent(&self, path: &str, event: &str, date: &str) -> Result<String, String> {
let p = self.finished_jpeg(path)?;
let file_name = Path::new(path)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("");
let p = if is_raw_name(file_name) {
self.inside_kept(path)?
} else {
self.finished_jpeg(path)?
};
let dir = work_folder(&self.settings().work_folder, event, date);
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let name = p
@@ -629,7 +710,29 @@ impl FtpState {
target = dir.join(format!("{stem}-{n}{ext}"));
n += 1;
}
let sidecars = if is_photo(&p) {
raw_sidecars(&p)
} else {
Vec::new()
};
let paired = target
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| stem.clone());
move_file(&p, &target).map_err(|e| e.to_string())?;
for raw in sidecars {
let raw_ext = raw
.extension()
.map(|e| e.to_string_lossy().into_owned())
.unwrap_or_default();
let mut raw_target = dir.join(format!("{paired}.{raw_ext}"));
let mut k = 1;
while raw_target.exists() {
raw_target = dir.join(format!("{paired}-{k}.{raw_ext}"));
k += 1;
}
let _ = move_file(&raw, &raw_target);
}
self.taken.lock().unwrap().remove(path);
Ok(target.to_string_lossy().into_owned())
}
@@ -951,6 +1054,47 @@ mod tests {
);
}
/// Tether saves the RAW next to the JPEG; filing the JPEG takes the RAW into the work folder.
#[test]
fn sent_keeps_the_raw_with_the_jpeg() {
let dir = std::env::temp_dir().join(format!("pr-raw-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let ingest = dir.join("ingest").join(".usb");
std::fs::create_dir_all(&ingest).unwrap();
// Minimal JPEG with SOI/EOI so finished_jpeg accepts it.
std::fs::write(ingest.join("IMG_0001.JPG"), [0xFFu8, 0xD8, 0xFF, 0xD9]).unwrap();
std::fs::write(ingest.join("IMG_0001.CR3"), b"raw").unwrap();
let state = FtpState {
config_path: Some(dir.join("ftp.json")),
..Default::default()
};
state
.save(FtpSettings {
port: 2121,
users: vec![FtpUser {
name: "1dx".into(),
password: "1dx".into(),
enabled: true,
label: String::new(),
}],
ingest: dir.join("ingest").to_string_lossy().into_owned(),
work_folder: dir.join("work/{date} - {event}").to_string_lossy().into_owned(),
auto_start: false,
upload_originals: false,
})
.unwrap();
let jpeg = ingest.join("IMG_0001.JPG");
let moved = state
.sent(jpeg.to_str().unwrap(), "POR x SUI", "2026-11-04")
.unwrap();
let moved = PathBuf::from(&moved);
assert!(moved.is_file());
assert!(moved.with_extension("CR3").is_file());
assert!(!jpeg.exists());
assert!(!ingest.join("IMG_0001.CR3").exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn settings_are_checked() {
let mut s = FtpSettings::default();
@@ -960,11 +1104,13 @@ mod tests {
name: "1dx".into(),
password: "1dx".into(),
enabled: true,
label: String::new(),
},
FtpUser {
name: "R3".into(),
password: "r3".into(),
enabled: false,
label: "R3".into(),
},
];
assert!(s.check().is_ok());
@@ -974,6 +1120,7 @@ mod tests {
// Settings saved by an older app have no "enabled": the login is on.
let old: FtpUser = serde_json::from_str(r#"{"name":"r1","password":"r1"}"#).unwrap();
assert!(old.enabled);
assert!(old.label.is_empty());
s.port = 21;
assert_eq!(s.check().unwrap_err(), "port_low");
s.port = 2121;
@@ -1007,11 +1154,13 @@ mod tests {
name: "1dx".into(),
password: "1dx".into(),
enabled: true,
label: String::new(),
},
FtpUser {
name: "R3".into(),
password: "r3".into(),
enabled: false,
label: "R3".into(),
},
],
ingest: dir.join("ingest").to_string_lossy().into_owned(),
@@ -1128,6 +1277,7 @@ mod tests {
name: "1dx".into(),
password: "1dx".into(),
enabled: true,
label: String::new(),
}],
ingest: dir.join("ingest").to_string_lossy().into_owned(),
work_folder: dir
+14 -4
View File
@@ -1,12 +1,14 @@
//! Native shell around apps/app. The web app calls these commands through `@tauri-apps/api` when it runs
//! inside the desktop app (see apps/app/src/platform.ts). The refresh token never touches disk in clear:
//! it lives in the OS keychain (macOS Keychain, Windows Credential Manager, Secret Service on Linux).
//! `ftp` runs the local FTP server cameras send photos to; `local` finds originals on disk for the editor; `catalog`
//! indexes the photographer's own folders for it; `deliver` saves deliveries to folders here and imports upload
//! destinations from Photo Mechanic and FileZilla; `updater` keeps the shell itself current.
//! `ftp` runs the local FTP server cameras send photos to; `camera` receives tethered shots from a body
//! plugged in by USB; `local` finds originals on disk for the editor; `catalog` indexes the photographer's
//! own folders for it; `deliver` saves deliveries to folders here and imports upload destinations from
//! Photo Mechanic and FileZilla; `updater` keeps the shell itself current.
mod accel;
mod browse;
mod camera;
mod card;
mod catalog;
mod deliver;
@@ -85,6 +87,7 @@ pub fn run() {
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.manage(ftp::FtpState::default())
.manage(camera::CameraState::default())
.manage(local::LocalIndex::default())
.manage(catalog::Catalog::default())
.manage(browse::OpenFolders::default())
@@ -95,6 +98,7 @@ pub fn run() {
.setup(|app| {
use tauri::Manager;
ftp::auto_start(&app.state::<ftp::FtpState>());
camera::start(&app.state::<ftp::FtpState>());
// `tauri dev` serves the dev server: nothing to update.
if !cfg!(debug_assertions) {
ui::watch(app.handle().clone());
@@ -177,7 +181,13 @@ pub fn run() {
deliver::delivery_folders,
deliver::delivery_folder_pick,
deliver::delivery_write,
deliver::import_upload_profiles
deliver::import_upload_profiles,
camera::camera_status,
camera::camera_take,
camera::camera_tether,
camera::camera_sync,
camera::camera_import,
camera::camera_refresh
])
.run(context);
if let Err(err) = result {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "PhotoReport",
"version": "0.3.24",
"version": "0.3.26",
"identifier": "pt.photoreport.desktop",
"build": {
"devUrl": "http://localhost:5173",
+16 -17
View File
@@ -2,6 +2,7 @@
import { useEffect, useMemo, useState } from "react";
import { asJpeg } from "../../../lib/asJpeg";
import { SelfieCamera } from "../../../lib/SelfieCamera";
import { day, download, Forbidden, LEVEL, Unauthorised, type FindByPhotoResult, type Level, type Me, type PhotoFace } from "./api";
import { Lightbox } from "./Lightbox";
import { Icon } from "./parts";
@@ -35,6 +36,7 @@ export function FindByPhoto({
const [result, setResult] = useState<FindByPhotoResult | null>(null);
const [only, setOnly] = useState<Level | null>(null);
const [index, setIndex] = useState<number | null>(null);
const [camera, setCamera] = useState(false);
// Start the face engine while the editor is on this page, so the first upload does not wait on model load.
useEffect(() => {
@@ -121,28 +123,15 @@ export function FindByPhoto({
Carrega uma fotografia com a cara bem visível (retrato, recorte de imprensa). Mostramos as fotos do arquivo em que essa pessoa aparece. A foto só serve para esta pesquisa: não fica guardada.
</p>
<div style={{ display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center" }}>
<label className="arq-btn" style={{ cursor: busy ? "wait" : "pointer" }} aria-busy={busy}>
<button type="button" className="arq-btn" disabled={busy} aria-busy={busy} onClick={() => setCamera(true)}>
{busy ? "A procurar…" : "Tirar foto"}
<input
type="file"
accept="image/*"
capture="user"
// Visible hit target is the label; keep the control out of layout without display:none (iOS skips those).
style={{ position: "absolute", width: 1, height: 1, opacity: 0, overflow: "hidden" }}
disabled={busy}
onChange={(e) => {
const f = e.target.files?.[0];
if (f) void search(f);
e.target.value = "";
}}
/>
</label>
<label className="arq-link" style={{ cursor: busy ? "wait" : "pointer" }}>
</button>
<label className="arq-link" style={{ cursor: busy ? "wait" : "pointer", position: "relative" }}>
{result ? "Outra da galeria" : "Escolher da galeria"}
<input
type="file"
accept="image/*,.heic,.heif"
style={{ position: "absolute", width: 1, height: 1, opacity: 0, overflow: "hidden" }}
style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0, cursor: "pointer" }}
disabled={busy}
onChange={(e) => {
const f = e.target.files?.[0];
@@ -232,6 +221,16 @@ export function FindByPhoto({
</>
)}
{camera && (
<SelfieCamera
onCancel={() => setCamera(false)}
onShot={(shot) => {
setCamera(false);
void search(shot);
}}
/>
)}
{index !== null && photos[index] && (
<Lightbox
photos={photos}
@@ -5,6 +5,7 @@ import Link from "next/link";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { asJpeg } from "../../../lib/asJpeg";
import { SelfieCamera } from "../../../lib/SelfieCamera";
import { addToCart, useCart } from "../../../lib/cart";
import { eur, shotAt, sizeLabel } from "../../../lib/format";
import { useProofing } from "../../../lib/proofing";
@@ -484,6 +485,7 @@ function BundleBar({ gallery, products, cartGallery }: { gallery: PublicGallery;
*/
function FindMe({ slug, token, onFound, onClose }: { slug: string; token: string | null; onFound: (photoIds: string[], moreFaces: boolean) => void; onClose: () => void }) {
const [state, setState] = useState<{ busy: boolean; error: string | null; file: File | null; faces: number; face: number }>({ busy: false, error: null, file: null, faces: 0, face: 0 });
const [camera, setCamera] = useState(false);
const search = async (picked: File, face = 0) => {
setState((s) => ({ ...s, busy: true, error: null, face }));
try {
@@ -517,27 +519,15 @@ function FindMe({ slug, token, onFound, onClose }: { slug: string; token: string
<p>Envia uma foto tua (ou de quem procuras) com a cara bem visível. Mostramos as fotos desta galeria em que essa pessoa aparece.</p>
<p className="meta">A foto só serve para esta pesquisa: não fica guardada.</p>
<div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginTop: 12, alignItems: "center" }}>
<label className="button" style={{ display: "inline-block", cursor: "pointer" }} aria-busy={state.busy}>
<button type="button" className="button" disabled={state.busy} aria-busy={state.busy} onClick={() => setCamera(true)}>
{state.busy ? "A procurar…" : "Tirar foto"}
<input
type="file"
accept="image/*"
capture="user"
style={{ position: "absolute", width: 1, height: 1, opacity: 0, overflow: "hidden" }}
disabled={state.busy}
onChange={(e) => {
const f = e.target.files?.[0];
if (f) void search(f);
e.target.value = "";
}}
/>
</label>
<label style={{ cursor: "pointer", color: "var(--accent)", textDecoration: "underline" }}>
</button>
<label style={{ cursor: "pointer", color: "var(--accent)", textDecoration: "underline", position: "relative" }}>
Escolher da galeria
<input
type="file"
accept="image/*,.heic,.heif"
style={{ position: "absolute", width: 1, height: 1, opacity: 0, overflow: "hidden" }}
style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0, cursor: "pointer" }}
disabled={state.busy}
onChange={(e) => {
const f = e.target.files?.[0];
@@ -566,6 +556,15 @@ function FindMe({ slug, token, onFound, onClose }: { slug: string; token: string
</button>
</p>
</div>
{camera && (
<SelfieCamera
onCancel={() => setCamera(false)}
onShot={(shot) => {
setCamera(false);
void search(shot);
}}
/>
)}
</div>
);
}
+149
View File
@@ -0,0 +1,149 @@
"use client";
import { useEffect, useRef, useState, type CSSProperties } from "react";
/**
* Front-camera capture in the page (getUserMedia → canvas JPEG). Prefer this over
* `<input capture>` on iPhone: the system picker often returns HEIC the face API cannot read,
* and a hidden file input inside a label is unreliable on iOS Safari.
*/
export function SelfieCamera({ onShot, onCancel }: { onShot: (file: File) => void; onCancel: () => void }) {
const video = useRef<HTMLVideoElement>(null);
const [problem, setProblem] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
let stream: MediaStream | null = null;
let cancelled = false;
const start = async () => {
if (!navigator.mediaDevices?.getUserMedia) {
setProblem("Este browser não dá acesso à câmara. Usa «Escolher da galeria» ou abre no Safari/Chrome.");
return;
}
try {
stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: { ideal: "user" }, width: { ideal: 1280 }, height: { ideal: 960 } },
audio: false,
});
if (cancelled) {
stream.getTracks().forEach((t) => t.stop());
return;
}
const el = video.current;
if (el) {
el.srcObject = stream;
await el.play().catch(() => undefined);
}
} catch {
if (!cancelled) setProblem("Não foi possível abrir a câmara. Autoriza a câmara neste site e tenta outra vez.");
}
};
void start();
return () => {
cancelled = true;
stream?.getTracks().forEach((t) => t.stop());
};
}, []);
const shoot = () => {
const v = video.current;
if (!v || !v.videoWidth || busy) return;
setBusy(true);
const canvas = document.createElement("canvas");
canvas.width = v.videoWidth;
canvas.height = v.videoHeight;
const ctx = canvas.getContext("2d");
if (!ctx) {
setProblem("Não foi possível capturar a imagem.");
setBusy(false);
return;
}
ctx.drawImage(v, 0, 0);
canvas.toBlob(
(blob) => {
setBusy(false);
if (!blob) {
setProblem("Não foi possível capturar a imagem.");
return;
}
onShot(new File([blob], "foto.jpg", { type: "image/jpeg" }));
},
"image/jpeg",
0.92,
);
};
return (
<div
role="dialog"
aria-modal="true"
aria-label="Tirar foto"
style={{
position: "fixed",
inset: 0,
zIndex: 80,
background: "rgba(8, 8, 9, 0.92)",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: 16,
padding: 20,
boxSizing: "border-box",
}}
>
{problem ? (
<>
<p role="alert" style={{ color: "#fff", textAlign: "center", maxWidth: 360, margin: 0 }}>
{problem}
</p>
<button type="button" onClick={onCancel} style={btnGhost}>
Voltar
</button>
</>
) : (
<>
<video
ref={video}
playsInline
muted
autoPlay
style={{
maxWidth: "100%",
maxHeight: "70vh",
borderRadius: 12,
transform: "scaleX(-1)",
background: "#000",
}}
/>
<div style={{ display: "flex", gap: 12, flexWrap: "wrap", justifyContent: "center" }}>
<button type="button" onClick={shoot} disabled={busy} style={btnPrimary}>
{busy ? "A capturar…" : "Capturar"}
</button>
<button type="button" onClick={onCancel} disabled={busy} style={btnGhost}>
Cancelar
</button>
</div>
</>
)}
</div>
);
}
const btnPrimary: CSSProperties = {
padding: "12px 22px",
fontSize: 16,
fontWeight: 600,
border: 0,
borderRadius: 8,
background: "#fff",
color: "#111",
cursor: "pointer",
};
const btnGhost: CSSProperties = {
...btnPrimary,
background: "transparent",
color: "#fff",
border: "1px solid rgba(255,255,255,0.45)",
};
+32 -7
View File
@@ -7,12 +7,8 @@ const JPEG_MAX_SIDE = 1600;
export async function asJpeg(file: File): Promise<File> {
const already = /^image\/(jpeg|jpg|png|webp)$/i.test(file.type);
if (already && file.size <= 3 * 1024 * 1024) return file;
let bitmap: ImageBitmap;
try {
bitmap = await createImageBitmap(file);
} catch {
throw new Error("convert_failed");
}
const bitmap = await decode(file);
try {
const scale = Math.min(1, JPEG_MAX_SIDE / Math.max(bitmap.width, bitmap.height));
const w = Math.max(1, Math.round(bitmap.width * scale));
@@ -22,7 +18,7 @@ export async function asJpeg(file: File): Promise<File> {
canvas.height = h;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("convert_failed");
ctx.drawImage(bitmap, 0, 0, w, h);
ctx.drawImage(bitmap.source, 0, 0, w, h);
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.92));
if (!blob) throw new Error("convert_failed");
return new File([blob], "foto.jpg", { type: "image/jpeg" });
@@ -30,3 +26,32 @@ export async function asJpeg(file: File): Promise<File> {
bitmap.close();
}
}
type Decoded = { source: CanvasImageSource; width: number; height: number; close: () => void };
async function decode(file: File): Promise<Decoded> {
try {
const bitmap = await createImageBitmap(file);
return { source: bitmap, width: bitmap.width, height: bitmap.height, close: () => bitmap.close() };
} catch {
// Safari sometimes cannot createImageBitmap(HEIC) even when <img> can paint it.
}
const url = URL.createObjectURL(file);
try {
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
const el = new Image();
el.onload = () => resolve(el);
el.onerror = () => reject(new Error("convert_failed"));
el.src = url;
});
return {
source: img,
width: img.naturalWidth || img.width,
height: img.naturalHeight || img.height,
close: () => URL.revokeObjectURL(url),
};
} catch (err) {
URL.revokeObjectURL(url);
throw err instanceof Error ? err : new Error("convert_failed");
}
}
+3 -1
View File
@@ -526,7 +526,9 @@ run on the `next` containers (the phase gate).
/v1/orgs/:orgId/faces/lookup`; on the sites, "Encontra-te" finds a visitor's face in one gallery, `POST
/v1/public/galleries/:slug/find`; in the archive, editors on the cloud with the option on search the whole
archive they can see, `POST /v1/archive/:source/find`). Only with biometrics on; the search photo is read in
memory and never kept. The API runs its own face engine for this, started on the first search and stopped
memory and never kept. On phones, "Tirar foto" uses the front camera in the page (`getUserMedia` → JPEG),
not `<input capture>` (iOS often hands HEIC the API cannot read). Gallery picks still convert to JPEG in
the browser before upload. The API runs its own face engine for this, started on the first search and stopped
after 10 idle minutes.
6. Cutover: final import, redirects, old projects read-only, then switched off.
+28 -6
View File
@@ -4,14 +4,30 @@
// node infra/desktop/update-manifest.mjs <bundle dir> <platform> <version> [notes]
// <platform>: darwin-universal, darwin-aarch64, darwin-x86_64, windows-x86_64 or linux-x86_64.
// Attach to the `desktop-v<version>` release: the installer it names, and the manifest.
import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { basename, join } from "node:path";
import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { basename, dirname, join } from "node:path";
const [dir, platform, version, notes] = process.argv.slice(2);
if (!dir || !platform || !version) {
const [dir, platform, versionArg, notes] = process.argv.slice(2);
if (!dir || !platform || !versionArg) {
console.error("usage: update-manifest.mjs <bundle dir> <platform> <version> [notes]");
process.exit(2);
}
// Tag name (desktop-vX.Y.Z) must match the version baked into the binary / signature. A retagged
// wrong commit otherwise announces X.Y.Z while the signature still says the previous one.
const version = versionArg.replace(/^desktop-v|^v/, "");
let confDir = dir;
while (confDir !== dirname(confDir)) {
const confPath = join(confDir, "tauri.conf.json");
if (existsSync(confPath)) {
const conf = JSON.parse(readFileSync(confPath, "utf8"));
if (conf.version && conf.version !== version) {
console.error(`manifest version ${version} != tauri.conf.json ${conf.version}: refuse to publish a mismatched update`);
process.exit(1);
}
break;
}
confDir = dirname(confDir);
}
/** Every file below `root`. */
function files(root) {
@@ -29,10 +45,16 @@ if (!installer) {
console.error(`No signed installer under ${dir}: build with TAURI_SIGNING_PRIVATE_KEY set and bundle.createUpdaterArtifacts on.`);
process.exit(1);
}
const signature = readFileSync(`${installer}.sig`, "utf8").trim();
const signed = [...signature.matchAll(/version:([0-9]+\.[0-9]+\.[0-9]+(?:[-.+][\w.-]+)?)/g)].map((m) => m[1]).pop();
if (signed && signed !== version) {
console.error(`signature version ${signed} != tag version ${version}: refuse to publish a mismatched update`);
process.exit(1);
}
const manifest = {
version: version.replace(/^desktop-v|^v/, ""),
version,
file: basename(installer),
signature: readFileSync(`${installer}.sig`, "utf8").trim(),
signature,
pub_date: new Date().toISOString(),
...(notes && { notes }),
};