mirror of
https://github.com/Stirling-Tools/Stirling-PDF.git
synced 2025-09-24 04:26:14 +00:00
Compare commits
No commits in common. "668c47d5a09b8910875116cd7086f5d04a9bbefc" and "55b8455b66cbc40b30da36258e21f2241530b420" have entirely different histories.
668c47d5a0
...
55b8455b66
@ -5,6 +5,7 @@ import { useMetadataExtraction } from "../../../hooks/tools/changeMetadata/useMe
|
||||
import DeleteAllStep from "./steps/DeleteAllStep";
|
||||
import StandardMetadataStep from "./steps/StandardMetadataStep";
|
||||
import DocumentDatesStep from "./steps/DocumentDatesStep";
|
||||
import CustomMetadataStep from "./steps/CustomMetadataStep";
|
||||
import AdvancedOptionsStep from "./steps/AdvancedOptionsStep";
|
||||
|
||||
interface ChangeMetadataSingleStepProps {
|
||||
@ -26,10 +27,17 @@ const ChangeMetadataSingleStep = ({
|
||||
}: ChangeMetadataSingleStepProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// Extract metadata from uploaded files
|
||||
const { isExtractingMetadata } = useMetadataExtraction({
|
||||
// Create a params object that matches the hook interface
|
||||
const paramsHook = {
|
||||
parameters,
|
||||
updateParameter: onParameterChange,
|
||||
});
|
||||
addCustomMetadata,
|
||||
removeCustomMetadata,
|
||||
updateCustomMetadata,
|
||||
};
|
||||
|
||||
// Extract metadata from uploaded files
|
||||
const { isExtractingMetadata } = useMetadataExtraction(paramsHook);
|
||||
|
||||
const isDeleteAllEnabled = parameters.deleteAll;
|
||||
const fieldsDisabled = disabled || isDeleteAllEnabled || isExtractingMetadata;
|
||||
@ -78,6 +86,23 @@ const ChangeMetadataSingleStep = ({
|
||||
|
||||
<Divider />
|
||||
|
||||
{/* Custom Metadata */}
|
||||
<Stack gap="md">
|
||||
<Text size="sm" fw={500}>
|
||||
{t('changeMetadata.customFields.title', 'Custom Metadata')}
|
||||
</Text>
|
||||
<CustomMetadataStep
|
||||
parameters={parameters}
|
||||
onParameterChange={onParameterChange}
|
||||
disabled={fieldsDisabled}
|
||||
addCustomMetadata={addCustomMetadata}
|
||||
removeCustomMetadata={removeCustomMetadata}
|
||||
updateCustomMetadata={updateCustomMetadata}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Divider />
|
||||
|
||||
{/* Advanced Options */}
|
||||
<Stack gap="md">
|
||||
<Text size="sm" fw={500}>
|
||||
@ -87,9 +112,6 @@ const ChangeMetadataSingleStep = ({
|
||||
parameters={parameters}
|
||||
onParameterChange={onParameterChange}
|
||||
disabled={fieldsDisabled}
|
||||
addCustomMetadata={addCustomMetadata}
|
||||
removeCustomMetadata={removeCustomMetadata}
|
||||
updateCustomMetadata={updateCustomMetadata}
|
||||
/>
|
||||
</Stack>
|
||||
</Stack>
|
||||
|
@ -1,31 +1,22 @@
|
||||
import { Stack, Select, Divider } from "@mantine/core";
|
||||
import { Select } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ChangeMetadataParameters } from "../../../../hooks/tools/changeMetadata/useChangeMetadataParameters";
|
||||
import { TrappedStatus } from "../../../../types/metadata";
|
||||
import CustomMetadataStep from "./CustomMetadataStep";
|
||||
|
||||
interface AdvancedOptionsStepProps {
|
||||
parameters: ChangeMetadataParameters;
|
||||
onParameterChange: <K extends keyof ChangeMetadataParameters>(key: K, value: ChangeMetadataParameters[K]) => void;
|
||||
disabled?: boolean;
|
||||
addCustomMetadata: (key?: string, value?: string) => void;
|
||||
removeCustomMetadata: (id: string) => void;
|
||||
updateCustomMetadata: (id: string, key: string, value: string) => void;
|
||||
}
|
||||
|
||||
const AdvancedOptionsStep = ({
|
||||
parameters,
|
||||
onParameterChange,
|
||||
disabled = false,
|
||||
addCustomMetadata,
|
||||
removeCustomMetadata,
|
||||
updateCustomMetadata
|
||||
disabled = false
|
||||
}: AdvancedOptionsStepProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
{/* Trapped Status */}
|
||||
<Select
|
||||
label={t('changeMetadata.trapped.label', 'Trapped Status')}
|
||||
description={t('changeMetadata.trapped.description', 'Indicates whether the document has been trapped for high-quality printing')}
|
||||
@ -42,19 +33,6 @@ const AdvancedOptionsStep = ({
|
||||
{ value: TrappedStatus.FALSE, label: t('changeMetadata.trapped.false', 'False') }
|
||||
]}
|
||||
/>
|
||||
|
||||
<Divider />
|
||||
|
||||
{/* Custom Metadata */}
|
||||
<CustomMetadataStep
|
||||
parameters={parameters}
|
||||
onParameterChange={onParameterChange}
|
||||
disabled={disabled}
|
||||
addCustomMetadata={addCustomMetadata}
|
||||
removeCustomMetadata={removeCustomMetadata}
|
||||
updateCustomMetadata={updateCustomMetadata}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
|
@ -98,15 +98,6 @@ export const useAdvancedOptionsTips = (): TooltipContent => {
|
||||
t("changeMetadata.tooltip.advanced.trapped.bullet2", "False: Document has not been trapped"),
|
||||
t("changeMetadata.tooltip.advanced.trapped.bullet3", "Unknown: Trapped status is not specified")
|
||||
]
|
||||
},
|
||||
{
|
||||
title: t("changeMetadata.tooltip.customFields.title", "Custom Metadata"),
|
||||
description: t("changeMetadata.tooltip.customFields.text", "Add your own custom key-value metadata pairs."),
|
||||
bullets: [
|
||||
t("changeMetadata.tooltip.customFields.bullet1", "Add any custom fields relevant to your document"),
|
||||
t("changeMetadata.tooltip.customFields.bullet2", "Examples: Department, Project, Version, Status"),
|
||||
t("changeMetadata.tooltip.customFields.bullet3", "Both key and value are required for each entry")
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
@ -1,41 +1,28 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { extractPDFMetadata } from "../../../services/pdfMetadataService";
|
||||
import { useState, useEffect } from "react";
|
||||
import { PDFMetadataService } from "../../../services/pdfMetadataService";
|
||||
import { useSelectedFiles } from "../../../contexts/file/fileHooks";
|
||||
import { ChangeMetadataParameters } from "./useChangeMetadataParameters";
|
||||
import { ChangeMetadataParametersHook } from "./useChangeMetadataParameters";
|
||||
|
||||
interface MetadataExtractionParams {
|
||||
updateParameter: <K extends keyof ChangeMetadataParameters>(key: K, value: ChangeMetadataParameters[K]) => void;
|
||||
}
|
||||
|
||||
export const useMetadataExtraction = (params: MetadataExtractionParams) => {
|
||||
export const useMetadataExtraction = (params: ChangeMetadataParametersHook) => {
|
||||
const { selectedFiles } = useSelectedFiles();
|
||||
const [isExtractingMetadata, setIsExtractingMetadata] = useState(false);
|
||||
const [hasExtractedMetadata, setHasExtractedMetadata] = useState(false);
|
||||
const previousFileCountRef = useRef(0);
|
||||
|
||||
// Reset extraction state only when files are cleared (length goes to 0)
|
||||
useEffect(() => {
|
||||
if (previousFileCountRef.current > 0 && selectedFiles.length === 0) {
|
||||
setHasExtractedMetadata(false);
|
||||
}
|
||||
previousFileCountRef.current = selectedFiles.length;
|
||||
}, [selectedFiles]);
|
||||
|
||||
// Extract metadata from first file when files change
|
||||
useEffect(() => {
|
||||
const extractMetadata = async () => {
|
||||
if (selectedFiles.length === 0) {
|
||||
if (selectedFiles.length === 0 || hasExtractedMetadata) {
|
||||
return;
|
||||
}
|
||||
const firstFile = selectedFiles[0];
|
||||
|
||||
if (hasExtractedMetadata) {
|
||||
const firstFile = selectedFiles[0];
|
||||
if (!firstFile) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsExtractingMetadata(true);
|
||||
|
||||
const result = await extractPDFMetadata(firstFile);
|
||||
try {
|
||||
const result = await PDFMetadataService.extractMetadata(firstFile);
|
||||
|
||||
if (result.success) {
|
||||
const metadata = result.metadata;
|
||||
@ -50,14 +37,17 @@ export const useMetadataExtraction = (params: MetadataExtractionParams) => {
|
||||
params.updateParameter('creationDate', metadata.creationDate);
|
||||
params.updateParameter('modificationDate', metadata.modificationDate);
|
||||
params.updateParameter('trapped', metadata.trapped);
|
||||
|
||||
// Set custom metadata entries directly to avoid state update timing issues
|
||||
params.updateParameter('customMetadata', metadata.customMetadata);
|
||||
|
||||
setHasExtractedMetadata(true);
|
||||
} else {
|
||||
console.warn('Failed to extract metadata:', result.error);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.warn('Failed to extract metadata:', error);
|
||||
} finally {
|
||||
setIsExtractingMetadata(false);
|
||||
}
|
||||
};
|
||||
|
||||
extractMetadata();
|
||||
|
@ -1,7 +1,6 @@
|
||||
import { pdfWorkerManager } from './pdfWorkerManager';
|
||||
import { FileAnalyzer } from './fileAnalyzer';
|
||||
import { TrappedStatus, CustomMetadataEntry, ExtractedPDFMetadata } from '../types/metadata';
|
||||
import { PDFDocumentProxy } from 'pdfjs-dist/types/src/display/api';
|
||||
|
||||
export interface MetadataExtractionResult {
|
||||
success: true;
|
||||
@ -19,11 +18,12 @@ export type MetadataExtractionResponse = MetadataExtractionResult | MetadataExtr
|
||||
* Utility to format PDF date strings to required format (yyyy/MM/dd HH:mm:ss)
|
||||
* Handles PDF date format: "D:YYYYMMDDHHmmSSOHH'mm'" or standard date strings
|
||||
*/
|
||||
function formatPDFDate(dateString: string): string {
|
||||
if (!dateString) {
|
||||
function formatPDFDate(dateString: unknown): string {
|
||||
if (!dateString || typeof dateString !== 'string') {
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
let date: Date;
|
||||
|
||||
// Check if it's a PDF date format (starts with "D:")
|
||||
@ -58,6 +58,9 @@ function formatPDFDate(dateString: string): string {
|
||||
const seconds = String(date.getSeconds()).padStart(2, '0');
|
||||
|
||||
return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -77,14 +80,14 @@ function convertTrappedStatus(trapped: unknown): TrappedStatus {
|
||||
* Extract custom metadata fields from PDF.js info object
|
||||
* Custom metadata is nested under the "Custom" key
|
||||
*/
|
||||
function extractCustomMetadata(custom: unknown): CustomMetadataEntry[] {
|
||||
function extractCustomMetadata(info: Record<string, unknown>): CustomMetadataEntry[] {
|
||||
const customMetadata: CustomMetadataEntry[] = [];
|
||||
let customIdCounter = 1;
|
||||
|
||||
|
||||
// Check if there's a Custom object containing the custom metadata
|
||||
if (typeof custom === 'object' && custom !== null) {
|
||||
const customObj = custom as Record<string, unknown>;
|
||||
if (info.Custom && typeof info.Custom === 'object' && info.Custom !== null) {
|
||||
const customObj = info.Custom as Record<string, unknown>;
|
||||
|
||||
Object.entries(customObj).forEach(([key, value]) => {
|
||||
if (value != null && value !== '') {
|
||||
@ -102,31 +105,14 @@ function extractCustomMetadata(custom: unknown): CustomMetadataEntry[] {
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely cleanup PDF document with error handling
|
||||
* Service to extract metadata from PDF files using PDF.js
|
||||
*/
|
||||
function cleanupPdfDocument(pdfDoc: PDFDocumentProxy | null): void {
|
||||
if (pdfDoc) {
|
||||
try {
|
||||
pdfWorkerManager.destroyDocument(pdfDoc);
|
||||
} catch (cleanupError) {
|
||||
console.warn('Failed to cleanup PDF document:', cleanupError);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getStringMetadata(info: Record<string, unknown>, key: string): string {
|
||||
if (typeof info[key] === 'string') {
|
||||
return info[key];
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export class PDFMetadataService {
|
||||
/**
|
||||
* Extract all metadata from a PDF file
|
||||
* Returns a result object with success/error state
|
||||
*/
|
||||
export async function extractPDFMetadata(file: File): Promise<MetadataExtractionResponse> {
|
||||
static async extractMetadata(file: File): Promise<MetadataExtractionResponse> {
|
||||
// Use existing PDF validation
|
||||
const isValidPDF = await FileAnalyzer.isValidPDF(file);
|
||||
if (!isValidPDF) {
|
||||
@ -136,46 +122,54 @@ export async function extractPDFMetadata(file: File): Promise<MetadataExtraction
|
||||
};
|
||||
}
|
||||
|
||||
let pdfDoc: PDFDocumentProxy | null = null;
|
||||
let arrayBuffer: ArrayBuffer;
|
||||
let metadata;
|
||||
let pdfDoc: any = null;
|
||||
|
||||
try {
|
||||
arrayBuffer = await file.arrayBuffer();
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
pdfDoc = await pdfWorkerManager.createDocument(arrayBuffer, {
|
||||
disableAutoFetch: true,
|
||||
disableStream: true
|
||||
});
|
||||
metadata = await pdfDoc.getMetadata();
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||
cleanupPdfDocument(pdfDoc);
|
||||
return {
|
||||
success: false,
|
||||
error: `Failed to read PDF: ${errorMessage}`
|
||||
};
|
||||
}
|
||||
|
||||
const info = metadata.info as Record<string, unknown>;
|
||||
const metadata = await pdfDoc.getMetadata();
|
||||
const info = metadata.info || {};
|
||||
|
||||
// Safely extract metadata with proper type checking
|
||||
const extractedMetadata: ExtractedPDFMetadata = {
|
||||
title: getStringMetadata(info, 'Title'),
|
||||
author: getStringMetadata(info, 'Author'),
|
||||
subject: getStringMetadata(info, 'Subject'),
|
||||
keywords: getStringMetadata(info, 'Keywords'),
|
||||
creator: getStringMetadata(info, 'Creator'),
|
||||
producer: getStringMetadata(info, 'Producer'),
|
||||
creationDate: formatPDFDate(getStringMetadata(info, 'CreationDate')),
|
||||
modificationDate: formatPDFDate(getStringMetadata(info, 'ModDate')),
|
||||
title: typeof info.Title === 'string' ? info.Title : '',
|
||||
author: typeof info.Author === 'string' ? info.Author : '',
|
||||
subject: typeof info.Subject === 'string' ? info.Subject : '',
|
||||
keywords: typeof info.Keywords === 'string' ? info.Keywords : '',
|
||||
creator: typeof info.Creator === 'string' ? info.Creator : '',
|
||||
producer: typeof info.Producer === 'string' ? info.Producer : '',
|
||||
creationDate: formatPDFDate(info.CreationDate),
|
||||
modificationDate: formatPDFDate(info.ModDate),
|
||||
trapped: convertTrappedStatus(info.Trapped),
|
||||
customMetadata: extractCustomMetadata(info.Custom),
|
||||
customMetadata: extractCustomMetadata(info)
|
||||
};
|
||||
|
||||
cleanupPdfDocument(pdfDoc);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
metadata: extractedMetadata
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: `Failed to extract PDF metadata: ${errorMessage}`
|
||||
};
|
||||
|
||||
} finally {
|
||||
// Ensure cleanup even if extraction fails
|
||||
if (pdfDoc) {
|
||||
try {
|
||||
pdfWorkerManager.destroyDocument(pdfDoc);
|
||||
} catch (cleanupError) {
|
||||
console.warn('Failed to cleanup PDF document:', cleanupError);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -6,12 +6,11 @@
|
||||
*/
|
||||
|
||||
import * as pdfjsLib from 'pdfjs-dist';
|
||||
import { PDFDocumentProxy } from 'pdfjs-dist/types/src/display/api';
|
||||
const { getDocument, GlobalWorkerOptions } = pdfjsLib;
|
||||
|
||||
class PDFWorkerManager {
|
||||
private static instance: PDFWorkerManager;
|
||||
private activeDocuments = new Set<PDFDocumentProxy>();
|
||||
private activeDocuments = new Set<any>();
|
||||
private workerCount = 0;
|
||||
private maxWorkers = 10; // Limit concurrent workers
|
||||
private isInitialized = false;
|
||||
@ -49,7 +48,7 @@ class PDFWorkerManager {
|
||||
stopAtErrors?: boolean;
|
||||
verbosity?: number;
|
||||
} = {}
|
||||
): Promise<PDFDocumentProxy> {
|
||||
): Promise<any> {
|
||||
// Wait if we've hit the worker limit
|
||||
if (this.activeDocuments.size >= this.maxWorkers) {
|
||||
await this.waitForAvailableWorker();
|
||||
@ -105,7 +104,7 @@ class PDFWorkerManager {
|
||||
/**
|
||||
* Properly destroy a PDF document and clean up resources
|
||||
*/
|
||||
destroyDocument(pdf: PDFDocumentProxy): void {
|
||||
destroyDocument(pdf: any): void {
|
||||
if (this.activeDocuments.has(pdf)) {
|
||||
try {
|
||||
pdf.destroy();
|
||||
|
@ -1,9 +1,10 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { createToolFlow } from "../components/tools/shared/createToolFlow";
|
||||
import DeleteAllStep from "../components/tools/changeMetadata/steps/DeleteAllStep";
|
||||
import StandardMetadataStep from "../components/tools/changeMetadata/steps/StandardMetadataStep";
|
||||
import DocumentDatesStep from "../components/tools/changeMetadata/steps/DocumentDatesStep";
|
||||
import CustomMetadataStep from "../components/tools/changeMetadata/steps/CustomMetadataStep";
|
||||
import AdvancedOptionsStep from "../components/tools/changeMetadata/steps/AdvancedOptionsStep";
|
||||
import { useChangeMetadataParameters } from "../hooks/tools/changeMetadata/useChangeMetadataParameters";
|
||||
import { useChangeMetadataOperation } from "../hooks/tools/changeMetadata/useChangeMetadataOperation";
|
||||
@ -14,6 +15,7 @@ import {
|
||||
useDeleteAllTips,
|
||||
useStandardMetadataTips,
|
||||
useDocumentDatesTips,
|
||||
useCustomMetadataTips,
|
||||
useAdvancedOptionsTips
|
||||
} from "../components/tooltips/useChangeMetadataTips";
|
||||
|
||||
@ -24,12 +26,14 @@ const ChangeMetadata = (props: BaseToolProps) => {
|
||||
const deleteAllTips = useDeleteAllTips();
|
||||
const standardMetadataTips = useStandardMetadataTips();
|
||||
const documentDatesTips = useDocumentDatesTips();
|
||||
const customMetadataTips = useCustomMetadataTips();
|
||||
const advancedOptionsTips = useAdvancedOptionsTips();
|
||||
|
||||
// Individual step collapse states
|
||||
const [deleteAllCollapsed, setDeleteAllCollapsed] = useState(false);
|
||||
const [standardMetadataCollapsed, setStandardMetadataCollapsed] = useState(false);
|
||||
const [documentDatesCollapsed, setDocumentDatesCollapsed] = useState(true);
|
||||
const [customMetadataCollapsed, setCustomMetadataCollapsed] = useState(true);
|
||||
const [advancedOptionsCollapsed, setAdvancedOptionsCollapsed] = useState(true);
|
||||
|
||||
const base = useBaseTool(
|
||||
@ -98,6 +102,24 @@ const ChangeMetadata = (props: BaseToolProps) => {
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t("changeMetadata.customFields.title", "Custom Metadata"),
|
||||
isCollapsed: getActualCollapsedState(customMetadataCollapsed),
|
||||
onCollapsedClick: base.hasResults
|
||||
? (base.settingsCollapsed ? base.handleSettingsReset : undefined)
|
||||
: () => setCustomMetadataCollapsed(!customMetadataCollapsed),
|
||||
tooltip: customMetadataTips,
|
||||
content: (
|
||||
<CustomMetadataStep
|
||||
parameters={base.params.parameters}
|
||||
onParameterChange={base.params.updateParameter}
|
||||
disabled={base.endpointLoading || base.params.parameters.deleteAll || isExtractingMetadata}
|
||||
addCustomMetadata={base.params.addCustomMetadata}
|
||||
removeCustomMetadata={base.params.removeCustomMetadata}
|
||||
updateCustomMetadata={base.params.updateCustomMetadata}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t("changeMetadata.advanced.title", "Advanced Options"),
|
||||
isCollapsed: getActualCollapsedState(advancedOptionsCollapsed),
|
||||
@ -110,9 +132,6 @@ const ChangeMetadata = (props: BaseToolProps) => {
|
||||
parameters={base.params.parameters}
|
||||
onParameterChange={base.params.updateParameter}
|
||||
disabled={base.endpointLoading || isExtractingMetadata}
|
||||
addCustomMetadata={base.params.addCustomMetadata}
|
||||
removeCustomMetadata={base.params.removeCustomMetadata}
|
||||
updateCustomMetadata={base.params.updateCustomMetadata}
|
||||
/>
|
||||
),
|
||||
},
|
||||
|
Loading…
x
Reference in New Issue
Block a user