Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a5cbbe594d | ||
|
|
e8339cdf3f |
No files matched your search
@@ -15,6 +15,10 @@ import { type Transport, type TransportKind, ZerozeroTransport, createTransport,
|
||||
import { type ZerozeroGame, matchGame, zerozeroGameId } from "./zerozero.js";
|
||||
|
||||
export const MAX_ATTEMPTS = 5;
|
||||
/** How long a delivery waits for an original still on the photographer's computer before it gives up. */
|
||||
export const ORIGINAL_WAIT_MS = 72 * 3600_000;
|
||||
/** How often it asks that computer again while waiting. */
|
||||
export const ORIGINAL_ASK_MS = 60_000;
|
||||
/** Running items older than this belonged to a worker that died; they go back in the queue. */
|
||||
const STALE_RUNNING_MS = 10 * 60_000;
|
||||
|
||||
@@ -217,6 +221,18 @@ export class DeliveryService {
|
||||
const { db, storage, log } = this.deps;
|
||||
const item = await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId }, include: { target: true, photo: { include: { uploader: { select: { name: true } } } }, event: true } });
|
||||
let update: Partial<DeliveryItem>;
|
||||
if (!item.photo.originalStored) {
|
||||
// Only the desktop's 2048 px preview is here: delivering it would send a small photo. Ask the desktop app
|
||||
// that keeps the original to send it, and try again shortly (waiting does not count as an attempt).
|
||||
this.deps.broadcaster.library(item.organizationId, { type: "original.requested", photoId: item.photoId, sha256: item.photo.sha256 });
|
||||
update =
|
||||
Date.now() - item.createdAt.getTime() > ORIGINAL_WAIT_MS
|
||||
? { status: "FAILED", lastError: "original_not_here", finishedAt: new Date() }
|
||||
: { status: "QUEUED", attempts: Math.max(0, item.attempts - 1), lastError: "waiting_for_original", nextAttemptAt: new Date(Date.now() + ORIGINAL_ASK_MS) };
|
||||
const saved = await db.deliveryItem.update({ where: { id: itemId }, data: update });
|
||||
this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) });
|
||||
return saved;
|
||||
}
|
||||
try {
|
||||
const vars = buildVars(
|
||||
eventInfoOf(item.event),
|
||||
|
||||
@@ -218,6 +218,8 @@ export class IngestService {
|
||||
data: { storageKey: key, byteSize: size, originalStored: true, ...(org?.biometricsEnabled && { facesStatus: "PENDING" }) },
|
||||
});
|
||||
log.info({ photoId: photo.id }, "ingest: original replaces the desktop preview");
|
||||
// Deliveries waiting for it go now.
|
||||
await db.deliveryItem.updateMany({ where: { photoId: photo.id, status: "QUEUED" }, data: { nextAttemptAt: new Date() } });
|
||||
this.deps.broadcaster.library(photo.organizationId, { type: "original.stored", photoId: photo.id });
|
||||
return { status: "ingested", photoId: photo.id, eventId: updated.eventId };
|
||||
}
|
||||
|
||||
@@ -410,6 +410,30 @@ describe("delivery", () => {
|
||||
expect((await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries/${claim.items[0]!.id}/local-file`, headers: bearer(token) })).statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("waits for an original still on the photographer's computer instead of delivering its preview", async () => {
|
||||
const { orgId, token } = await setup();
|
||||
const created = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/delivery-targets`,
|
||||
headers: bearer(token),
|
||||
payload: { name: "Disco", kind: "LOCAL", baseUrl: "/Users/peter/Entregas", username: "mac-0001-peter", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}" },
|
||||
});
|
||||
const targetId = (created.json() as { id: string }).id;
|
||||
const a = await photo("preview-only.jpg", "2026:09:23 21:10:00");
|
||||
await ctx.db.photo.update({ where: { id: a }, data: { originalStored: false } });
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a] } });
|
||||
await drain();
|
||||
const waiting = await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } });
|
||||
expect([waiting.status, waiting.lastError, waiting.attempts]).toEqual(["QUEUED", "waiting_for_original", 0]);
|
||||
expect(waiting.nextAttemptAt!.getTime()).toBeGreaterThan(Date.now());
|
||||
|
||||
// The original arrives (the ingest moves waiting deliveries forward): now it is rendered.
|
||||
await ctx.db.photo.update({ where: { id: a }, data: { originalStored: true } });
|
||||
await ctx.db.deliveryItem.updateMany({ where: { photoId: a, status: "QUEUED" }, data: { nextAttemptAt: new Date() } });
|
||||
await drain();
|
||||
expect(await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } })).toMatchObject({ status: "WAITING", lastError: null });
|
||||
});
|
||||
|
||||
it("retries transient errors with back-off and stops at auth errors", async () => {
|
||||
const { orgId, token, target } = await setup();
|
||||
const id = await photo("a.jpg", "2026:09:23 21:10:00");
|
||||
|
||||
@@ -87,6 +87,31 @@ describe("importing destinations", () => {
|
||||
expect(await screen.findByText("Importado")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("brings the saved password along when the other app keeps it readable", async () => {
|
||||
const created: { name: string; password?: string }[] = [];
|
||||
const api = {
|
||||
createDeliveryTarget: vi.fn(async (_org: string, input: { name: string; password?: string }) => {
|
||||
created.push(input);
|
||||
return { id: `t${created.length}`, ...input } as unknown as DeliveryTarget;
|
||||
}),
|
||||
} as unknown as ApiClient;
|
||||
render(
|
||||
<ImportTargets
|
||||
api={api}
|
||||
orgId="org"
|
||||
existing={[]}
|
||||
shell={shell({ profiles: async () => ({ photoMechanic: [], photoMechanicAccounts: [], filezilla: SITES, passwords: { "fz:Clube:ftp.clube.pt": "guardada" }, unreadable: ["fz:Jornal:ftp.jornal.pt"] }) })}
|
||||
onClose={() => {}}
|
||||
onImported={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(await screen.findByText("senha guardada no FileZilla")).toBeTruthy();
|
||||
expect(screen.getByText("o FileZilla guarda esta senha cifrada: escreve-a")).toBeTruthy();
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Clube" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Importar 1" }));
|
||||
await waitFor(() => expect(created).toEqual([expect.objectContaining({ name: "Clube", password: "guardada" })]));
|
||||
});
|
||||
|
||||
it("says when the desktop app is too old for it", async () => {
|
||||
render(<ImportTargets api={{} as ApiClient} orgId="org" existing={[]} shell={shell({ profiles: async () => Promise.reject(new Error("command not found")) })} onClose={() => {}} onImported={() => {}} />);
|
||||
expect(await screen.findByText(/atualiza a app/)).toBeTruthy();
|
||||
|
||||
@@ -198,7 +198,7 @@ export const t = {
|
||||
importTargets: {
|
||||
title: "Importar destinos",
|
||||
button: "Importar…",
|
||||
help: "Destinos guardados no Photo Mechanic (contas e modelos de upload) e no FileZilla, neste computador. Servidor, utilizador, pasta, tamanho, qualidade e nome do ficheiro vêm de lá; a senha escreves aqui (essas apps não a deixam ler). Escolhe os que queres e escreve a senha de cada um.",
|
||||
help: "Destinos guardados no Photo Mechanic (contas e modelos de upload) e no FileZilla, neste computador. Servidor, utilizador, senha, pasta, tamanho, qualidade e nome do ficheiro vêm de lá. Uma senha que a outra app guarda cifrada tens de a escrever aqui.",
|
||||
none: "Não encontrei destinos do Photo Mechanic nem do FileZilla neste computador.",
|
||||
tooOld: "Esta versão da app ainda não sabe importar destinos: atualiza a app.",
|
||||
showArchived: "Mostrar os modelos arquivados do Photo Mechanic",
|
||||
@@ -208,6 +208,8 @@ export const t = {
|
||||
password: "Senha",
|
||||
key: "Chave privada (PEM) ou senha",
|
||||
missingPassword: "Falta a senha nalguns dos escolhidos.",
|
||||
savedPassword: (app: string) => `senha guardada no ${app}`,
|
||||
encryptedPassword: (app: string) => `o ${app} guarda esta senha cifrada: escreve-a`,
|
||||
done: "Importado",
|
||||
import: (n: number) => (n ? `Importar ${n}` : "Importar"),
|
||||
},
|
||||
@@ -278,6 +280,10 @@ export const t = {
|
||||
shareLink: "Link de partilha",
|
||||
copyLink: "Copiar link",
|
||||
copied: "Copiado",
|
||||
deliveryErrors: {
|
||||
waiting_for_original: "À espera do original (está no computador do fotógrafo; abre a app PhotoReport nesse computador)",
|
||||
original_not_here: "O original nunca chegou do computador do fotógrafo",
|
||||
},
|
||||
deliveryStatus: { QUEUED: "Na fila", RUNNING: "A enviar", WAITING: "À espera do computador", DONE: "Entregue", FAILED: "Falhou" },
|
||||
codeList: "Substituição de códigos",
|
||||
codeListHelp: "Uma linha por código: código, tab, texto. Escreve \\v7\\ numa legenda e é trocado pelo texto. Listas do Photo Mechanic servem tal como estão.",
|
||||
|
||||
@@ -9,13 +9,15 @@ interface Row {
|
||||
selected: boolean;
|
||||
name: string;
|
||||
password: string;
|
||||
/** The password came from the other app ("saved"), or it keeps it encrypted ("encrypted"). */
|
||||
saved: "saved" | "encrypted" | null;
|
||||
result: "ok" | string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Desktop: the upload destinations saved in Photo Mechanic and FileZilla on this computer, to bring in as
|
||||
* destinations. Server, user, folders and output settings come from there; passwords are typed here (the other
|
||||
* apps keep them to themselves).
|
||||
* destinations. Server, user, folders, output settings and the saved password (when the other app keeps it readable)
|
||||
* come from there; an encrypted password is typed here.
|
||||
*/
|
||||
export function ImportTargets(props: { api: ApiClient; orgId: string; existing: DeliveryTarget[]; shell?: DeliveryShell; onClose: () => void; onImported: (targets: DeliveryTarget[]) => void }) {
|
||||
const L = t.importTargets;
|
||||
@@ -30,13 +32,17 @@ export function ImportTargets(props: { api: ApiClient; orgId: string; existing:
|
||||
shell.profiles().then(
|
||||
(sources) =>
|
||||
setRows(
|
||||
importCandidates(sources).map((c) => ({
|
||||
c,
|
||||
selected: false,
|
||||
name: taken.has(c.name.toLowerCase()) ? `${c.name} (${c.source === "FileZilla" ? "FileZilla" : "PM"})` : c.name,
|
||||
password: "",
|
||||
result: null,
|
||||
})),
|
||||
importCandidates(sources).map((c) => {
|
||||
const saved = sources.passwords?.[c.passwordKey];
|
||||
return {
|
||||
c,
|
||||
selected: false,
|
||||
name: taken.has(c.name.toLowerCase()) ? `${c.name} (${c.source === "FileZilla" ? "FileZilla" : "PM"})` : c.name,
|
||||
password: saved ?? "",
|
||||
saved: saved ? "saved" : sources.unreadable?.includes(c.passwordKey) ? "encrypted" : null,
|
||||
result: null,
|
||||
};
|
||||
}),
|
||||
),
|
||||
() => setError(L.tooOld),
|
||||
);
|
||||
@@ -123,8 +129,9 @@ export function ImportTargets(props: { api: ApiClient; orgId: string; existing:
|
||||
) : r.c.keyAuth ? (
|
||||
<textarea className={`${input} h-16 font-mono text-[10.5px]`} placeholder={L.key} value={r.password} onChange={(e) => set(i, { password: e.target.value, selected: true })} spellCheck={false} />
|
||||
) : (
|
||||
<input type="password" autoComplete="new-password" className={input} placeholder={L.password} value={r.password} onChange={(e) => set(i, { password: e.target.value, selected: true })} />
|
||||
<input type="password" autoComplete="new-password" className={input} placeholder={L.password} value={r.password} onChange={(e) => set(i, { password: e.target.value, selected: true, saved: null })} />
|
||||
)}
|
||||
{!r.c.problem && r.result !== "ok" && r.saved && <p className={`text-[11px] ${r.saved === "saved" ? "text-faint" : "text-[#f0a35a]"}`}>{r.saved === "saved" ? L.savedPassword(r.c.source) : L.encryptedPassword(r.c.source)}</p>}
|
||||
{r.result && r.result !== "ok" && <p className="text-danger">{r.result}</p>}
|
||||
</div>
|
||||
</li>
|
||||
|
||||
@@ -14,6 +14,10 @@ export interface ImportSources {
|
||||
photoMechanic: { kind: string; name: string; archived: boolean; text: string }[];
|
||||
photoMechanicAccounts: { kind: string; name: string; text: string }[];
|
||||
filezilla: string | null;
|
||||
/** Saved passwords the desktop app could read, by `passwordKey` (older apps: none). */
|
||||
passwords?: Record<string, string>;
|
||||
/** Keys of saved passwords that are encrypted (typed by hand). */
|
||||
unreadable?: string[];
|
||||
}
|
||||
|
||||
export interface ImportCandidate {
|
||||
@@ -38,6 +42,8 @@ export interface ImportCandidate {
|
||||
keyAuth: boolean;
|
||||
/** Why it cannot be imported as it is (no server known). */
|
||||
problem: string | null;
|
||||
/** Where its saved password is found in `ImportSources.passwords` (the account or site). */
|
||||
passwordKey: string;
|
||||
}
|
||||
|
||||
interface PmAccount {
|
||||
@@ -218,6 +224,7 @@ export function importCandidates(src: ImportSources): ImportCandidate[] {
|
||||
dpi: Math.min(1200, Math.max(72, Number(s.render_res_edit) || 300)),
|
||||
keyAuth: found?.account.keyAuth ?? false,
|
||||
problem: found ? null : accountName ? `a conta "${accountName}" não está nas contas do Photo Mechanic` : "sem conta",
|
||||
passwordKey: `pm:${kind}:${accountName}`,
|
||||
});
|
||||
}
|
||||
for (const [k, { kind, account }] of accounts) {
|
||||
@@ -241,6 +248,7 @@ export function importCandidates(src: ImportSources): ImportCandidate[] {
|
||||
dpi: 300,
|
||||
keyAuth: account.keyAuth,
|
||||
problem: account.host ? null : "sem servidor",
|
||||
passwordKey: `pm:${kind}:${account.name}`,
|
||||
});
|
||||
}
|
||||
if (src.filezilla) out.push(...fileZillaCandidates(src.filezilla));
|
||||
@@ -298,6 +306,7 @@ export function fileZillaCandidates(xml: string): ImportCandidate[] {
|
||||
dpi: 300,
|
||||
keyAuth: text(server, "Logontype") === "5",
|
||||
problem: host ? null : "sem servidor",
|
||||
passwordKey: `fz:${name}:${host}`,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
|
||||
@@ -121,7 +121,7 @@ export function DeliveryPage() {
|
||||
<td className="border-b border-line px-3 py-1.5 font-mono text-[11px] text-faint">{i.sequence}</td>
|
||||
<td className="border-b border-line px-3 py-1.5 font-mono text-[11px] break-all">
|
||||
{i.remotePath ?? <span className="text-faint">—</span>}
|
||||
{i.lastError && <span className="block text-[10px] text-[#f0a35a]">{i.lastError}</span>}
|
||||
{i.lastError && <span className="block text-[10px] text-[#f0a35a]">{t.deliveryErrors[i.lastError as keyof typeof t.deliveryErrors] ?? i.lastError}</span>}
|
||||
</td>
|
||||
<td className={`border-b border-line px-3 py-1.5 font-mono text-[11px] ${STATUS_COLOR[i.status]}`}>
|
||||
{t.deliveryStatus[i.status]}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@photoreport/desktop",
|
||||
"version": "0.3.10",
|
||||
"version": "0.3.11",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "photoreport-desktop"
|
||||
version = "0.3.10"
|
||||
version = "0.3.11"
|
||||
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."
|
||||
|
||||
@@ -5,9 +5,10 @@
|
||||
//! folder picker (kept in the app's config folder), never anywhere a page asks: the web app is loaded from the server.
|
||||
//!
|
||||
//! Importing reads two fixed places, never a path a page passes: Photo Mechanic's upload accounts and templates
|
||||
//! (`fileupload`), and FileZilla's site manager. Passwords are removed here and never reach the page: the person
|
||||
//! types them once when importing.
|
||||
//! (`fileupload`), and FileZilla's site manager. Saved passwords are taken out of those texts and handed over on
|
||||
//! their own, when the other app keeps them readable (plain or base64); encrypted ones are typed by the person.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
@@ -180,6 +181,173 @@ pub struct ImportSources {
|
||||
pub photo_mechanic_accounts: Vec<Snapshot>,
|
||||
/// FileZilla's site manager (XML, passwords removed).
|
||||
pub filezilla: Option<String>,
|
||||
/// The saved passwords that could be read, by destination: `pm:<KIND>:<account>` (Photo Mechanic) and
|
||||
/// `fz:<site name>:<host>` (FileZilla). They go straight into the destinations the person imports.
|
||||
pub passwords: BTreeMap<String, String>,
|
||||
/// Destinations with a saved password that cannot be read (encrypted by the other app): typed by hand.
|
||||
pub unreadable: Vec<String>,
|
||||
}
|
||||
|
||||
/// Standard base64 (whitespace ignored). None when it is not base64.
|
||||
fn base64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
let (mut acc, mut bits) = (0u32, 0u32);
|
||||
for c in s.bytes().filter(|c| !c.is_ascii_whitespace()) {
|
||||
let v = match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'+' => 62,
|
||||
b'/' => 63,
|
||||
b'=' => break,
|
||||
_ => return None,
|
||||
} as u32;
|
||||
acc = (acc << 6) | v;
|
||||
bits += 6;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
out.push((acc >> bits) as u8);
|
||||
acc &= (1 << bits) - 1;
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A password as text: readable UTF-8 without control characters, else None (encrypted or binary).
|
||||
fn readable(bytes: Vec<u8>) -> Option<String> {
|
||||
let s = String::from_utf8(bytes).ok()?;
|
||||
(!s.is_empty() && !s.chars().any(char::is_control)).then_some(s)
|
||||
}
|
||||
|
||||
fn unquote(v: &str) -> String {
|
||||
let v = v.trim();
|
||||
if v.len() >= 2
|
||||
&& ((v.starts_with('\'') && v.ends_with('\'')) || (v.starts_with('"') && v.ends_with('"')))
|
||||
{
|
||||
v[1..v.len() - 1].replace("''", "'")
|
||||
} else {
|
||||
v.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// The password of each Photo Mechanic account (`name: [user, password, settings]`, the second item): plain text,
|
||||
/// or `!binary` base64 when it decodes to text. Some(None): saved but not readable.
|
||||
pub fn pm_passwords(yaml: &str) -> Vec<(String, Option<String>)> {
|
||||
let lines: Vec<&str> = yaml.lines().collect();
|
||||
let mut out = Vec::new();
|
||||
let mut account: Option<String> = None;
|
||||
let mut item_indent: Option<usize> = None;
|
||||
let mut items = 0;
|
||||
let mut i = 0;
|
||||
while i < lines.len() {
|
||||
let line = lines[i];
|
||||
let indent = line.len() - line.trim_start().len();
|
||||
let t = line.trim();
|
||||
i += 1;
|
||||
if t.ends_with(':') && !t.starts_with('-') && !t.starts_with(':') {
|
||||
account = Some(unquote(&t[..t.len() - 1]));
|
||||
item_indent = None;
|
||||
items = 0;
|
||||
continue;
|
||||
}
|
||||
if !(t.starts_with("- ") || t == "-") {
|
||||
continue;
|
||||
}
|
||||
if item_indent.is_none() {
|
||||
item_indent = Some(indent);
|
||||
}
|
||||
if item_indent != Some(indent) {
|
||||
continue;
|
||||
}
|
||||
items += 1;
|
||||
if items != 2 {
|
||||
continue;
|
||||
}
|
||||
let Some(name) = account.clone() else {
|
||||
continue;
|
||||
};
|
||||
let value = t[1..].trim();
|
||||
// What belongs to the item: its value and any deeper lines (a block scalar).
|
||||
let mut block = String::new();
|
||||
while i < lines.len() {
|
||||
let l = lines[i];
|
||||
let ind = l.len() - l.trim_start().len();
|
||||
if l.trim().is_empty() || ind > indent {
|
||||
block.push_str(l.trim());
|
||||
i += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let password = if let Some(rest) = value.strip_prefix("!binary") {
|
||||
let inline = rest.trim().trim_start_matches(['|', '>', '-']).trim();
|
||||
base64_decode(&format!("{inline}{block}")).and_then(readable)
|
||||
} else {
|
||||
let v = unquote(value);
|
||||
(!v.is_empty() && v != "~" && v != "null").then_some(v)
|
||||
};
|
||||
if password.is_some() || !value.is_empty() && value != "''" {
|
||||
out.push((name, password));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn tag<'a>(xml: &'a str, name: &str) -> Option<(&'a str, &'a str)> {
|
||||
let open = format!("<{name}");
|
||||
let start = xml.find(&open)?;
|
||||
let after = &xml[start + open.len()..];
|
||||
if !after.starts_with('>') && !after.starts_with(' ') {
|
||||
return None;
|
||||
}
|
||||
let gt = after.find('>')?;
|
||||
let attrs = &after[..gt];
|
||||
let body = &after[gt + 1..];
|
||||
let end = body.find(&format!("</{name}>"))?;
|
||||
Some((attrs, &body[..end]))
|
||||
}
|
||||
|
||||
fn xml_text(s: &str) -> String {
|
||||
s.trim()
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace(""", "\"")
|
||||
.replace("'", "'")
|
||||
.replace("&", "&")
|
||||
}
|
||||
|
||||
/// FileZilla's saved passwords per site (`<Pass encoding="base64">`, or plain); one protected by a master password
|
||||
/// (`encoding="crypt"`) is not readable.
|
||||
pub fn filezilla_passwords(xml: &str) -> Vec<(String, Option<String>)> {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = xml;
|
||||
while let Some(start) = rest.find("<Server") {
|
||||
let after = &rest[start..];
|
||||
let Some(end) = after.find("</Server>") else {
|
||||
break;
|
||||
};
|
||||
let server = &after[..end];
|
||||
rest = &after[end + "</Server>".len()..];
|
||||
let Some((attrs, pass)) = tag(server, "Pass") else {
|
||||
continue;
|
||||
};
|
||||
let host = tag(server, "Host")
|
||||
.map(|(_, v)| xml_text(v))
|
||||
.unwrap_or_default();
|
||||
let name = tag(server, "Name")
|
||||
.map(|(_, v)| xml_text(v))
|
||||
.filter(|n| !n.is_empty())
|
||||
.unwrap_or_else(|| host.clone());
|
||||
let password = if attrs.contains("encoding=\"base64\"") {
|
||||
base64_decode(pass.trim()).and_then(readable)
|
||||
} else if attrs.contains("encoding=") {
|
||||
None
|
||||
} else {
|
||||
Some(xml_text(pass)).filter(|p| !p.is_empty())
|
||||
};
|
||||
out.push((format!("{name}:{host}"), password));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Photo Mechanic's account files list each account as `name: [user, password, settings]`; the password (the second
|
||||
@@ -284,6 +452,15 @@ pub fn import_sources(home: &Path, config: Option<&Path>) -> ImportSources {
|
||||
};
|
||||
if let Some(text) = read_text(&e.path()) {
|
||||
if text.contains(":settings:") {
|
||||
for (account, password) in pm_passwords(&text) {
|
||||
let key = format!("pm:{}:{account}", kind.to_uppercase());
|
||||
match password {
|
||||
Some(p) => {
|
||||
sources.passwords.insert(key, p);
|
||||
}
|
||||
None => sources.unreadable.push(key),
|
||||
}
|
||||
}
|
||||
sources.photo_mechanic_accounts.push(Snapshot {
|
||||
kind: kind.to_string(),
|
||||
name: kind.to_string(),
|
||||
@@ -334,10 +511,18 @@ pub fn import_sources(home: &Path, config: Option<&Path>) -> ImportSources {
|
||||
fz.push(config.join("FileZilla").join("sitemanager.xml"));
|
||||
fz.push(config.join("filezilla").join("sitemanager.xml"));
|
||||
}
|
||||
sources.filezilla = fz
|
||||
.iter()
|
||||
.find_map(|p| read_text(p))
|
||||
.map(|t| strip_filezilla_passwords(&t));
|
||||
if let Some(xml) = fz.iter().find_map(|p| read_text(p)) {
|
||||
for (site, password) in filezilla_passwords(&xml) {
|
||||
let key = format!("fz:{site}");
|
||||
match password {
|
||||
Some(p) => {
|
||||
sources.passwords.insert(key, p);
|
||||
}
|
||||
None => sources.unreadable.push(key),
|
||||
}
|
||||
}
|
||||
sources.filezilla = Some(strip_filezilla_passwords(&xml));
|
||||
}
|
||||
sources
|
||||
}
|
||||
|
||||
@@ -400,7 +585,7 @@ pub fn delivery_write(
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// Upload destinations saved in Photo Mechanic and FileZilla on this computer (without passwords).
|
||||
/// Upload destinations saved in Photo Mechanic and FileZilla on this computer, with the passwords that can be read.
|
||||
#[tauri::command]
|
||||
pub fn import_upload_profiles() -> ImportSources {
|
||||
let home = dirs::home_dir().unwrap_or_default();
|
||||
@@ -478,6 +663,27 @@ mod tests {
|
||||
assert_eq!(out.matches("- ''").count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_saved_passwords_when_they_are_text() {
|
||||
let yaml = "---\n:connection_settings_dialog:\n :settings:\n COFINA - ARQUIVO:\n - mnoticiasex\n - !binary |-\n c2VjcmV0\n - :server_addr_edit:\n :value: ftp.cofina.pt\n FPF:\n - fpf\n - plainsecret\n - :server_addr_edit:\n :value: ftp.fpf.pt\n CIFRADA:\n - c\n - !binary |-\n /wCAgQ==\n - :x: 1\n SEM:\n - s\n - ''\n - :x: 1\n";
|
||||
assert_eq!(
|
||||
pm_passwords(yaml),
|
||||
vec![
|
||||
("COFINA - ARQUIVO".to_string(), Some("secret".to_string())),
|
||||
("FPF".to_string(), Some("plainsecret".to_string())),
|
||||
("CIFRADA".to_string(), None),
|
||||
]
|
||||
);
|
||||
let xml = r#"<Servers><Server><Host>ftp.x.pt</Host><User>u</User><Pass encoding="base64">c2VjcmV0</Pass><Name>X & Y</Name></Server><Server><Host>ftp.z.pt</Host><Pass encoding="crypt" pubkey="k">zz</Pass><Name>Z</Name></Server><Server><Host>ftp.n.pt</Host></Server></Servers>"#;
|
||||
assert_eq!(
|
||||
filezilla_passwords(xml),
|
||||
vec![
|
||||
("X & Y:ftp.x.pt".to_string(), Some("secret".to_string())),
|
||||
("Z:ftp.z.pt".to_string(), None),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filezilla_passwords_never_leave() {
|
||||
let xml = r#"<Server><Host>ftp.x.pt</Host><User>u</User><Pass encoding="base64">c2VjcmV0</Pass><Name>X</Name></Server>"#;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "PhotoReport",
|
||||
"version": "0.3.10",
|
||||
"version": "0.3.11",
|
||||
"identifier": "pt.photoreport.desktop",
|
||||
"build": {
|
||||
"devUrl": "http://localhost:5173",
|
||||
|
||||
@@ -323,9 +323,11 @@ The same queue also delivers to SFTP, FTP/FTPS and Dropbox (`delivery/transports
|
||||
the finished files to choose from later.
|
||||
- **Importing destinations** (desktop, "Importar…" in Destinos): Photo Mechanic's upload accounts
|
||||
(`fileupload/templates/builtin/<kind>-conn.yml`) and templates (`fileupload/snapshot/builtin/<kind>/*.snap`), and
|
||||
FileZilla's `sitemanager.xml`, read by the desktop app from their fixed places with the passwords removed there;
|
||||
`library/importSources.ts` turns them into destinations (server, user, folder, size, quality, rename) and the
|
||||
person types each password.
|
||||
FileZilla's `sitemanager.xml`, read by the desktop app from their fixed places. The desktop takes the saved
|
||||
passwords out of those texts and hands them over separately when they are readable (plain, or base64 that decodes
|
||||
to text; FileZilla's `encoding="crypt"` and binary Photo Mechanic blobs are not); `library/importSources.ts` turns
|
||||
the rest into destinations (server, user, folder, size, quality, rename), and an encrypted password is typed by
|
||||
the person.
|
||||
- **ZeroZero** (`fotos.zerozero.pt`, `delivery/zerozero.ts`): the photographer's zerozero.pt account. The server
|
||||
signs in through zerozero.pt's OAuth (`/api/auth/login` → `oauth.php` → `ax_login.php` → `/api/auth/callback`,
|
||||
cookies kept in a small jar), and uploads with tus to `/api/upload?match_id=<game>` with the file name and the
|
||||
|
||||
Reference in new issue
Block a user