Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

1.4 KB
Raw Blame
import type {
  DownloadRequest,
  DownloadResult,
} from "@editor-core/services/downloadService";
import { assertFilesNotBlocked } from "@editor/services/policyFileGuard";
import {
  saveToLocalPath,
  showSaveDialog,
} from "@editor/services/localFileSaveService";

export type { DownloadRequest, DownloadResult };

export const SAVES_TO_DISK = true;

export async function downloadFile(
  request: DownloadRequest,
): Promise<DownloadResult> {
  assertFilesNotBlocked([request.fileId]);
  if (request.localPath) {
    const result = await saveToLocalPath(request.data, request.localPath);
    if (!result.success) {
      throw new Error(result.error || "Failed to save file");
    }
    return { savedPath: request.localPath };
  }

  const savePath = await showSaveDialog(request.filename);
  if (!savePath) {
    return { cancelled: true };
  }

  assertFilesNotBlocked([request.fileId]);
  const result = await saveToLocalPath(request.data, savePath);
  if (!result.success) {
    throw new Error(result.error || "Failed to save file");
  }

  return { savedPath: savePath };
}

export async function downloadFromUrl(
  url: string,
  filename: string,
  localPath?: string,
): Promise<DownloadResult> {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`Download failed (${response.status})`);
  }
  const blob = await response.blob();
  return downloadFile({ data: blob, filename, localPath });
}