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

feat(editor): Add validate minetype when upload files #339

Merged
merged 1 commit into from
May 7, 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
3 changes: 3 additions & 0 deletions backend/config/get-config-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import { PluginInfoJSONType } from "@/plugins/core/admin/plugins/helpers/files/c
export interface ConfigType {
editor: {
allow_head_h1: boolean;
files: {
allow_type: "all" | "images_videos" | "images" | "none";
};
sticky: boolean;
};
rebuild_required: {
Expand Down
22 changes: 22 additions & 0 deletions backend/functions/config/default-config-data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ConfigType } from "@/config/get-config-file";

export const DEFAULT_CONFIG_DATA: ConfigType = {
rebuild_required: {
themes: false,
langs: false,
plugins: false
},
editor: {
sticky: true,
allow_head_h1: false,
files: {
allow_type: "all"
}
},
settings: {
general: {
site_name: "VitNode Community",
site_short_name: "VitNode"
}
}
};
12 changes: 3 additions & 9 deletions backend/functions/config/finish-build-config-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { join } from "path";
import { migrate } from "drizzle-orm/node-postgres/migrator";

import { updatePlugins } from "./update-plugins";
import { DEFAULT_CONFIG_DATA } from "./default-config-data";

import {
ConfigType,
Expand All @@ -19,16 +20,9 @@ import { db } from "@/plugins/database/client";
const config = await getConfigFile();
const newData: ConfigType = {
...config,
rebuild_required: {
langs: false,
plugins: false,
themes: false
},
editor: {
sticky: true,
allow_head_h1: false
}
...DEFAULT_CONFIG_DATA
};

fs.writeFileSync(configPath, JSON.stringify(newData, null, 2), "utf8");

// Migration for database
Expand Down
40 changes: 12 additions & 28 deletions backend/functions/config/generate-config-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,46 +3,30 @@ import * as fs from "fs";

import { generateManifest } from "./manifest";
import { updateObject } from "./update-object";
import { DEFAULT_CONFIG_DATA } from "./default-config-data";

import {
ConfigType,
configPath,
getConfigFile
} from "../../config/get-config-file";

const DATA: ConfigType = {
rebuild_required: {
themes: false,
langs: false,
plugins: false
},
editor: {
sticky: true,
allow_head_h1: false
},
settings: {
general: {
site_name: "VitNode Community",
site_short_name: "VitNode"
}
}
};
import { configPath, getConfigFile } from "../../config/get-config-file";

(async () => {
if (!fs.existsSync(configPath)) {
fs.writeFile(configPath, JSON.stringify(DATA, null, 2), "utf8", err => {
if (err) throw err;
});
fs.writeFile(
configPath,
JSON.stringify(DEFAULT_CONFIG_DATA, null, 2),
"utf8",
err => {
if (err) throw err;
}
);

await generateManifest(DATA);
await generateManifest(DEFAULT_CONFIG_DATA);

console.log("[VitNode] - Config file has been generated");
} else {
console.log("[VitNode] - Config file already exists. Updating...");

// Update config file
const config = await getConfigFile();
const updatedConfig = updateObject(config, DATA);
const updatedConfig = updateObject(config, DEFAULT_CONFIG_DATA);

fs.writeFile(
configPath,
Expand Down
24 changes: 22 additions & 2 deletions backend/plugins/core/editor/upload/upload.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { UploadCoreFilesArgs } from "../../files/helpers/upload/dto/upload.args"
import { core_files } from "../../admin/database/schema/files";
import { ShowCoreFiles } from "../../files/show/dto/show.obj";
import { generateRandomString } from "@/functions/generate-random-string";
import { getConfigFile } from "@/config/get-config-file";

@Injectable()
export class UploadCoreEditorService extends HelpersUploadCoreFilesService {
Expand All @@ -26,11 +27,30 @@ export class UploadCoreEditorService extends HelpersUploadCoreFilesService {
...acceptMimeTypeVideo
];

private async getAcceptMineType(): Promise<string[]> {
const {
editor: {
files: { allow_type }
}
} = await getConfigFile();

if (allow_type === "images_videos") {
return [...acceptMimeTypeImage, ...acceptMimeTypeVideo];
}

if (allow_type === "images") {
return acceptMimeTypeImage;
}

return [];
}

private async getFilesAfterUpload({
file,
folder,
plugin
}: UploadCoreEditorArgs) {
const acceptMimeType = await this.getAcceptMineType();
const allowUploadToFrontend = await this.checkAcceptMimeType({
file,
acceptMimeType: this.acceptMimeTypeToFrontend,
Expand All @@ -46,15 +66,15 @@ export class UploadCoreEditorService extends HelpersUploadCoreFilesService {
if (allowUploadToFrontend) {
const current = await this.uploadFile.upload({
...args,
acceptMimeType: this.acceptMimeTypeToFrontend
acceptMimeType
});

return current[0];
}

const current = await this.uploadFile.upload({
...args,
acceptMimeType: [],
acceptMimeType,
secure: true
});

Expand Down
3 changes: 3 additions & 0 deletions frontend/admin/core/views/core/styles/editor/content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
import { useEditorAdmin, type EditorAdminArgs } from "./hooks/use-editor-admin";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { FilesSectionContentEditorAdmin } from "./sections/files";

export const ContentEditorAdmin = ({ data }: EditorAdminArgs) => {
const t = useTranslations("admin.core.styles.editor");
Expand Down Expand Up @@ -69,6 +70,8 @@ export const ContentEditorAdmin = ({ data }: EditorAdminArgs) => {
)}
/>

<FilesSectionContentEditorAdmin />

<Button type="submit" loading={form.formState.isSubmitting}>
{tCore("save")}
</Button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,18 @@ export const useEditorAdmin = ({ data }: EditorAdminArgs) => {
const t = useTranslations("core");
const formSchema = z.object({
sticky: z.boolean(),
allow_head_h1: z.boolean()
allow_head_h1: z.boolean(),
files: z.object({
allow_type: z.enum(["all", "images_videos", "images", "none"])
})
});

const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
sticky: data.editor.sticky,
allow_head_h1: data.editor.allow_head_h1
allow_head_h1: data.editor.allow_head_h1,
files: data.editor.files
}
});

Expand Down
60 changes: 60 additions & 0 deletions frontend/admin/core/views/core/styles/editor/sections/files.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { useTranslations } from "next-intl";
import { useFormContext } from "react-hook-form";

import { HeaderContent } from "@/components/header-content/header-content";
import { FormField, FormItem, FormLabel } from "@/components/ui/form";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";

export const FilesSectionContentEditorAdmin = () => {
const t = useTranslations("admin.core.styles.editor");
const form = useFormContext();

return (
<div>
<HeaderContent h2={"Files"} className="m-0" />

<FormField
control={form.control}
name="files.allow_type"
render={({ field }) => (
<FormItem>
<FormLabel>{t("files.allow_type.title")}</FormLabel>
<RadioGroup
onValueChange={field.onChange}
defaultValue={field.value}
>
<div className="flex items-center gap-2">
<RadioGroupItem value="all" id="files.allow_type.all" />
<Label htmlFor="files.allow_type.all">
{t("files.allow_type.all")}
</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem
value="images_videos"
id="files.allow_type.images_videos"
/>
<Label htmlFor="files.allow_type.images_videos">
{t("files.allow_type.images_videos")}
</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value="images" id="files.allow_type.images" />
<Label htmlFor="files.allow_type.images">
{t("files.allow_type.images")}
</Label>
</div>
<div className="flex items-center gap-2">
<RadioGroupItem value="none" id="files.allow_type.none" />
<Label htmlFor="files.allow_type.none">
{t("files.allow_type.none")}
</Label>
</div>
</RadioGroup>
</FormItem>
)}
/>
</div>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@ import { useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";

import type { FileStateEditor } from "../files";
import {
acceptMimeTypeImage,
acceptMimeTypeVideo,
type FileStateEditor
} from "../files";
import { uploadMutationApi } from "./upload-mutation-api";
import type { ErrorType } from "@/graphql/fetcher";
import type { TextLanguage } from "@/graphql/hooks";
import { getFilesFromContent } from "@/components/editor/extensions/files/hooks/functions";
import { useGlobals } from "@/hooks/core/use-globals";

export interface UploadFilesHandlerArgs {
files: FileStateEditor[];
Expand All @@ -25,10 +30,12 @@ export const useUploadFilesHandlerEditor = ({
allowUploadFiles,
value
}: UploadFilesHandlerEditorArgs) => {
const { config } = useGlobals();
const [files, setFiles] = useState<FileStateEditor[]>(
Array.isArray(value) ? getFilesFromContent(value) : []
);
const t = useTranslations("core");
const t = useTranslations("core.editor.files");
const tCore = useTranslations("core");

const handleUpload = async ({
data,
Expand All @@ -47,8 +54,8 @@ export const useUploadFilesHandlerEditor = ({
const error = mutation.error as ErrorType | undefined;

if (error || !mutation.data) {
toast.error(t("errors.title"), {
description: t("errors.internal_server_error")
toast.error(tCore("errors.title"), {
description: tCore("errors.internal_server_error")
});

return;
Expand Down Expand Up @@ -77,13 +84,52 @@ export const useUploadFilesHandlerEditor = ({
});
};

const validateMineTypeFiles = (
files: FileStateEditor[]
): FileStateEditor[] => {
// console.log(files);
if (config.editor.files.allow_type === "all") return files;

return files.filter(file => {
if (config.editor.files.allow_type === "images_videos") {
return [...acceptMimeTypeImage, ...acceptMimeTypeVideo].includes(
file.file?.type || ""
);
}

if (config.editor.files.allow_type === "images") {
return acceptMimeTypeImage.includes(file.file?.type || "");
}
});
};

const uploadFiles = async ({
files,
finishUpload
}: UploadFilesHandlerArgs) => {
if (!files.length || !allowUploadFiles) return;
if (
!files.length ||
!allowUploadFiles ||
config.editor.files.allow_type === "none"
) {
return;
}

const validateMineType = validateMineTypeFiles(files);

if (validateMineType.length !== files.length) {
toast.error(t("errors.invalid_file_type.title"), {
description: t("errors.invalid_file_type.desc", {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
types: t(config.editor.files.allow_type)
})
});
}

if (!validateMineType.length) return;

setFiles(prev => [...prev, ...files]);
setFiles(prev => [...prev, ...validateMineType]);

await Promise.all(
files.map(async data => {
Expand Down
2 changes: 1 addition & 1 deletion frontend/components/editor/footer/files/item/item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export const ItemListFilesFooterEditor = ({
<Button
size="icon"
variant="destructiveGhost"
ariaLabel="Delete"
ariaLabel={tCore("delete")}
onClick={async () => {
const nodes: Node[] = [];
editor.state.tr.doc.descendants(node => {
Expand Down
Loading
Loading