feat: run Velum project jobs in the background and process DOCX locally
This commit is contained in:
@@ -1,9 +1,10 @@
|
||||
import { Action, ActionPanel, Alert, confirmAlert, Form, Icon, List, showInFinder, showToast, Toast, useNavigation } from "@raycast/api";
|
||||
import { Action, ActionPanel, Alert, confirmAlert, Detail, Form, Icon, List, showInFinder, showToast, Toast, useNavigation } from "@raycast/api";
|
||||
import { promises as fs } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import { basename, dirname, extname, join } from "node:path";
|
||||
import { useEffect, useState } from "react";
|
||||
import { depseudonymizeDocument } from "./velum";
|
||||
import { restoreXlsxFile } from "./lib/xlsx-restoration";
|
||||
import { addProjectMappingEntry, canonicalProjectPath, digest, isMarkdownFile, listAllRuns, mappingForMatchingSnapshots, resolveWithin, restorePath, restoreTextWithCount, runCopiesPath, scanRestorableCopyFiles, unresolvedPlaceholderIds, updateProjectMapping, withUnambiguousHistoricalMappings } from "./lib/velum-project";
|
||||
import type { ProjectFile, ProjectRun } from "./lib/velum-project";
|
||||
import type { MappingEntry, PlaceholderMapping } from "./types";
|
||||
@@ -15,7 +16,7 @@ import { releaseProjectMapping } from "./project-mapping-actions";
|
||||
import { projectMappingCreatedAt } from "./lib/mapping-created-at";
|
||||
import { listRestorableFolders, selectRestorableFolder } from "./lib/restore-file-selection";
|
||||
import type { RestorableFolder } from "./lib/restore-file-selection";
|
||||
import { relocateProject } from "./lib/project-relocation";
|
||||
import { RelocateProjectForm } from "./project-relocation-form";
|
||||
|
||||
type SavedRun = { run: ProjectRun; directory: string };
|
||||
type RestoreDecision = MappingEntry | null;
|
||||
@@ -179,17 +180,21 @@ function RevisionReview(props: { saved: SavedRun; onSaved: () => Promise<void> }
|
||||
</List>;
|
||||
}
|
||||
|
||||
function FolderPicker(props: { folders: RestorableFolder[]; onSelect: (folder: string, includeDocuments: boolean) => void }) {
|
||||
function FolderPicker(props: { folders: RestorableFolder[]; onSelect: (folder: string, includeDocuments: boolean, restoreImmediately?: boolean) => void }) {
|
||||
const { pop } = useNavigation();
|
||||
function choose(folder: string, includeDocuments: boolean) {
|
||||
props.onSelect(folder, includeDocuments);
|
||||
function choose(folder: string, includeDocuments: boolean, restoreImmediately = false) {
|
||||
props.onSelect(folder, includeDocuments, restoreImmediately);
|
||||
pop();
|
||||
}
|
||||
return <List navigationTitle="Nur einen Ordner wiederherstellen" searchBarPlaceholder="Ordner suchen">
|
||||
<List.Section title="Ordner samt Unterordnern · Textdateien zuerst">
|
||||
<List.Section title="Ordner samt Unterordnern · Klartext-Kopien in Downloads/Velum">
|
||||
{props.folders.map((folder) => <List.Item key={folder.path} icon={Icon.Folder}
|
||||
title={folder.path} subtitle={`${folder.fileCount} Dateien · ${folder.textCount} Text · ${folder.documentCount} Office`}
|
||||
actions={<ActionPanel>
|
||||
<Action title={folder.documentCount > 0 ? "Ordner inklusive Office wiederherstellen" : "Ordner wiederherstellen"}
|
||||
icon={Icon.Download} onAction={() => choose(folder.path, true, true)} />
|
||||
{folder.documentCount > 0 && folder.textCount > 0 && <Action title="Nur Textdateien wiederherstellen"
|
||||
icon={Icon.Download} onAction={() => choose(folder.path, false, true)} />}
|
||||
{folder.textCount > 0 && <Action title="Nur Textdateien dieses Ordners auswählen" icon={Icon.CheckCircle}
|
||||
onAction={() => choose(folder.path, false)} />}
|
||||
{folder.documentCount > 0 && <Action title="Diesen Ordner inklusive Office auswählen" icon={Icon.Folder}
|
||||
@@ -207,6 +212,7 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
|
||||
const [skipped, setSkipped] = useState(0);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [unresolved, setUnresolved] = useState<Array<{ file: string; id: string }>>([]);
|
||||
const [exportError, setExportError] = useState<{ title: string; message: string }>();
|
||||
const [decisions, setDecisions] = useState<Record<string, Record<string, RestoreDecision>>>({});
|
||||
const mappings = [props.run.mapping, ...props.earlierRuns.map((entry) => entry.run.mapping)]
|
||||
.map(mappingForRestoration);
|
||||
@@ -234,8 +240,10 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
|
||||
setSelected(new Set(scan.files.filter((file) => file.kind === "text").map((file) => file.relPath)));
|
||||
setSkipped(scan.skipped);
|
||||
}
|
||||
load().catch((error: Error) => showToast({ style: Toast.Style.Failure,
|
||||
title: "Kopienordner nicht lesbar", message: error.message }));
|
||||
load().catch((error: Error) => {
|
||||
setExportError({ title: "Kopienordner nicht lesbar", message: error.message });
|
||||
return showToast({ style: Toast.Style.Failure, title: "Kopienordner nicht lesbar", message: error.message });
|
||||
});
|
||||
return () => { active = false; };
|
||||
}, [props.run, props.directory, props.historical]);
|
||||
function toggle(path: string) {
|
||||
@@ -246,36 +254,54 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
|
||||
return next;
|
||||
});
|
||||
}
|
||||
async function exportFiles() {
|
||||
async function exportFiles(selection = selected) {
|
||||
if (busy) return;
|
||||
if (!selected.size) {
|
||||
if (!selection.size) {
|
||||
await showToast({ style: Toast.Style.Failure, title: "Keine Dateien ausgewählt" });
|
||||
return;
|
||||
}
|
||||
if (!sourceRoot) return;
|
||||
setBusy(true);
|
||||
setExportError(undefined);
|
||||
const toast = await showToast({ style: Toast.Style.Animated, title: "Klartext-Kopien werden erstellt" });
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const parent = join(homedir(), "Downloads", "Velum");
|
||||
let targetRoot: string | undefined;
|
||||
let activeFile: string | undefined;
|
||||
try {
|
||||
if (!Object.keys(baseMapping).length && !Object.keys(decisions).length) {
|
||||
throw new Error("Dieser Projektstand hat keine Übersetzungstabelle.");
|
||||
}
|
||||
const names = new Set<string>();
|
||||
const planned = files.filter((item) => selected.has(item.relPath));
|
||||
const planned = files.filter((item) => selection.has(item.relPath));
|
||||
let renamedFiles = 0;
|
||||
let contentReplacements = 0;
|
||||
await fs.mkdir(parent, { recursive: true, mode: 0o700 });
|
||||
targetRoot = await fs.mkdtemp(join(parent, `${basename(props.run.projectName)}-${stamp}-`));
|
||||
for (const file of planned) {
|
||||
activeFile = file.relPath;
|
||||
toast.title = "Datei wird wiederhergestellt";
|
||||
toast.message = file.relPath;
|
||||
const source = resolveWithin(sourceRoot, file.relPath);
|
||||
if (!(await fs.lstat(source)).isFile()) throw new Error(`Keine reguläre Datei: ${file.relPath}`);
|
||||
const data = await fs.readFile(source);
|
||||
const mapping: PlaceholderMapping = { ...baseMapping };
|
||||
const manual = decisions[file.relPath] ?? {};
|
||||
for (const [id, entry] of Object.entries(manual)) if (entry) mapping[id] = entry;
|
||||
let restoredName = restorePath(file.relPath, mapping, props.run.matchModes);
|
||||
if (file.kind === "document" && extname(file.relPath).toLowerCase() === ".xlsx") {
|
||||
if (names.has(restoredName)) throw new Error(`Mehrdeutiger Ausgabename: ${restoredName}`);
|
||||
names.add(restoredName);
|
||||
if (restoredName !== file.relPath) renamedFiles++;
|
||||
const target = resolveWithin(targetRoot, restoredName);
|
||||
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
||||
const restored = await restoreXlsxFile(source, target, mapping, (percent) => {
|
||||
toast.title = `Excel wird lokal wiederhergestellt · ${percent} %`;
|
||||
toast.message = file.relPath;
|
||||
});
|
||||
contentReplacements += restored.replacements;
|
||||
continue;
|
||||
}
|
||||
const data = await fs.readFile(source);
|
||||
let result: Buffer;
|
||||
if (file.kind === "document") {
|
||||
result = await depseudonymizeDocument(basename(file.relPath), data, mapping);
|
||||
@@ -317,12 +343,12 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
|
||||
}
|
||||
setUnresolved([]);
|
||||
toast.style = Toast.Style.Success;
|
||||
toast.title = `${selected.size} Klartext-Dateien in Downloads`;
|
||||
toast.title = `${selection.size} Klartext-Dateien in Downloads`;
|
||||
const deliberatelyKept = planned.reduce((count, file) => count
|
||||
+ Object.values(decisions[file.relPath] ?? {}).filter((entry) => entry === null).length, 0);
|
||||
toast.message = `${contentReplacements} Textersetzungen · ${renamedFiles} Dateinamen geändert`
|
||||
+ (deliberatelyKept ? ` · ${deliberatelyKept} Platzhalter bewusst belassen` : "")
|
||||
+ (planned.some((file) => file.kind === "document") ? " · Office-Inhalte nicht gezählt" : "");
|
||||
+ (planned.some((file) => file.kind === "document" && extname(file.relPath).toLowerCase() !== ".xlsx") ? " · DOCX/PPTX-Inhalte nicht gezählt" : "");
|
||||
await showInFinder(targetRoot).catch(() => undefined);
|
||||
} catch (error) {
|
||||
if (targetRoot) await fs.rm(targetRoot, { recursive: true, force: true });
|
||||
@@ -331,15 +357,19 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
|
||||
toast.title = error instanceof UnresolvedRestoreError ? "Platzhalter zuordnen" : "Klartext-Export fehlgeschlagen";
|
||||
toast.message = error instanceof UnresolvedRestoreError
|
||||
? `${error.file}: ${error.ids.join(", ")}. Bitte die Einträge unten klären und den Export erneut starten.`
|
||||
: (error as Error).message;
|
||||
: `${activeFile ? activeFile + ": " : ""}${error instanceof Error ? error.message : String(error)}`;
|
||||
setExportError({ title: toast.title, message: toast.message });
|
||||
} finally { setBusy(false); }
|
||||
}
|
||||
const textFiles = files.filter((file) => file.kind === "text");
|
||||
const complexFiles = files.filter((file) => file.kind === "document");
|
||||
const folders = listRestorableFolders(files);
|
||||
const allSelected = files.length > 0 && selected.size === files.length;
|
||||
const selectOnlyFolder = (folder: string, includeDocuments = false) =>
|
||||
setSelected(selectRestorableFolder(files, folder, includeDocuments));
|
||||
const selectOnlyFolder = (folder: string, includeDocuments = false, restoreImmediately = false) => {
|
||||
const selection = selectRestorableFolder(files, folder, includeDocuments);
|
||||
setSelected(selection);
|
||||
if (restoreImmediately) void exportFiles(selection);
|
||||
};
|
||||
const openFolderPicker = () => push(<FolderPicker folders={folders} onSelect={selectOnlyFolder} />);
|
||||
const selectionActions = () => <ActionPanel.Section title="Dateiauswahl">
|
||||
<Action title={allSelected ? "Alle Dateien abwählen" : "Alle Dateien auswählen (inklusive Office)"}
|
||||
@@ -363,24 +393,37 @@ function FilePicker(props: { run: ProjectRun; directory: string; historical?: bo
|
||||
accessories={file.kind === "document" ? [{ text: "Office · manuell auswählen" }] : []}
|
||||
actions={<ActionPanel>
|
||||
<Action title={selected.has(file.relPath) ? "Datei abwählen" : "Datei auswählen"} onAction={() => toggle(file.relPath)} />
|
||||
<Action title="Auswahl nach Downloads wiederherstellen" icon={Icon.Download} onAction={exportFiles} />
|
||||
<Action title="Auswahl nach Downloads wiederherstellen" icon={Icon.Download} onAction={() => exportFiles()} />
|
||||
{fileFolder && <Action title={fileFolder.textCount > 0
|
||||
? "Nur Textdateien dieses Ordners auswählen" : "Diesen Ordner inklusive Office auswählen"}
|
||||
icon={Icon.Folder} onAction={() => selectOnlyFolder(fileFolder.path, fileFolder.textCount === 0)} />}
|
||||
{selectionActions()}
|
||||
</ActionPanel>} />;
|
||||
};
|
||||
return <List isLoading={busy || !sourceRoot} navigationTitle={`${props.run.projectName}: Dateien für Klartext wählen`}
|
||||
return <List isLoading={busy || (!sourceRoot && !exportError)} navigationTitle={`${props.run.projectName}: Dateien für Klartext wählen`}
|
||||
searchBarPlaceholder="Dateien filtern">
|
||||
<List.Section title={`${selected.size} von ${files.length} Dateien ausgewählt · ${skipped} übersprungen`}>
|
||||
<List.Item key="export" icon={Icon.Download} title="Ausgewählte Dateien wiederherstellen"
|
||||
subtitle="Klartext-Kopien in Downloads/Velum erstellen · Office-Dateien nur nach Auswahl"
|
||||
actions={<ActionPanel><Action title="Auswahl nach Downloads wiederherstellen"
|
||||
icon={Icon.Download} onAction={exportFiles} />{selectionActions()}</ActionPanel>} />
|
||||
icon={Icon.Download} onAction={() => exportFiles()} />{selectionActions()}</ActionPanel>} />
|
||||
{folders.length > 0 && <List.Item key="folders" icon={Icon.Folder}
|
||||
title="Einzelnen Ordner wiederherstellen"
|
||||
subtitle={`${folders.length} Ordner · jeweils inklusive Unterordnern`}
|
||||
actions={<ActionPanel><Action title="Ordner zur Wiederherstellung wählen" icon={Icon.Folder}
|
||||
onAction={openFolderPicker} />{selectionActions()}</ActionPanel>} />}
|
||||
<List.Item key="source" icon={Icon.Folder} title={sourceLabel} subtitle={sourceRoot}
|
||||
actions={<ActionPanel><Action title="Quellordner im Finder anzeigen" onAction={() => showInFinder(sourceRoot)} />
|
||||
{selectionActions()}</ActionPanel>} />
|
||||
</List.Section>
|
||||
{exportError && <List.Section title={exportError.title}>
|
||||
<List.Item icon={Icon.ExclamationMark} title="Fehlerdetails anzeigen" subtitle={exportError.message}
|
||||
keywords={files.map((file) => file.relPath)} actions={<ActionPanel>
|
||||
<Action.Push title="Fehlerdetails anzeigen" target={<Detail markdown={exportError.message.replace(/</g, "<")} />} />
|
||||
<Action.CopyToClipboard title="Fehlermeldung kopieren" content={exportError.message} />
|
||||
<Action title="Wiederherstellung erneut starten" icon={Icon.Download} onAction={() => exportFiles()} />
|
||||
</ActionPanel>} />
|
||||
</List.Section>}
|
||||
{unresolved.some((item) => selected.has(item.file)) && <List.Section title="Platzhalter für diesen Export klären">
|
||||
{unresolved.filter((item) => selected.has(item.file)).map(({ file, id }) => {
|
||||
const candidates = candidatesFor(id);
|
||||
@@ -429,47 +472,6 @@ function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) {
|
||||
</List>;
|
||||
}
|
||||
|
||||
function RelocateProjectForm(props: { projectName: string; oldPath: string; onMoved: () => Promise<void> }) {
|
||||
const { pop } = useNavigation();
|
||||
const [busy, setBusy] = useState(false);
|
||||
async function save(values: { newPath: string[] }) {
|
||||
const newPath = values.newPath[0];
|
||||
if (!newPath) {
|
||||
await showToast({ style: Toast.Style.Failure, title: "Bitte den neuen Projektordner wählen" });
|
||||
return;
|
||||
}
|
||||
if (!(await confirmAlert({
|
||||
title: "Projektordner aktualisieren?",
|
||||
message: `Alle gespeicherten Projektstände und Regeln werden künftig ${newPath} zugeordnet. `
|
||||
+ `Bisheriger Pfad: ${props.oldPath}. Die Dateien im gewählten Ordner werden nicht verändert.`,
|
||||
primaryAction: { title: "Projektpfad aktualisieren" },
|
||||
}))) return;
|
||||
setBusy(true);
|
||||
const toast = await showToast({ style: Toast.Style.Animated, title: "Projektpfad wird aktualisiert" });
|
||||
try {
|
||||
const result = await relocateProject(props.oldPath, newPath);
|
||||
await props.onMoved();
|
||||
toast.style = Toast.Style.Success;
|
||||
toast.title = "Projektordner aktualisiert";
|
||||
toast.message = `${result.runsMoved} Projektstände übernommen`
|
||||
+ (result.copiesRelinked ? ` · ${result.copiesRelinked} Kopienordner neu gefunden` : "")
|
||||
+ (result.copiesMissing ? ` · ${result.copiesMissing} Kopienordner nicht gefunden; gespeicherte Stände bleiben verfügbar` : "");
|
||||
pop();
|
||||
} catch (error) {
|
||||
toast.style = Toast.Style.Failure;
|
||||
toast.title = "Projektpfad nicht aktualisiert";
|
||||
toast.message = (error as Error).message;
|
||||
} finally { setBusy(false); }
|
||||
}
|
||||
return <Form isLoading={busy} navigationTitle={`${props.projectName}: Projektordner ändern`}
|
||||
actions={<ActionPanel><Action.SubmitForm title="Projektpfad aktualisieren" icon={Icon.Folder}
|
||||
onSubmit={save} /></ActionPanel>}>
|
||||
<Form.Description title="Bisheriger Projektordner" text={props.oldPath} />
|
||||
<Form.FilePicker id="newPath" title="Neuer Projektordner" allowMultipleSelection={false}
|
||||
canChooseDirectories canChooseFiles={false} />
|
||||
<Form.Description text="Gespeicherte Stände, Ausnahmen und Projektbegriffe bleiben erhalten. Dateien im neuen Ordner werden weder analysiert noch geändert." />
|
||||
</Form>;
|
||||
}
|
||||
|
||||
export default function Command() {
|
||||
const { push } = useNavigation();
|
||||
|
||||
Reference in New Issue
Block a user