Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2fc1f73254 | ||
|
|
fa14bf91f5 | ||
|
|
db84533632 | ||
|
|
02a1440d66 | ||
|
|
7ac4c67176 | ||
|
|
9123d97918 | ||
|
|
3a0d3877f3 | ||
|
|
da7296af99 | ||
|
|
8a8218c6b3 | ||
|
|
34e8c27036 |
No files matched your search
@@ -9,7 +9,8 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16
|
||||
# Faces need pgvector (the migrations create the extension).
|
||||
image: pgvector/pgvector:pg16
|
||||
env:
|
||||
POSTGRES_USER: photoreport
|
||||
POSTGRES_PASSWORD: photoreport
|
||||
|
||||
@@ -46,7 +46,8 @@ const encodePath = (p: string) => p.split("/").map(encodeURIComponent).join("/")
|
||||
export async function startLogin(baseUrl: string, fetchImpl: typeof fetch = fetch, appName = "PhotoReport Arquivo"): Promise<LoginStart> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchImpl(`${cleanBase(baseUrl)}/index.php/login/v2`, { method: "POST", headers: { "user-agent": appName, accept: "application/json" } });
|
||||
// A cloud that does not answer is said at once, not after the proxy gives up.
|
||||
res = await fetchImpl(`${cleanBase(baseUrl)}/index.php/login/v2`, { method: "POST", headers: { "user-agent": appName, accept: "application/json" }, signal: AbortSignal.timeout(15_000) });
|
||||
} catch (err) {
|
||||
throw new NextcloudError(`network error: ${(err as Error).message}`, 0);
|
||||
}
|
||||
|
||||
@@ -381,17 +381,40 @@ export async function registerArchiveViewerRoutes(
|
||||
* Leixões SC"), and the known team's official name when exactly one fits ("SCP", "Sporting" → "Sporting CP").
|
||||
* Each with the names its galleries use, so filtering by it finds them all.
|
||||
*/
|
||||
/**
|
||||
* Each source's folder team names and the known team they are (`canonicalTeam` compares a name with every known
|
||||
* team: thousands of games times every team blocked the API for minutes). One answer per name, kept for a while,
|
||||
* shared by every viewer of the source.
|
||||
*/
|
||||
const canonicalNames = new Map<string, { at: number; known: Promise<{ name: string; abbreviation: string | null; slug: string }[]>; names: Map<string, string> }>();
|
||||
const CANONICAL_TTL_MS = 6 * 3600_000;
|
||||
const teamGroups = async (sourceId: string, games: Iterable<{ home: string; away: string }>): Promise<Map<string, { names: Set<string>; galleries: number }>> => {
|
||||
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { look: true, baseUrl: true } });
|
||||
const liga = source?.look === "liga" || /liga/i.test(source?.baseUrl ?? "");
|
||||
const known = await db.sportsTeam.findMany({ where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } }, select: { name: true, abbreviation: true, slug: true } });
|
||||
let memo = canonicalNames.get(sourceId);
|
||||
if (!memo || Date.now() - memo.at > CANONICAL_TTL_MS) {
|
||||
const known = (async () => {
|
||||
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { look: true, baseUrl: true } });
|
||||
const liga = source?.look === "liga" || /liga/i.test(source?.baseUrl ?? "");
|
||||
return db.sportsTeam.findMany({ where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } }, select: { name: true, abbreviation: true, slug: true } });
|
||||
})();
|
||||
known.catch(() => canonicalNames.delete(sourceId));
|
||||
memo = { at: Date.now(), known, names: new Map() };
|
||||
canonicalNames.set(sourceId, memo);
|
||||
}
|
||||
const known = await memo.known;
|
||||
const out = new Map<string, { names: Set<string>; galleries: number }>();
|
||||
const byKey = new Map<string, string>();
|
||||
const fold = (x: string) => x.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
|
||||
let fresh = 0;
|
||||
for (const g of games)
|
||||
for (const raw of [g.home, g.away]) {
|
||||
if (!raw) continue;
|
||||
const name = canonicalTeam(raw, known);
|
||||
let name = memo.names.get(raw);
|
||||
if (name === undefined) {
|
||||
name = canonicalTeam(raw, known);
|
||||
memo.names.set(raw, name);
|
||||
// Let other requests in between the new names (the first reading of a big archive).
|
||||
if (++fresh % 25 === 0) await new Promise((r) => setImmediate(r));
|
||||
}
|
||||
const key = fold(name);
|
||||
const label = byKey.get(key) ?? name;
|
||||
byKey.set(key, label);
|
||||
@@ -403,6 +426,21 @@ export async function registerArchiveViewerRoutes(
|
||||
return out;
|
||||
};
|
||||
|
||||
// The team names of every archive read once in the background after a start, so the first viewer of "Equipas"
|
||||
// does not wait for them (and the proxy does not give up first).
|
||||
const warmTeams = async () => {
|
||||
const sources = await db.cloudSource.findMany({ where: { secretEnc: { not: null } }, select: { id: true } });
|
||||
for (const s of sources) {
|
||||
const rows = await db.cloudFolder.findMany({ where: { sourceId: s.id, matchedBy: { not: "FOLDER" } }, select: { event: { select: { home: true, away: true } } } });
|
||||
await teamGroups(s.id, rows.flatMap((r) => (r.event ? [r.event] : [])));
|
||||
}
|
||||
};
|
||||
if (!process.env.VITEST) {
|
||||
app.addHook("onReady", async () => {
|
||||
setTimeout(() => void warmTeams().catch((err: Error) => app.log.warn({ err }, "archive teams warm-up failed")), 5_000).unref();
|
||||
});
|
||||
}
|
||||
|
||||
/** Galleries the viewer may see, newest first; by words in the name, a team or a player. */
|
||||
app.get("/v1/archive/:sourceId/galleries", async (req) => {
|
||||
const { sourceId } = SourceParams.parse(req.params);
|
||||
|
||||
@@ -530,7 +530,7 @@ describe("delivery", () => {
|
||||
// Only the best: without the autopilot, the photographer's stars decide.
|
||||
await ctx.db.photo.update({ where: { id: b }, data: { rating: 3 } });
|
||||
const best = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/best`, headers: bearer(token), payload: { targetId, eventId: event.id, count: 1, dryRun: true } });
|
||||
expect(best.json()).toEqual({ chosen: [b], queued: [], skipped: [] });
|
||||
expect(best.json()).toEqual({ chosen: [b], rest: [], queued: [], skipped: [] });
|
||||
const res = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a, b] } });
|
||||
expect(res.statusCode).toBe(202);
|
||||
zz.logins = 0;
|
||||
|
||||
@@ -306,7 +306,7 @@ describe("library", () => {
|
||||
headers: bearer(admin),
|
||||
payload: { ids, patch: { flag: "PICK", rating: 4, players: ["Miguel Silva (VSC)"] } },
|
||||
});
|
||||
expect(patch.json()).toEqual({ updated: 2, changed: 2, resent: 0 });
|
||||
expect(patch.json()).toEqual({ updated: 2 });
|
||||
expect(broadcaster.sent[0]?.message).toEqual({ type: "photo.updated", ids, patch: { flag: "PICK", rating: 4, players: ["Miguel Silva (VSC)"] } });
|
||||
|
||||
const picks = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?flag=PICK&minRating=4`, headers: bearer(admin) });
|
||||
|
||||
@@ -457,6 +457,8 @@ export const t = {
|
||||
hostnamePlaceholder: "arquivo.ligaportugal.pt",
|
||||
hostnameHelp: "Opcional. Aponta esse endereço (DNS, CNAME) para o mesmo servidor do arquivo: o arquivo abre na raiz e o certificado é pedido sozinho.",
|
||||
hostnameSave: "Guardar",
|
||||
rename: "Nome do arquivo",
|
||||
renameHelp: "Aparece aqui e no título do site de consulta.",
|
||||
resume: "Retomar",
|
||||
remove: "Desligar",
|
||||
removeConfirm: "Desligar esta cloud? As fotos já indexadas ficam na biblioteca.",
|
||||
|
||||
@@ -121,6 +121,8 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
|
||||
const viewerUrl = source.hostname ? `https://${source.hostname}` : `${VIEWER_BASE.replace(/\/+$/, "")}/arquivo/${source.id}`;
|
||||
const [hostname, setHostname] = useState(source.hostname ?? "");
|
||||
useEffect(() => setHostname(source.hostname ?? ""), [source.hostname]);
|
||||
const [name, setName] = useState(source.name);
|
||||
useEffect(() => setName(source.name), [source.name]);
|
||||
|
||||
const run = (fn: () => Promise<CloudSource | void>) => {
|
||||
setBusy(true);
|
||||
@@ -212,6 +214,30 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<form
|
||||
className="flex w-full flex-wrap items-center gap-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) void run(() => api.updateCloudSource(source.id, { name: name.trim() }));
|
||||
}}
|
||||
>
|
||||
<span className="text-muted">{A.rename}:</span>
|
||||
<input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
maxLength={80}
|
||||
disabled={busy}
|
||||
className="h-6 min-w-[220px] border border-black bg-cell px-2 text-[11px] text-ink"
|
||||
/>
|
||||
{name.trim() && name.trim() !== source.name && (
|
||||
<button type="submit" disabled={busy} className="h-6 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on disabled:opacity-40">
|
||||
{A.hostnameSave}
|
||||
</button>
|
||||
)}
|
||||
<span className="w-full text-faint">{A.renameHelp}</span>
|
||||
</form>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<form
|
||||
className="flex w-full flex-wrap items-center gap-2"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@photoreport/desktop",
|
||||
"version": "0.3.19",
|
||||
"version": "0.3.20",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "photoreport-desktop"
|
||||
version = "0.3.19"
|
||||
version = "0.3.20"
|
||||
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."
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- Shown once in macOS's permission prompt (merged into the app's Info.plist by Tauri). -->
|
||||
<key>NSDesktopFolderUsageDescription</key>
|
||||
<string>O PhotoReport lê a pasta de entrada (FTP) e guarda os originais de cada evento na Secretária.</string>
|
||||
<key>NSDocumentsFolderUsageDescription</key>
|
||||
<string>O PhotoReport lê e guarda fotografias nas pastas que escolheres em Documentos.</string>
|
||||
<key>NSDownloadsFolderUsageDescription</key>
|
||||
<string>O PhotoReport lê fotografias que estejam nas Transferências, quando escolhes essa pasta.</string>
|
||||
<key>NSRemovableVolumesUsageDescription</key>
|
||||
<string>O PhotoReport copia as fotografias dos cartões de memória.</string>
|
||||
<key>NSNetworkVolumesUsageDescription</key>
|
||||
<string>O PhotoReport lê e guarda fotografias nas pastas de rede que escolheres.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "PhotoReport",
|
||||
"version": "0.3.19",
|
||||
"version": "0.3.20",
|
||||
"identifier": "pt.photoreport.desktop",
|
||||
"build": {
|
||||
"devUrl": "http://localhost:5173",
|
||||
|
||||
@@ -257,7 +257,7 @@ function SignIn({ info, logo, owner, onDone }: { info: ArchiveInfo; logo: string
|
||||
},
|
||||
() => {
|
||||
win?.close();
|
||||
setError("Não foi possível iniciar a entrada. Tenta daqui a pouco.");
|
||||
setError("O serviço de entrada não está a responder. Tenta daqui a pouco.");
|
||||
},
|
||||
)
|
||||
.finally(() => setBusy(false));
|
||||
|
||||
@@ -82,6 +82,10 @@ Gitea -> webhook -> the container pulls and redeploys itself. No manual `scp`/`r
|
||||
Stripe secret key and webhook secret; in Stripe add the shown endpoint for `checkout.session.completed`,
|
||||
`checkout.session.async_payment_succeeded`, `checkout.session.async_payment_failed` and
|
||||
`checkout.session.expired`. Set `SMTP_URL` on the worker for order emails.
|
||||
An archive's own address (app -> Arquivo -> "Endereço próprio", e.g. `ligaportugal.photoreport.pt`) is one
|
||||
more host on the same port 3100: in Nginx Proxy Manager a Proxy Host for it, forwarded like
|
||||
`events.next.photoreport.pt` (Host passed as is), with its Let's Encrypt certificate. With a wildcard
|
||||
certificate (DNS challenge) one Proxy Host for `*.photoreport.pt` covers every archive under that domain.
|
||||
|
||||
11. SFTPGo (pr-ingest): no users in SFTPGo itself. Set `data_provider.external_auth_hook` to
|
||||
`http://<api>/v1/sftpgo/auth?key=<SFTPGO_HOOK_KEY>` and `external_auth_scope` to 1 (passwords), with the same
|
||||
|
||||
+3
-2
@@ -166,8 +166,9 @@ browser follows it. Photos kept at full size are made 2048 px on the way out.
|
||||
An archive can have its own host (`cloud_sources.hostname`, app → Arquivo → "Endereço próprio"), e.g.
|
||||
`arquivo.ligaportugal.pt`: the site's middleware asks the API (`GET /v1/archive/host?host=`, kept 5 minutes) and
|
||||
serves that archive at the root (`/g/…`, `/p/…`, `/f/…`); links stay at the root. The host's DNS points at the
|
||||
proxy; Caddy gets its certificate on demand, after asking the same endpoint (`?domain=`, 200 only for an archive's
|
||||
host; `infra/proxy/Caddyfile.example`). A host can be one archive's or one public site's, never both.
|
||||
proxy, which sends it to the site like the other domains (Nginx Proxy Manager: a Proxy Host with its certificate,
|
||||
`docs/DEPLOY.md`). With Caddy instead, on-demand TLS can ask the same endpoint (`?domain=`, 200 only for an
|
||||
archive's host; `infra/proxy/Caddyfile.example`). A host can be one archive's or one public site's, never both.
|
||||
|
||||
### People and faces (viewers too)
|
||||
|
||||
|
||||
@@ -52,6 +52,41 @@ if [[ -n "${TAURI_SIGNING_PRIVATE_KEY:-}" && -n "${TAURI_UPDATER_PUBKEY:-}" ]];
|
||||
# The bundler checks each signature against plugins.updater.pubkey, so the public key goes into the config too.
|
||||
extra=(--bundles dmg,app --config "$(node -e 'console.log(JSON.stringify({bundle:{createUpdaterArtifacts:true},plugins:{updater:{pubkey:process.env.PHOTOREPORT_UPDATER_PUBKEY}}}))')")
|
||||
fi
|
||||
step "Code signing"
|
||||
# macOS remembers the folders an app may open (Desktop, Documents, cards) by its signature. Unsigned, every build
|
||||
# (and every update) looks like a new app and asks again, once per access. Signed always with the same identity, the
|
||||
# answer is kept. With an Apple Developer ID set in APPLE_SIGNING_IDENTITY that one is used; otherwise a local
|
||||
# identity, made once in the login keychain, the same for every build on this Mac.
|
||||
if [[ -z "${APPLE_SIGNING_IDENTITY:-}" ]]; then
|
||||
local_id="PhotoReport Local Signing"
|
||||
if ! security find-identity -p codesigning | grep -q "\"$local_id\""; then
|
||||
tmp="$(mktemp -d)"
|
||||
cat >"$tmp/cert.cfg" <<CFG
|
||||
[req]
|
||||
distinguished_name = dn
|
||||
x509_extensions = ext
|
||||
prompt = no
|
||||
[dn]
|
||||
CN = $local_id
|
||||
[ext]
|
||||
keyUsage = critical, digitalSignature
|
||||
extendedKeyUsage = critical, codeSigning
|
||||
basicConstraints = critical, CA:false
|
||||
CFG
|
||||
# The system's LibreSSL: its .p12 is one the keychain imports (OpenSSL 3's default one is not).
|
||||
/usr/bin/openssl req -x509 -newkey rsa:2048 -nodes -days 3650 -keyout "$tmp/key.pem" -out "$tmp/cert.pem" -config "$tmp/cert.cfg" 2>/dev/null
|
||||
/usr/bin/openssl pkcs12 -export -inkey "$tmp/key.pem" -in "$tmp/cert.pem" -name "$local_id" -out "$tmp/id.p12" -passout pass:photoreport
|
||||
security import "$tmp/id.p12" -k "$HOME/Library/Keychains/login.keychain-db" -P photoreport -T /usr/bin/codesign
|
||||
echo "macOS asks for your password once, to trust this certificate for signing:"
|
||||
security add-trusted-cert -r trustRoot -p codeSign -k "$HOME/Library/Keychains/login.keychain-db" "$tmp/cert.pem"
|
||||
rm -rf "$tmp"
|
||||
fi
|
||||
export APPLE_SIGNING_IDENTITY="$local_id"
|
||||
# Not a Developer ID: no notarisation, so no hardened runtime (it would refuse the bundled ONNX library).
|
||||
extra+=(--config '{"bundle":{"macOS":{"hardenedRuntime":false}}}')
|
||||
fi
|
||||
echo "Signing as: $APPLE_SIGNING_IDENTITY"
|
||||
|
||||
VITE_API_URL="$API" PHOTOREPORT_API_URL="$API" pnpm --filter @photoreport/desktop exec tauri build --target universal-apple-darwin "${extra[@]}"
|
||||
BUNDLE="apps/desktop/src-tauri/target/universal-apple-darwin/release/bundle"
|
||||
OUT="$BUNDLE/dmg"
|
||||
|
||||
@@ -205,10 +205,11 @@ impl Engine {
|
||||
want: usize,
|
||||
embed: &mut dyn FnMut(&[u8]) -> Option<Vec<f32>>,
|
||||
) -> Option<Vec<f32>> {
|
||||
if let Some(vector) = embed(crop) {
|
||||
if vector.len() == want && vector.iter().all(|value| value.is_finite()) {
|
||||
return Some(vector);
|
||||
}
|
||||
if let Some(vector) = embed(crop)
|
||||
&& vector.len() == want
|
||||
&& vector.iter().all(|value| value.is_finite())
|
||||
{
|
||||
return Some(vector);
|
||||
}
|
||||
self.models.embedder.embed(crop).ok()
|
||||
}
|
||||
|
||||
@@ -22,8 +22,16 @@ struct Request {
|
||||
#[derive(Serialize)]
|
||||
#[serde(untagged)]
|
||||
enum Response {
|
||||
Ok { id: String, width: usize, height: usize, faces: Vec<FoundFace> },
|
||||
Err { id: String, error: String },
|
||||
Ok {
|
||||
id: String,
|
||||
width: usize,
|
||||
height: usize,
|
||||
faces: Vec<FoundFace>,
|
||||
},
|
||||
Err {
|
||||
id: String,
|
||||
error: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@@ -35,7 +43,12 @@ fn main() {
|
||||
match arg.as_str() {
|
||||
"--models" => models_dir = args.next().unwrap_or_default(),
|
||||
"--embedder" => embedder = args.next().unwrap_or_default(),
|
||||
"--min-score" => min_score = args.next().and_then(|v| v.parse().ok()).unwrap_or(min_score),
|
||||
"--min-score" => {
|
||||
min_score = args
|
||||
.next()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(min_score)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -48,7 +61,11 @@ fn main() {
|
||||
};
|
||||
let stdout = std::io::stdout();
|
||||
let mut out = stdout.lock();
|
||||
let _ = writeln!(out, "{}", serde_json::json!({ "ready": true, "embedder": embedder, "dim": models.dim() }));
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{}",
|
||||
serde_json::json!({ "ready": true, "embedder": embedder, "dim": models.dim() })
|
||||
);
|
||||
let _ = out.flush();
|
||||
for line in std::io::stdin().lock().lines() {
|
||||
let Ok(line) = line else { break };
|
||||
@@ -57,12 +74,23 @@ fn main() {
|
||||
}
|
||||
let response = match serde_json::from_str::<Request>(&line) {
|
||||
Ok(req) => match models.analyse(Path::new(&req.path)) {
|
||||
Ok(read) => Response::Ok { id: req.id, width: read.width, height: read.height, faces: read.faces },
|
||||
Ok(read) => Response::Ok {
|
||||
id: req.id,
|
||||
width: read.width,
|
||||
height: read.height,
|
||||
faces: read.faces,
|
||||
},
|
||||
Err(error) => Response::Err { id: req.id, error },
|
||||
},
|
||||
Err(e) => Response::Err { id: String::new(), error: format!("bad request: {e}") },
|
||||
Err(e) => Response::Err {
|
||||
id: String::new(),
|
||||
error: format!("bad request: {e}"),
|
||||
},
|
||||
};
|
||||
if serde_json::to_writer(&mut out, &response).is_err() || writeln!(out).is_err() || out.flush().is_err() {
|
||||
if serde_json::to_writer(&mut out, &response).is_err()
|
||||
|| writeln!(out).is_err()
|
||||
|| out.flush().is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user