Open History to see the last commit
1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3import { AuthFilesystemReadScope, type EnvironmentId } from "@t3tools/contracts";
4import { useGT } from "gt-react";
5
6import { resolveAssetUrl } from "~/assets/assetUrls";
7import { m } from "~/i18n/messages";
8import { assetEnvironment } from "~/state/assets";
9import { readPreparedConnection, useEnvironmentScope } from "~/state/session";
10import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
11
12import { downloadMedia } from "../media/mediaContent";
13import { toastManager } from "../ui/toast";
14
15export function useFileDownload(environmentId: EnvironmentId | null) {
16 const gt = useGT();
17 const canReadFiles = useEnvironmentScope(environmentId, AuthFilesystemReadScope);
18 const createUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
19 reportFailure: false,
20 refresh: true,
21 });
22 if (!canReadFiles || environmentId === null) return null;
23 return (cwd: string, filePath: string | Promise<string>) =>
24 void (async () => {
25 const path = await filePath;
26 const httpBaseUrl = readPreparedConnection(environmentId)?.httpBaseUrl;
27 if (!httpBaseUrl) throw new Error(gt("Reconnect to the environment and try again."));
28 const result = await createUrl({
29 environmentId,
30 input: { resource: { _tag: "draft-workspace-file", cwd, path, disposition: "attachment" } },
31 });
32 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
33 const url = resolveAssetUrl(httpBaseUrl, result.value.relativeUrl);
34 if (!url) throw new Error(gt("The file could not be loaded. Try again."));
35 await downloadMedia(url, path.split(/[\\/]/).at(-1) || path);
36 })().catch((cause: unknown) =>
37 toastManager.add({
38 type: "error",
39 title: gt("Could not download file"),
40 description: thrownErrorMessage(cause, m) ?? gt("Please try again."),
41 }),
42 );
43}