Files
FEDEO/mobile/src/lib/file-opening.ts

39 lines
1.4 KiB
TypeScript

import { File, Paths } from 'expo-file-system';
import * as Sharing from 'expo-sharing';
import type { ProjectFile } from '@/src/lib/api';
import { getApiBaseUrlSync } from '@/src/lib/server-config';
export function getOpenableFileUrl(rawUrl: string): string {
if (/^https?:\/\//i.test(rawUrl)) return rawUrl;
const apiBaseUrl = getApiBaseUrlSync().replace(/\/+$/, '');
const path = rawUrl.startsWith('/') ? rawUrl : `/${rawUrl}`;
return `${apiBaseUrl}${path}`;
}
function safeFilename(file: ProjectFile): string {
const fallback = `dokument-${file.id}`;
const rawName = String(file.name || file.path?.split('/').pop() || fallback);
return rawName.replace(/[^a-zA-Z0-9äöüÄÖÜß._-]/g, '_');
}
export async function openAuthenticatedFile(file: ProjectFile, token: string): Promise<void> {
if (!file.url) throw new Error('Für dieses Dokument ist kein Download verfügbar.');
const target = new File(Paths.cache, `${file.id}-${safeFilename(file)}`);
const downloaded = await File.downloadFileAsync(getOpenableFileUrl(file.url), target, {
headers: { Authorization: `Bearer ${token}` },
idempotent: true,
});
if (!(await Sharing.isAvailableAsync())) {
throw new Error('Die Dokumentvorschau ist auf diesem Gerät nicht verfügbar.');
}
await Sharing.shareAsync(downloaded.uri, {
mimeType: file.mimeType || undefined,
dialogTitle: safeFilename(file),
});
}