Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/app/api/entity-download/presigned-url/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from 'next/server';

import { downloadAsset } from '@/api/entitycore/queries/assets';
import { TEntityTypeDict } from '@/api/entitycore/types';
import { formatBytes } from '@/utils/format';
import { log } from '@/utils/logger';
import { auth } from '@/auth';

export async function GET(request: NextRequest) {
const query = request.nextUrl.searchParams;
const entityType = query.get('entityType')! as TEntityTypeDict;
const entityId = query.get('entityId')!;
const virtualLabId = query.get('virtualLabId')!;
const projectId = query.get('projectId')!;
const configAssetId = query.get('configAssetId')!;

const session = await auth();

if (!session) {
return new Response('Unauthorized', {
status: 401,
statusText: 'The supplied authentication is not authorized for this action',
});
}
try {
const response = await downloadAsset({
entityType,
entityId: entityId!,
id: configAssetId!,
asRawResponse: true,
ctx: { virtualLabId, projectId },
});

if (response.ok) {
const { url, headers } = response;
const size = formatBytes(Number(headers.get('content-length')));
return NextResponse.json({ url, size }, { status: 200 });
}
return NextResponse.json(
{ error: 'Failed to process download request' },
{ status: response.status }
);
} catch (error) {
log('error', error);
return NextResponse.json({ error: 'Failed to process download request' }, { status: 500 });
}
}
2 changes: 1 addition & 1 deletion src/entity-configuration/domain/model/circuit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ export const Circuit: EntityCoreTypeConfig<ICircuit> = {
context: params[0].context,
withFacets: params[0].withFacets,
filters: {
...params[0].filters,
scale__in: without(
Object.values(CircuitScaleDictionary),
CircuitScaleDictionary.Single
),
...params[0].filters,
},
});
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
import { CheckCircleOutlined } from '@ant-design/icons';
import { useCallback, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useParams } from 'next/navigation';
import { Button, Progress } from 'antd';
import { match } from 'ts-pattern';
import delay from 'es-toolkit/compat/delay';
import saveAs from 'file-saver';
import { get } from 'es-toolkit/compat';
import { Button } from 'antd';

import { trackDownloadProgress } from '@/utils/track-download-progress';
import { AssetLabel } from '@/api/entitycore/types/shared/global';
import { downloadAsset } from '@/api/entitycore/queries/assets';
import { keyBuilder } from '@/ui/use-query-keys/third-parties';
import { getAssetElement } from '@/api/entitycore/utils';
import { EntityTypeDict } from '@/api/entitycore/types';
import { DownloadIcon } from '@/components/icons';
import { formatBytes } from '@/utils/format';
import { log } from '@/utils/logger';

