mirror of
https://github.com/arsvendg/Stirling-PDF.git
synced 2026-07-16 11:23:10 +02:00
fileshare (#5414)
Co-authored-by: ConnorYoh <[email protected]> Co-authored-by: Connor Yoh <[email protected]> Co-authored-by: EthanHealy01 <[email protected]> Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
ConnorYoh
Connor Yoh
EthanHealy01
Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
parent
47cad0a131
commit
28613caf8a
@@ -0,0 +1,93 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import apiClient from '@app/services/apiClient';
|
||||
import { alert } from '@app/components/toast';
|
||||
import { SignRequestSummary, SessionSummary } from '@app/types/signingSession';
|
||||
|
||||
export interface UseSigningSessionsOptions {
|
||||
enabled?: boolean;
|
||||
autoRefreshInterval?: number; // milliseconds, 0 to disable
|
||||
}
|
||||
|
||||
export interface UseSigningSessionsResult {
|
||||
signRequests: SignRequestSummary[];
|
||||
mySessions: SessionSummary[];
|
||||
loading: boolean;
|
||||
error: Error | null;
|
||||
refetch: () => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fetch signing sessions data (sign requests and user's sessions).
|
||||
* Supports auto-refresh for real-time updates.
|
||||
*/
|
||||
export const useSigningSessions = (
|
||||
options: UseSigningSessionsOptions = {}
|
||||
): UseSigningSessionsResult => {
|
||||
const { enabled = true, autoRefreshInterval = 0 } = options;
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [signRequests, setSignRequests] = useState<SignRequestSummary[]>([]);
|
||||
const [mySessions, setMySessions] = useState<SessionSummary[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
if (!enabled) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const [requestsResponse, sessionsResponse] = await Promise.all([
|
||||
apiClient.get<SignRequestSummary[]>('/api/v1/security/cert-sign/sign-requests'),
|
||||
apiClient.get<SessionSummary[]>('/api/v1/security/cert-sign/sessions'),
|
||||
]);
|
||||
|
||||
setSignRequests(requestsResponse.data);
|
||||
setMySessions(sessionsResponse.data);
|
||||
} catch (err) {
|
||||
const errorObj = err instanceof Error ? err : new Error('Failed to fetch signing data');
|
||||
setError(errorObj);
|
||||
console.error('Failed to fetch signing data:', err);
|
||||
|
||||
alert({
|
||||
alertType: 'warning',
|
||||
title: t('common.error'),
|
||||
body: t('certSign.fetchFailed', 'Failed to load signing data'),
|
||||
expandable: false,
|
||||
durationMs: 2500,
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [enabled, t]);
|
||||
|
||||
// Initial fetch
|
||||
useEffect(() => {
|
||||
if (enabled) {
|
||||
fetchData();
|
||||
}
|
||||
}, [enabled, fetchData]);
|
||||
|
||||
// Auto-refresh
|
||||
useEffect(() => {
|
||||
if (!enabled || !autoRefreshInterval || autoRefreshInterval <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const interval = setInterval(() => {
|
||||
fetchData();
|
||||
}, autoRefreshInterval);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [enabled, autoRefreshInterval, fetchData]);
|
||||
|
||||
return {
|
||||
signRequests,
|
||||
mySessions,
|
||||
loading,
|
||||
error,
|
||||
refetch: fetchData,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useToolWorkflow } from '@app/contexts/ToolWorkflowContext';
|
||||
import SignRequestWorkbenchView from '@app/components/tools/certSign/SignRequestWorkbenchView';
|
||||
import SessionDetailWorkbenchView from '@app/components/tools/certSign/SessionDetailWorkbenchView';
|
||||
|
||||
export interface WorkbenchRegistration {
|
||||
id: string;
|
||||
workbenchId: string;
|
||||
label: string;
|
||||
component: React.ComponentType<any>;
|
||||
}
|
||||
|
||||
export interface UseSigningWorkbenchResult {
|
||||
signRequestWorkbench: {
|
||||
id: string;
|
||||
type: string;
|
||||
};
|
||||
sessionDetailWorkbench: {
|
||||
id: string;
|
||||
type: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to manage custom workbench registration for signing workflows.
|
||||
* Automatically registers and unregisters workbenches on mount/unmount.
|
||||
*/
|
||||
export const useSigningWorkbench = (): UseSigningWorkbenchResult => {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
registerCustomWorkbenchView,
|
||||
unregisterCustomWorkbenchView,
|
||||
} = useToolWorkflow();
|
||||
|
||||
// Define workbench IDs as constants
|
||||
const SIGN_REQUEST_WORKBENCH_ID = 'signRequestWorkbench';
|
||||
const SIGN_REQUEST_WORKBENCH_TYPE = 'custom:signRequestWorkbench' as const;
|
||||
const SESSION_DETAIL_WORKBENCH_ID = 'sessionDetailWorkbench';
|
||||
const SESSION_DETAIL_WORKBENCH_TYPE = 'custom:sessionDetailWorkbench' as const;
|
||||
|
||||
// Register workbenches on mount
|
||||
useEffect(() => {
|
||||
registerCustomWorkbenchView({
|
||||
id: SIGN_REQUEST_WORKBENCH_ID,
|
||||
workbenchId: SIGN_REQUEST_WORKBENCH_TYPE,
|
||||
label: t('certSign.collab.signRequest.workbenchTitle', 'Sign Request'),
|
||||
component: SignRequestWorkbenchView,
|
||||
});
|
||||
|
||||
registerCustomWorkbenchView({
|
||||
id: SESSION_DETAIL_WORKBENCH_ID,
|
||||
workbenchId: SESSION_DETAIL_WORKBENCH_TYPE,
|
||||
label: t('certSign.collab.sessionDetail.workbenchTitle', 'Session Management'),
|
||||
component: SessionDetailWorkbenchView,
|
||||
});
|
||||
|
||||
return () => {
|
||||
unregisterCustomWorkbenchView(SIGN_REQUEST_WORKBENCH_ID);
|
||||
unregisterCustomWorkbenchView(SESSION_DETAIL_WORKBENCH_ID);
|
||||
};
|
||||
}, [registerCustomWorkbenchView, unregisterCustomWorkbenchView, t]);
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
signRequestWorkbench: {
|
||||
id: SIGN_REQUEST_WORKBENCH_ID,
|
||||
type: SIGN_REQUEST_WORKBENCH_TYPE,
|
||||
},
|
||||
sessionDetailWorkbench: {
|
||||
id: SESSION_DETAIL_WORKBENCH_ID,
|
||||
type: SESSION_DETAIL_WORKBENCH_TYPE,
|
||||
},
|
||||
}),
|
||||
[]
|
||||
);
|
||||
};
|
||||
@@ -3,10 +3,74 @@ import { useIndexedDB } from '@app/contexts/IndexedDBContext';
|
||||
import { fileStorage } from '@app/services/fileStorage';
|
||||
import { StirlingFileStub, StirlingFile } from '@app/types/fileContext';
|
||||
import { FileId } from '@app/types/fileContext';
|
||||
import apiClient from '@app/services/apiClient';
|
||||
import { useAppConfig } from '@app/contexts/AppConfigContext';
|
||||
|
||||
interface StoredFileResponse {
|
||||
id: number;
|
||||
fileName: string;
|
||||
contentType?: string | null;
|
||||
sizeBytes: number;
|
||||
createdAt?: string | null;
|
||||
updatedAt?: string | null;
|
||||
owner?: string | null;
|
||||
ownedByCurrentUser?: boolean;
|
||||
accessRole?: string | null;
|
||||
shareLinks?: Array<{ token?: string | null }>;
|
||||
sharedWithUsers?: string[];
|
||||
filePurpose?: string | null;
|
||||
}
|
||||
|
||||
interface AccessedShareLinkResponse {
|
||||
shareToken?: string | null;
|
||||
fileId?: number | null;
|
||||
fileName?: string | null;
|
||||
owner?: string | null;
|
||||
ownedByCurrentUser?: boolean;
|
||||
createdAt?: string | null;
|
||||
lastAccessedAt?: string | null;
|
||||
}
|
||||
|
||||
export const useFileManager = () => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const indexedDB = useIndexedDB();
|
||||
const { config } = useAppConfig();
|
||||
|
||||
const normalizeServerFileName = useCallback((fileName: string | undefined | null): string => {
|
||||
const fallback = fileName?.trim() || 'server-file';
|
||||
const lowerName = fallback.toLowerCase();
|
||||
const historySuffix = '-history.zip';
|
||||
if (lowerName.endsWith(historySuffix)) {
|
||||
return fallback.slice(0, fallback.length - historySuffix.length) || fallback;
|
||||
}
|
||||
if (lowerName.endsWith('.zip')) {
|
||||
const knownInnerExt = [
|
||||
'pdf',
|
||||
'doc',
|
||||
'docx',
|
||||
'ppt',
|
||||
'pptx',
|
||||
'xls',
|
||||
'xlsx',
|
||||
'png',
|
||||
'jpg',
|
||||
'jpeg',
|
||||
'tif',
|
||||
'tiff',
|
||||
'txt',
|
||||
'csv',
|
||||
'rtf',
|
||||
'html',
|
||||
'epub',
|
||||
];
|
||||
for (const ext of knownInnerExt) {
|
||||
if (lowerName.endsWith(`.${ext}.zip`)) {
|
||||
return fallback.slice(0, fallback.length - 4) || fallback;
|
||||
}
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}, []);
|
||||
|
||||
const convertToFile = useCallback(async (fileStub: StirlingFileStub): Promise<File> => {
|
||||
if (!indexedDB) {
|
||||
@@ -32,9 +96,237 @@ export const useFileManager = () => {
|
||||
|
||||
// Load only leaf files metadata (processed files that haven't been used as input for other tools)
|
||||
const stirlingFileStubs = await fileStorage.getLeafStirlingFileStubs();
|
||||
const remoteIdSet = new Set(
|
||||
stirlingFileStubs
|
||||
.map((stub) => stub.remoteStorageId)
|
||||
.filter((id): id is number => typeof id === 'number')
|
||||
);
|
||||
let combinedStubs = stirlingFileStubs;
|
||||
|
||||
const shouldFetchServerFiles = config?.storageEnabled === true;
|
||||
|
||||
if (shouldFetchServerFiles) {
|
||||
try {
|
||||
const response = await apiClient.get<StoredFileResponse[]>(
|
||||
'/api/v1/storage/files',
|
||||
{ suppressErrorToast: true, skipAuthRedirect: true } as any
|
||||
);
|
||||
const serverFiles = Array.isArray(response.data) ? response.data : [];
|
||||
const serverStubs: StirlingFileStub[] = [];
|
||||
const serverMap = new Map<number, StoredFileResponse>();
|
||||
serverFiles.forEach((file) => {
|
||||
if (file && typeof file.id === 'number') {
|
||||
serverMap.set(file.id, file);
|
||||
}
|
||||
});
|
||||
|
||||
const updatedLocalStubs = stirlingFileStubs.map((stub) => {
|
||||
if (!stub.remoteStorageId) {
|
||||
return stub;
|
||||
}
|
||||
const serverFile = serverMap.get(stub.remoteStorageId);
|
||||
if (!serverFile) {
|
||||
if (stub.remoteSharedViaLink) {
|
||||
return {
|
||||
...stub,
|
||||
remoteOwnedByCurrentUser: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...stub,
|
||||
remoteStorageId: undefined,
|
||||
remoteStorageUpdatedAt: undefined,
|
||||
remoteOwnerUsername: undefined,
|
||||
remoteOwnedByCurrentUser: undefined,
|
||||
remoteAccessRole: undefined,
|
||||
remoteSharedViaLink: false,
|
||||
remoteHasShareLinks: undefined,
|
||||
};
|
||||
}
|
||||
// If this server file is a signing-workflow file, detach it from the file manager
|
||||
if (serverFile.filePurpose && serverFile.filePurpose !== 'generic') {
|
||||
return {
|
||||
...stub,
|
||||
remoteStorageId: undefined,
|
||||
remoteStorageUpdatedAt: undefined,
|
||||
remoteOwnerUsername: undefined,
|
||||
remoteOwnedByCurrentUser: undefined,
|
||||
remoteAccessRole: undefined,
|
||||
remoteSharedViaLink: false,
|
||||
remoteHasShareLinks: undefined,
|
||||
};
|
||||
}
|
||||
const updatedAtMs = serverFile.updatedAt
|
||||
? new Date(serverFile.updatedAt).getTime()
|
||||
: serverFile.createdAt
|
||||
? new Date(serverFile.createdAt).getTime()
|
||||
: undefined;
|
||||
return {
|
||||
...stub,
|
||||
remoteOwnerUsername: serverFile.owner ?? stub.remoteOwnerUsername,
|
||||
remoteOwnedByCurrentUser:
|
||||
typeof serverFile.ownedByCurrentUser === 'boolean'
|
||||
? serverFile.ownedByCurrentUser
|
||||
: stub.remoteOwnedByCurrentUser,
|
||||
remoteAccessRole: serverFile.accessRole ?? stub.remoteAccessRole,
|
||||
remoteSharedViaLink: stub.remoteSharedViaLink,
|
||||
remoteHasShareLinks: Boolean(serverFile.shareLinks?.length),
|
||||
remoteStorageUpdatedAt:
|
||||
typeof updatedAtMs === 'number' && Number.isFinite(updatedAtMs)
|
||||
? updatedAtMs
|
||||
: stub.remoteStorageUpdatedAt,
|
||||
};
|
||||
});
|
||||
|
||||
for (const file of serverFiles) {
|
||||
if (!file || typeof file.id !== 'number') {
|
||||
continue;
|
||||
}
|
||||
if (remoteIdSet.has(file.id)) {
|
||||
continue;
|
||||
}
|
||||
// Skip signing-workflow files — only accessible via SignPopout
|
||||
if (file.filePurpose && file.filePurpose !== 'generic') {
|
||||
continue;
|
||||
}
|
||||
const updatedAtMs = file.updatedAt
|
||||
? new Date(file.updatedAt).getTime()
|
||||
: file.createdAt
|
||||
? new Date(file.createdAt).getTime()
|
||||
: Date.now();
|
||||
const name = normalizeServerFileName(file.fileName);
|
||||
const lastModified = Number.isFinite(updatedAtMs) ? updatedAtMs : Date.now();
|
||||
const id = `server-${file.id}` as FileId;
|
||||
serverStubs.push({
|
||||
id,
|
||||
name,
|
||||
type: file.contentType || 'application/octet-stream',
|
||||
size: file.sizeBytes ?? 0,
|
||||
lastModified,
|
||||
createdAt: lastModified,
|
||||
isLeaf: true,
|
||||
originalFileId: id,
|
||||
versionNumber: 1,
|
||||
toolHistory: [],
|
||||
quickKey: `${name}|${file.sizeBytes ?? 0}|${lastModified}`,
|
||||
remoteStorageId: file.id,
|
||||
remoteStorageUpdatedAt: lastModified,
|
||||
remoteOwnerUsername: file.owner ?? undefined,
|
||||
remoteOwnedByCurrentUser:
|
||||
typeof file.ownedByCurrentUser === 'boolean'
|
||||
? file.ownedByCurrentUser
|
||||
: undefined,
|
||||
remoteAccessRole: file.accessRole ?? undefined,
|
||||
remoteSharedViaLink: false,
|
||||
remoteHasShareLinks: Boolean(file.shareLinks?.length),
|
||||
});
|
||||
}
|
||||
|
||||
combinedStubs = [...updatedLocalStubs, ...serverStubs];
|
||||
} catch (error) {
|
||||
console.warn('Failed to load server files:', error);
|
||||
}
|
||||
|
||||
if (config?.storageShareLinksEnabled === true) {
|
||||
try {
|
||||
const sharedResponse = await apiClient.get<AccessedShareLinkResponse[]>(
|
||||
'/api/v1/storage/share-links/accessed',
|
||||
{ suppressErrorToast: true, skipAuthRedirect: true } as any
|
||||
);
|
||||
const sharedLinks = Array.isArray(sharedResponse.data) ? sharedResponse.data : [];
|
||||
const allowedShareTokens = new Set(
|
||||
sharedLinks
|
||||
.map((link) => link.shareToken)
|
||||
.filter((token): token is string => Boolean(token))
|
||||
);
|
||||
const shareClearUpdates: Array<Promise<boolean>> = [];
|
||||
combinedStubs = combinedStubs.map((stub) => {
|
||||
if (
|
||||
stub.remoteSharedViaLink &&
|
||||
stub.remoteShareToken &&
|
||||
!allowedShareTokens.has(stub.remoteShareToken)
|
||||
) {
|
||||
const cleared = {
|
||||
...stub,
|
||||
remoteStorageId: undefined,
|
||||
remoteStorageUpdatedAt: undefined,
|
||||
remoteOwnerUsername: undefined,
|
||||
remoteOwnedByCurrentUser: undefined,
|
||||
remoteSharedViaLink: false,
|
||||
remoteHasShareLinks: undefined,
|
||||
remoteShareToken: undefined,
|
||||
};
|
||||
shareClearUpdates.push(
|
||||
fileStorage.updateFileMetadata(stub.id, {
|
||||
remoteStorageId: undefined,
|
||||
remoteStorageUpdatedAt: undefined,
|
||||
remoteOwnerUsername: undefined,
|
||||
remoteOwnedByCurrentUser: undefined,
|
||||
remoteSharedViaLink: false,
|
||||
remoteHasShareLinks: undefined,
|
||||
remoteShareToken: undefined,
|
||||
})
|
||||
);
|
||||
return cleared;
|
||||
}
|
||||
return stub;
|
||||
});
|
||||
if (shareClearUpdates.length > 0) {
|
||||
await Promise.all(shareClearUpdates);
|
||||
}
|
||||
const existingShareTokens = new Set(
|
||||
combinedStubs
|
||||
.map((stub) => stub.remoteShareToken)
|
||||
.filter((token): token is string => Boolean(token))
|
||||
);
|
||||
const sharedStubs: StirlingFileStub[] = [];
|
||||
|
||||
for (const link of sharedLinks) {
|
||||
if (!link || !link.shareToken) {
|
||||
continue;
|
||||
}
|
||||
if (existingShareTokens.has(link.shareToken)) {
|
||||
continue;
|
||||
}
|
||||
const createdAtMs = link.lastAccessedAt
|
||||
? new Date(link.lastAccessedAt).getTime()
|
||||
: link.createdAt
|
||||
? new Date(link.createdAt).getTime()
|
||||
: Date.now();
|
||||
const lastModified = Number.isFinite(createdAtMs) ? createdAtMs : Date.now();
|
||||
const name = normalizeServerFileName(link.fileName || 'shared-file');
|
||||
const id = `shared-${link.shareToken}` as FileId;
|
||||
sharedStubs.push({
|
||||
id,
|
||||
name,
|
||||
type: 'application/octet-stream',
|
||||
size: 0,
|
||||
lastModified,
|
||||
createdAt: lastModified,
|
||||
isLeaf: true,
|
||||
originalFileId: id,
|
||||
versionNumber: 1,
|
||||
toolHistory: [],
|
||||
quickKey: `${name}|0|${lastModified}`,
|
||||
remoteStorageId: link.fileId ?? undefined,
|
||||
remoteStorageUpdatedAt: lastModified,
|
||||
remoteOwnerUsername: link.owner ?? undefined,
|
||||
remoteOwnedByCurrentUser: false,
|
||||
remoteSharedViaLink: true,
|
||||
remoteHasShareLinks: false,
|
||||
remoteShareToken: link.shareToken,
|
||||
});
|
||||
}
|
||||
|
||||
combinedStubs = [...combinedStubs, ...sharedStubs];
|
||||
} catch (error) {
|
||||
console.warn('Failed to load shared links:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// For now, only regular files - drafts will be handled separately in the future
|
||||
const sortedFiles = stirlingFileStubs.sort((a, b) => (b.lastModified || 0) - (a.lastModified || 0));
|
||||
const sortedFiles = combinedStubs.sort((a, b) => (b.lastModified || 0) - (a.lastModified || 0));
|
||||
|
||||
return sortedFiles;
|
||||
} catch (error) {
|
||||
@@ -43,7 +335,7 @@ export const useFileManager = () => {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [indexedDB]);
|
||||
}, [indexedDB, config?.enableLogin, config?.storageEnabled, config?.storageShareLinksEnabled, normalizeServerFileName]);
|
||||
|
||||
const handleRemoveFile = useCallback(async (index: number, files: StirlingFileStub[], setFiles: (files: StirlingFileStub[]) => void) => {
|
||||
const file = files[index];
|
||||
|
||||
@@ -7,3 +7,11 @@ import { useMediaQuery } from '@mantine/hooks';
|
||||
export const useIsMobile = (): boolean => {
|
||||
return useMediaQuery('(max-width: 1024px)') ?? false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Custom hook to detect phone-sized viewport (≤768px)
|
||||
* Use for layouts that need a more compact single-column arrangement
|
||||
*/
|
||||
export const useIsPhone = (): boolean => {
|
||||
return useMediaQuery('(max-width: 768px)') ?? false;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user