Skip to content

Commit

Permalink
delete model
Browse files Browse the repository at this point in the history
  • Loading branch information
fidoriel committed Nov 8, 2024
1 parent 76b0476 commit 45eaedc
Show file tree
Hide file tree
Showing 6 changed files with 242 additions and 16 deletions.
18 changes: 18 additions & 0 deletions backend/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,23 @@ async fn refresh_model(
(StatusCode::OK, Json(response))
}

async fn delete_model(
State(state): State<AppState>,
Path(slug): Path<String>,
) -> impl IntoResponse {
let mut connection = state.pool.get().await.unwrap();

let result = models3d::dsl::models3d
.filter(models3d::dsl::name.eq(slug))
.first::<Model3D>(&mut connection)
.await
.unwrap();
match result.delete(&state.config, &mut connection).await {
Ok(_) => StatusCode::OK,
Err(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}

async fn handle_refresh(State(state): State<AppState>) -> impl IntoResponse {
parse_library::refresh_library(state.pool, state.config.clone())
.await
Expand Down Expand Up @@ -237,6 +254,7 @@ async fn main() {
.route("/models/list", get(list_models))
.route("/model/:slug", get(get_model_by_slug))
.route("/model/:slug/refresh", get(refresh_model))
.route("/model/:slug/delete", post(delete_model))
.route("/download/:folder", get(handle_zip_download))
.route("/upload", post(upload::handle_upload))
.layer(DefaultBodyLimit::disable())
Expand Down
15 changes: 15 additions & 0 deletions backend/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use diesel::prelude::*;
use diesel_async::{AsyncConnection, RunQueryDsl};
use serde::{Deserialize, Serialize};
use typeshare::typeshare;
use tracing::debug;

fn comma_separated_to_pathbuf_vec(input: &str) -> Vec<PathBuf> {
if input.trim().is_empty() {
Expand Down Expand Up @@ -116,6 +117,20 @@ impl Model3D {

anyhow::Ok(())
}

pub async fn delete<Conn>(&self, config: &Config, connection: &mut Conn) -> anyhow::Result<()>
where
Conn: AsyncConnection<Backend = diesel::sqlite::Sqlite>,
{
fs_extra::dir::remove(self.absolute_path(config));
debug!("Deleted {}", self.absolute_path(config).display());
diesel::delete(models3d::dsl::models3d.filter(models3d::dsl::id.eq(self.id)))
.execute(connection)
.await
.unwrap();

anyhow::Ok(())
}
}

#[typeshare]
Expand Down
91 changes: 75 additions & 16 deletions frontend/Model.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Card, CardContent } from "@/components/ui/card";
import { Download, Heart, MoreVertical, RefreshCcw, Bookmark } from "lucide-react";

import { useState, useEffect, useRef } from "react";
import { useParams } from "react-router-dom";
import { useNavigate, useParams } from "react-router-dom";
import { DetailedFileResponse, DetailedModelResponse } from "./bindings";
import { BACKEND_BASE_URL } from "./lib/api";
import { saveAs } from "file-saver";
Expand All @@ -23,21 +23,80 @@ import { DialogHeader } from "./components/ui/dialog";
import ModelViewer from "./ModelViewer";
import { useToast } from "./hooks/use-toast";

function OptionsDropdownMenu() {
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";

function OptionsDropdownMenu({ model }: { model: DetailedModelResponse }) {
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
const { toast } = useToast();
const navigate = useNavigate();

async function deleteModel() {
fetch(BACKEND_BASE_URL + `/api/model/${model.name}/delete`, {
method: "POST",
})
.then((response) => {
if (!response.ok) {
toast({
title: `Deleting model "${model.title}" failed`,
description: `An unknown server error occurred`,
});
}
toast({
title: `Deleting model "${model.title}" successful`,
description: `It is now permanently removed`,
});
navigate("/");
})
.catch((error) => {
console.error("Fetch error:", error);
});
}

return (
<DropdownMenu>
<DropdownMenuTrigger>
<MoreVertical className="h-5 w-5" />
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>Model Options</DropdownMenuLabel>
<DropdownMenuSeparator></DropdownMenuSeparator>
<DropdownMenuItem>Edit</DropdownMenuItem>
<DropdownMenuItem>Delete</DropdownMenuItem>
<DropdownMenuItem>Compress</DropdownMenuItem>
<DropdownMenuItem>Merge</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<>
<DropdownMenu>
<DropdownMenuTrigger>
<MoreVertical className="h-5 w-5" />
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>Model Options</DropdownMenuLabel>
<DropdownMenuSeparator></DropdownMenuSeparator>
{/* <DropdownMenuItem>Edit</DropdownMenuItem> */}
<DropdownMenuItem onClick={() => setIsDeleteDialogOpen(true)}>Delete</DropdownMenuItem>
{/* <DropdownMenuItem>Compress</DropdownMenuItem> */}
</DropdownMenuContent>
</DropdownMenu>

<AlertDialog open={isDeleteDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure to delete "{model.title}"?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete "{model.title}" from database and
filesystem.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={() => setIsDeleteDialogOpen(false)}>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={deleteModel}
className="bg-destructive hover:bg-destructive/80 text-destructive-foreground"
>
Delete
</AlertDialogAction>{" "}
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}

Expand Down Expand Up @@ -141,7 +200,7 @@ function InfoCard({ model, refresh }: { model: DetailedModelResponse; refresh: (
<div className="space-y-2">
<h1 className="text-2xl font-bold">{model.title}</h1>
</div>
<OptionsDropdownMenu />
<OptionsDropdownMenu model={model} />
</div>

<div className="mb-6">
Expand Down
104 changes: 104 additions & 0 deletions frontend/components/ui/alert-dialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import * as React from "react";
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";

import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button";

const AlertDialog = AlertDialogPrimitive.Root;

const AlertDialogTrigger = AlertDialogPrimitive.Trigger;

const AlertDialogPortal = AlertDialogPrimitive.Portal;

const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
ref={ref}
/>
));
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;

const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className,
)}
{...props}
/>
</AlertDialogPortal>
));
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;

const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
);
AlertDialogHeader.displayName = "AlertDialogHeader";

const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />
);
AlertDialogFooter.displayName = "AlertDialogFooter";

const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title ref={ref} className={cn("text-lg font-semibold", className)} {...props} />
));
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;

const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName;

const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
));
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;

const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(buttonVariants({ variant: "outline" }), "mt-2 sm:mt-0", className)}
{...props}
/>
));
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;

export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};
29 changes: 29 additions & 0 deletions 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 package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"precommit": "npm run format && npm run lint:fix && npm run build"
},
"dependencies": {
"@radix-ui/react-alert-dialog": "^1.1.2",
"@radix-ui/react-aspect-ratio": "^1.1.0",
"@radix-ui/react-collapsible": "^1.1.1",
"@radix-ui/react-dialog": "^1.1.2",
Expand Down

0 comments on commit 45eaedc

Please sign in to comment.