Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Visualizer download button #2571

Merged
merged 4 commits into from
Nov 13, 2024
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
9 changes: 5 additions & 4 deletions api_app/analyzers_manager/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# See the file 'LICENSE' for copying permission.

from logging import getLogger
from typing import Optional
from typing import Optional, Union

from django.contrib.contenttypes.fields import GenericRelation
from django.core.exceptions import ValidationError
Expand Down Expand Up @@ -121,16 +121,17 @@ def _calculate_from_filename(cls, file_name: str) -> Optional["MimeTypes"]:
return mimetype

@classmethod
def calculate(cls, file_pointer, file_name) -> str:
def calculate(cls, buffer: Union[bytes, str], file_name: str) -> str:
from magic import from_buffer as magic_from_buffer

mimetype = None
if file_name:
mimetype = cls._calculate_from_filename(file_name)

if mimetype is None:
buffer = file_pointer.read()
mimetype = magic_from_buffer(buffer, mime=True)
mimetype = magic_from_buffer(
buffer.encode() if isinstance(buffer, str) else buffer, mime=True
)
logger.debug(f"mimetype is {mimetype}")
try:
mimetype = cls(mimetype)
Expand Down
4 changes: 3 additions & 1 deletion api_app/serializers/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -749,7 +749,9 @@ def validate(self, attrs: dict) -> dict:
# calculate ``file_mimetype``
if "file_name" not in attrs:
attrs["file_name"] = attrs["file"].name
attrs["file_mimetype"] = MimeTypes.calculate(attrs["file"], attrs["file_name"])
attrs["file_mimetype"] = MimeTypes.calculate(
attrs["file"].read(), attrs["file_name"]
)
# calculate ``md5``
file_obj = attrs["file"].file
file_obj.seek(0)
Expand Down
45 changes: 45 additions & 0 deletions api_app/visualizers_manager/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from django.db.models import QuerySet

from api_app.analyzers_manager.models import MimeTypes
from api_app.choices import PythonModuleBasePaths
from api_app.classes import Plugin
from api_app.models import AbstractReport
Expand Down Expand Up @@ -141,6 +142,50 @@ def type(self) -> str:
return "title"


class VisualizableDownload(VisualizableObject):

def __init__(
self,
value: str,
payload: str,
alignment: VisualizableAlignment = VisualizableAlignment.CENTER,
size: VisualizableSize = VisualizableSize.S_AUTO,
disable: bool = False,
copy_text: str = "",
description: str = "",
add_metadata_in_description: bool = True,
link: str = "",
):
# assignments
super().__init__(size, alignment, disable)
self.value = value
self.payload = payload
self.copy_text = copy_text
self.description = description
self.add_metadata_in_description = add_metadata_in_description
self.link = link
# logic
self.mimetype = MimeTypes.calculate(
self.payload, self.value
) # needed as field from the frontend

@property
def type(self) -> str:
return "download"

@property
def attributes(self) -> List[str]:
return super().attributes + [
"value",
"mimetype",
"payload",
"copy_text",
"description",
"add_metadata_in_description",
"link",
]


class VisualizableBool(VisualizableBase):
def __init__(
self,
Expand Down
78 changes: 78 additions & 0 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
"@testing-library/jest-dom": "^6.5.0",
"@testing-library/react": "^12.1.5",
"@testing-library/user-event": "^14.5.2",
"@types/jest": "^29.5.14",
"babel-eslint": "^10.1.0",
"babel-jest": "^29.7.0",
"eslint": "^8.57.1",
Expand Down
11 changes: 1 addition & 10 deletions frontend/src/components/jobs/result/bar/JobActionBar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
retryJobIcon,
downloadReportIcon,
} from "../../../common/icon/icons";
import { fileDownload } from "../../../../utils/files";

export function JobActionsBar({ job }) {
// routers
Expand All @@ -29,16 +30,6 @@ export function JobActionsBar({ job }) {
setTimeout(() => navigate(-1), 250);
};

const fileDownload = (blob, filename) => {
// create URL blob and a hidden <a> tag to serve file for download
const fileLink = document.createElement("a");
fileLink.href = window.URL.createObjectURL(blob);
fileLink.rel = "noopener,noreferrer";
fileLink.download = `${filename}`;
// triggers the click event
fileLink.click();
};

const onDownloadSampleBtnClick = async () => {
const blob = await downloadJobSample(job.id);
if (!blob) return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ export const VisualizerComponentType = Object.freeze({
HLIST: "horizontal_list",
TITLE: "title",
TABLE: "table",
DOWNLOAD: "download",
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import React from "react";
import { Button } from "reactstrap";
import PropTypes from "prop-types";
import { FaFileDownload } from "react-icons/fa";
import { fileDownload, humanReadbleSize } from "../../../../../utils/files";
import { VisualizerTooltip } from "../VisualizerTooltip";

export function DownloadVisualizer({
size,
alignment,
disable,
id,
value,
mimetype,
payload,
isChild,
copyText,
description,
addMetadataInDescription,
link,
}) {
const blobFile = new Blob([payload], { type: mimetype });
let finalDescription = description;
if (addMetadataInDescription) {
finalDescription += `\n\n**Mimetype**: ${mimetype}. **Size**: ${humanReadbleSize(
blobFile.size,
)}`;
}

return (
<>
<div
className={`${size} ${
isChild ? "small" : ""
} p-0 m-1 d-flex align-items-center text-${alignment} justify-content-${alignment} ${
disable ? "opacity-25" : ""
}`}
id={id}
>
<Button
onClick={() => {
const blob = blobFile;
if (!blob) return;
fileDownload(blob, value);
}}
id={`${id}-tooltip`}
disabled={disable}
>
<FaFileDownload />
<span className={`${isChild ? "small" : ""}`}>{value}</span>
</Button>
</div>
<VisualizerTooltip
idElement={`${id}-tooltip`}
copyText={copyText}
link={link}
disable={disable}
description={finalDescription}
/>
</>
);
}

DownloadVisualizer.propTypes = {
size: PropTypes.string.isRequired,
alignment: PropTypes.string,
disable: PropTypes.bool,
id: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
mimetype: PropTypes.string.isRequired,
payload: PropTypes.string.isRequired,
isChild: PropTypes.bool,
copyText: PropTypes.string,
description: PropTypes.string,
addMetadataInDescription: PropTypes.bool,
link: PropTypes.string,
};

DownloadVisualizer.defaultProps = {
alignment: "center",
disable: false,
isChild: false,
copyText: "",
description: "",
addMetadataInDescription: true,
link: "",
};
Loading
Loading