import type { ICircuit } from '@/api/entitycore/types/entities/circuit';
import type { WorkspaceContext } from '@/types/common';
Expand All @@ -24,79 +19,51 @@ type Props = {

export default function EntireCircuitExport({ circuit }: Props) {
const { virtualLabId, projectId } = useParams<WorkspaceContext>();
const [downloadProgress, updateDownloadProgress] = useState(0);
const [status, setStatus] = useState<'idle' | 'downloading' | 'done'>('idle');

const assets = circuit?.assets;
const configAsset = getAssetElement({
assets,
filter: (asset) => asset.label === AssetLabel.compressed_sonata_circuit,
});
const extension = configAsset?.content_type.split('/').pop();
// TODO: this should be refactored after SFN
const getPresignedUrl = async () => {
const url = `${window.location.origin}/api/entity-download/presigned-url`;
const query = new URLSearchParams();
query.set('entityType', EntityTypeDict.Circuit);
query.set('entityId', circuit.id);
query.set('virtualLabId', virtualLabId);
query.set('projectId', projectId);
query.set('configAssetId', configAsset?.id!);

const downloadDirectory = useCallback(async () => {
const result = await trackDownloadProgress(
() =>
downloadAsset({
entityType: EntityTypeDict.Circuit,
entityId: circuit.id,
id: configAsset?.id!,
asRawResponse: true,
ctx: { virtualLabId, projectId },
}),
(progress) => {
log('info', 'download-progress', progress);
updateDownloadProgress(progress);
if (progress >= 100) {
setStatus('done');
delay(() => setStatus('idle'), 3000);
}
}
);

const blob = new Blob(result, { type: configAsset?.content_type });
saveAs(blob, `${circuit.name}.${extension}`);
updateDownloadProgress(0);
}, [circuit.id, configAsset?.id, virtualLabId, projectId]); // eslint-disable-line react-hooks/exhaustive-deps

const onClick = () => {
if (configAsset?.path) {
setStatus('downloading');
downloadDirectory();
const response = await fetch(`${url}?${query.toString()}`, {
method: 'get',
headers: {
accept: 'application/json',
'Content-Type': 'application/json',
},
});
if (response.ok) {
const result = await response.json();
return result;
}
throw new Error(`Error #${response.status} creating presigned url: ${response.statusText}`);
};

const { isLoading, data } = useQuery({
queryKey: keyBuilder.s3presignedUrl({
entityType: EntityTypeDict.Circuit,
entity: circuit.id,
asset: configAsset?.id!,
virtualLabId,
projectId,
}),
queryFn: getPresignedUrl,
});

const totalSize =
configAsset?.size && configAsset?.size > 1 ? formatBytes(configAsset?.size) : '';

const action = match({ status })
.with({ status: 'idle' }, () => (
<Button
onClick={onClick}
type="text"
htmlType="button"
className="border-primary-6 flex items-center justify-center rounded-none border border-solid"
aria-label={`download ${circuit.name}`}
title={`download ${circuit.name}`}
icon={<DownloadIcon className="text-white!" />}
/>
))
.with({ status: 'downloading' }, () => (
<div className="flex flex-col items-center justify-center gap-0.5">
<Progress
type="circle"
percent={Math.round(downloadProgress)}
size={32}
strokeColor="#1890ff"
showInfo
className="[&_.ant-progress-text]:text-white!"
style={{ marginLeft: 8 }}
/>
<span className="text-[8px]">downloading</span>
</div>
))
.with({ status: 'done' }, () => (
<CheckCircleOutlined className="px-1 text-3xl text-green-400" />
))
.otherwise(() => null);
return (
<div className="bg-primary-8 mx-8 flex flex-col justify-between rounded-md p-8 shadow-xs">
<div id="download-header" className="flex w-full items-start justify-between gap-3">
Expand All @@ -112,16 +79,31 @@ export default function EntireCircuitExport({ circuit }: Props) {
rel="noopener noreferrer"
className="underline underline-offset-2"
>
{' '}
see more here
</a>
</p>
</div>
<div className="text-primary-1 flex flex-row gap-x-3 font-semibold">
<div>{totalSize}</div>
<div>{extension}</div>
{action}
</div>
{!isLoading && data && (
<div className="text-primary-1 flex flex-row gap-x-3 font-semibold">
<div>{get(data, 'size', totalSize)}</div>
<div>{extension}</div>
{get(data, 'url', null) && (
<Button
htmlType="button"
type="link"
className="border-primary-6 flex items-center justify-center rounded-none border border-solid"
aria-label={`download ${circuit.name}`}
title={`download ${circuit.name}`}
icon={<DownloadIcon className="text-white!" />}
loading={isLoading}
href={get(data, 'url', null)}
target="_blank"
rel="noopener noreferrer"
download={`${circuit.name}.${circuit.id}`}
/>
)}
</div>
)}
</div>
</div>
);
Expand Down
1 change: 1 addition & 0 deletions src/ui/use-query-keys/third-parties.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ export const keyBuilder = {
{ virtualLabId },
],
stripeInstance: () => [`${prefix}-stripe-instance`],
s3presignedUrl: (props: Record<string, any>) => [`${prefix}-presigned-url`, { ...props }],
};