mirror of
https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir.git
synced 2025-08-11 21:23:54 -04:00
Compare commits
No commits in common. "40aee9aa8978f4e1adb420621e813958810fe388" and "7a8ab7e5f586899113b863f4553c60e94509205f" have entirely different histories.
40aee9aa89
...
7a8ab7e5f5
20 changed files with 106 additions and 1185 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -41,7 +41,6 @@ build/Release
|
||||||
# Dependency directories
|
# Dependency directories
|
||||||
node_modules/
|
node_modules/
|
||||||
jspm_packages/
|
jspm_packages/
|
||||||
mongo-backup/
|
|
||||||
|
|
||||||
# Snowpack dependency directory (https://snowpack.dev/)
|
# Snowpack dependency directory (https://snowpack.dev/)
|
||||||
web_modules/
|
web_modules/
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,2 @@
|
||||||
VITE_BACKEND_URL=http://localhost:4400
|
VITE_BACKEND_URL=http://localhost:4400
|
||||||
VITE_BACKEND_SOCKET_URL=http://localhost:4400
|
VITE_BACKEND_SOCKET_URL=http://localhost:4400
|
||||||
VITE_IMG_URL=http://localhost:4400
|
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,2 @@
|
||||||
VITE_BACKEND_URL=http://localhost:4400
|
VITE_BACKEND_URL=http://localhost:4400
|
||||||
VITE_AZURE_BACKEND_URL=http://localhost:4400
|
VITE_AZURE_BACKEND_URL=http://localhost:4400
|
||||||
VITE_IMG_URL=http://localhost:4400
|
|
||||||
73
client/package-lock.json
generated
73
client/package-lock.json
generated
|
|
@ -45,7 +45,6 @@
|
||||||
"@testing-library/dom": "^10.4.0",
|
"@testing-library/dom": "^10.4.0",
|
||||||
"@testing-library/jest-dom": "^6.6.3",
|
"@testing-library/jest-dom": "^6.6.3",
|
||||||
"@testing-library/react": "^16.2.0",
|
"@testing-library/react": "^16.2.0",
|
||||||
"@testing-library/user-event": "^14.6.1",
|
|
||||||
"@types/jest": "^29.5.13",
|
"@types/jest": "^29.5.13",
|
||||||
"@types/node": "^22.13.5",
|
"@types/node": "^22.13.5",
|
||||||
"@types/react": "^18.2.15",
|
"@types/react": "^18.2.15",
|
||||||
|
|
@ -420,24 +419,26 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@babel/helpers": {
|
"node_modules/@babel/helpers": {
|
||||||
"version": "7.27.0",
|
"version": "7.26.9",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.27.0.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.9.tgz",
|
||||||
"integrity": "sha512-U5eyP/CTFPuNE3qk+WZMxFkp/4zUzdceQlfzf7DdGdhp+Fezd7HD+i8Y24ZuTMKX3wQBld449jijbGq6OdGNQg==",
|
"integrity": "sha512-Mz/4+y8udxBKdmzt/UjPACs4G3j5SshJJEFFKxlCGPydG4JAHXxjWjAwjd09tf6oINvl1VfMJo+nB7H2YKQ0dA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/template": "^7.27.0",
|
"@babel/template": "^7.26.9",
|
||||||
"@babel/types": "^7.27.0"
|
"@babel/types": "^7.26.9"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@babel/parser": {
|
"node_modules/@babel/parser": {
|
||||||
"version": "7.27.0",
|
"version": "7.26.9",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.27.0.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.9.tgz",
|
||||||
"integrity": "sha512-iaepho73/2Pz7w2eMS0Q5f83+0RKI7i4xmiYeBmDzfRVbQtTOG7Ts0S4HzJVsTMGI9keU8rNfuZr8DKfSt7Yyg==",
|
"integrity": "sha512-81NWa1njQblgZbQHxWHpxxCzNsa3ZwvFqpUg7P+NNUU6f3UU2jBEg4OlF/J6rl8+PQGh1q6/zWScd001YwcA5A==",
|
||||||
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/types": "^7.27.0"
|
"@babel/types": "^7.26.9"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"parser": "bin/babel-parser.js"
|
"parser": "bin/babel-parser.js"
|
||||||
|
|
@ -1892,9 +1893,10 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@babel/runtime": {
|
"node_modules/@babel/runtime": {
|
||||||
"version": "7.27.0",
|
"version": "7.26.9",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.27.0.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.9.tgz",
|
||||||
"integrity": "sha512-VtPOkrdPHZsKc/clNqyi9WUA8TINkZ4cGk63UUE3u4pmB2k+ZMQRDuIOagv8UVd6j7k0T3+RRIb7beKTebNbcw==",
|
"integrity": "sha512-aA63XwOkcl4xxQa3HjPMqOP6LiK0ZDv3mUPYEFXkpHbaFjtGggE1A61FjFzJnB+p7/oy2gA8E+rcBNl/zC1tMg==",
|
||||||
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"regenerator-runtime": "^0.14.0"
|
"regenerator-runtime": "^0.14.0"
|
||||||
},
|
},
|
||||||
|
|
@ -1903,13 +1905,14 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@babel/template": {
|
"node_modules/@babel/template": {
|
||||||
"version": "7.27.0",
|
"version": "7.26.9",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.0.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.26.9.tgz",
|
||||||
"integrity": "sha512-2ncevenBqXI6qRMukPlXwHKHchC7RyMuu4xv5JBXRfOGVcTy1mXCD12qrp7Jsoxll1EV3+9sE4GugBVRjT2jFA==",
|
"integrity": "sha512-qyRplbeIpNZhmzOysF/wFMuP9sctmh2cFzRAZOn1YapxBsE1i9bJIY586R/WBLfLcmcBlM8ROBiQURnnNy+zfA==",
|
||||||
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/code-frame": "^7.26.2",
|
"@babel/code-frame": "^7.26.2",
|
||||||
"@babel/parser": "^7.27.0",
|
"@babel/parser": "^7.26.9",
|
||||||
"@babel/types": "^7.27.0"
|
"@babel/types": "^7.26.9"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
|
|
@ -1943,9 +1946,10 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@babel/types": {
|
"node_modules/@babel/types": {
|
||||||
"version": "7.27.0",
|
"version": "7.26.9",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.27.0.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.9.tgz",
|
||||||
"integrity": "sha512-H45s8fVLYjbhFH62dIJ3WtmJ6RSPt/3DRO0ZcT2SUiYiQyz3BLVb9ADEnLl91m74aQPS3AzzeajZHYOalWe3bg==",
|
"integrity": "sha512-Y3IR1cRnOxOCDvMmNiym7XpXQ93iGDDPHx+Zj+NM+rg0fBaShfQLkg+hKPaZCEvg5N/LeCo4+Rj/i3FuJsIQaw==",
|
||||||
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/helper-string-parser": "^7.25.9",
|
"@babel/helper-string-parser": "^7.25.9",
|
||||||
"@babel/helper-validator-identifier": "^7.25.9"
|
"@babel/helper-validator-identifier": "^7.25.9"
|
||||||
|
|
@ -4431,19 +4435,6 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@testing-library/user-event": {
|
|
||||||
"version": "14.6.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.1.tgz",
|
|
||||||
"integrity": "sha512-vq7fv0rnt+QTXgPxr5Hjc210p6YKq2kmdziLgnsZGgLJ9e6VAShx1pACLuRjd/AS/sr7phAR58OIIpf0LlmQNw==",
|
|
||||||
"dev": true,
|
|
||||||
"engines": {
|
|
||||||
"node": ">=12",
|
|
||||||
"npm": ">=6"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@testing-library/dom": ">=7.21.4"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@tootallnate/once": {
|
"node_modules/@tootallnate/once": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz",
|
||||||
|
|
@ -5344,9 +5335,10 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/axios": {
|
"node_modules/axios": {
|
||||||
"version": "1.8.4",
|
"version": "1.8.1",
|
||||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.8.4.tgz",
|
"resolved": "https://registry.npmjs.org/axios/-/axios-1.8.1.tgz",
|
||||||
"integrity": "sha512-eBSYY4Y68NNlHbHBMdeDmKNtDgXWhQsJcGqzO3iLUM0GraQFSS9cVgPX5I9b3lbdFKyYoAEGAZF1DwhTaljNAw==",
|
"integrity": "sha512-NN+fvwH/kV01dYUQ3PTOZns4LWtWhOFCAhQ/pHb88WQ1hNe5V/dvFwc4VJcDL11LT9xSX0QtsR8sWUuyOuOq7g==",
|
||||||
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"follow-redirects": "^1.15.6",
|
"follow-redirects": "^1.15.6",
|
||||||
"form-data": "^4.0.0",
|
"form-data": "^4.0.0",
|
||||||
|
|
@ -12918,9 +12910,10 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/vite": {
|
"node_modules/vite": {
|
||||||
"version": "6.2.5",
|
"version": "6.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.2.5.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-6.2.0.tgz",
|
||||||
"integrity": "sha512-j023J/hCAa4pRIUH6J9HemwYfjB5llR2Ps0CWeikOtdR8+pAURAk0DoJC5/mm9kd+UgdnIy7d6HE4EAvlYhPhA==",
|
"integrity": "sha512-7dPxoo+WsT/64rDcwoOjk76XHj+TqNTIvHKcuMQ1k4/SeHDaQt5GFAeLYzrimZrMpn/O6DtdI03WUjdxuPM0oQ==",
|
||||||
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"esbuild": "^0.25.0",
|
"esbuild": "^0.25.0",
|
||||||
"postcss": "^8.5.3",
|
"postcss": "^8.5.3",
|
||||||
|
|
|
||||||
|
|
@ -49,7 +49,6 @@
|
||||||
"@testing-library/dom": "^10.4.0",
|
"@testing-library/dom": "^10.4.0",
|
||||||
"@testing-library/jest-dom": "^6.6.3",
|
"@testing-library/jest-dom": "^6.6.3",
|
||||||
"@testing-library/react": "^16.2.0",
|
"@testing-library/react": "^16.2.0",
|
||||||
"@testing-library/user-event": "^14.6.1",
|
|
||||||
"@types/jest": "^29.5.13",
|
"@types/jest": "^29.5.13",
|
||||||
"@types/node": "^22.13.5",
|
"@types/node": "^22.13.5",
|
||||||
"@types/react": "^18.2.15",
|
"@types/react": "^18.2.15",
|
||||||
|
|
|
||||||
|
|
@ -1,17 +0,0 @@
|
||||||
export interface ImageType {
|
|
||||||
id: string;
|
|
||||||
file_content: string;
|
|
||||||
file_name: string;
|
|
||||||
mime_type: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ImagesResponse {
|
|
||||||
images: ImageType[];
|
|
||||||
total: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ImagesParams {
|
|
||||||
page: number;
|
|
||||||
limit: number;
|
|
||||||
uid?: string;
|
|
||||||
}
|
|
||||||
|
|
@ -1,17 +0,0 @@
|
||||||
export interface Images {
|
|
||||||
id: string;
|
|
||||||
file_content: string;
|
|
||||||
file_name: string;
|
|
||||||
mime_type: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ImagesResponse {
|
|
||||||
images: Images[];
|
|
||||||
total: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ImagesParams {
|
|
||||||
page: number;
|
|
||||||
limit: number;
|
|
||||||
uid?: string;
|
|
||||||
}
|
|
||||||
|
|
@ -1,147 +0,0 @@
|
||||||
import React, { act } from "react";
|
|
||||||
import "@testing-library/jest-dom";
|
|
||||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
|
||||||
import ImageGallery from "../../../components/ImageGallery/ImageGallery";
|
|
||||||
import ApiService from "../../../services/ApiService";
|
|
||||||
import { Images } from "../../../Types/Images";
|
|
||||||
import userEvent from "@testing-library/user-event";
|
|
||||||
|
|
||||||
jest.mock("../../../services/ApiService");
|
|
||||||
|
|
||||||
const mockImages: Images[] = [
|
|
||||||
{ id: "1", file_name: "image1.jpg", mime_type: "image/jpeg", file_content: "mockBase64Content1" },
|
|
||||||
{ id: "2", file_name: "image2.jpg", mime_type: "image/jpeg", file_content: "mockBase64Content2" },
|
|
||||||
{ id: "3", file_name: "image3.jpg", mime_type: "image/jpeg", file_content: "mockBase64Content3" },
|
|
||||||
];
|
|
||||||
|
|
||||||
beforeAll(() => {
|
|
||||||
global.URL.createObjectURL = jest.fn(() => 'mockedObjectUrl');
|
|
||||||
Object.assign(navigator, {
|
|
||||||
clipboard: {
|
|
||||||
writeText: jest.fn(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("ImageGallery", () => {
|
|
||||||
let mockHandleDelete: jest.Mock;
|
|
||||||
|
|
||||||
beforeEach(async () => {
|
|
||||||
(ApiService.getUserImages as jest.Mock).mockResolvedValue({ images: mockImages, total: 3 });
|
|
||||||
(ApiService.deleteImage as jest.Mock).mockResolvedValue(true);
|
|
||||||
(ApiService.uploadImage as jest.Mock).mockResolvedValue('mockImageUrl');
|
|
||||||
await act(async () => {
|
|
||||||
render(<ImageGallery />);
|
|
||||||
});
|
|
||||||
mockHandleDelete = jest.fn();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should render images correctly", async () => {
|
|
||||||
await act(async () => {
|
|
||||||
await screen.findByText("Galerie");
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(screen.getByAltText("Image image1.jpg")).toBeInTheDocument();
|
|
||||||
expect(screen.getByAltText("Image image2.jpg")).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should handle copy action", async () => {
|
|
||||||
const handleCopyMock = jest.fn();
|
|
||||||
await act(async () => {
|
|
||||||
render(<ImageGallery handleCopy={handleCopyMock} />);
|
|
||||||
});
|
|
||||||
|
|
||||||
const copyButtons = await waitFor(() => screen.findAllByTestId(/gallery-tab-copy-/));
|
|
||||||
await act(async () => {
|
|
||||||
fireEvent.click(copyButtons[0]);
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(navigator.clipboard.writeText).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should delete an image and update the gallery", async () => {
|
|
||||||
const fetchImagesMock = jest.fn().mockResolvedValue({ images: mockImages.filter((image) => image.id !== "1"), total: 2 });
|
|
||||||
|
|
||||||
(ApiService.getUserImages as jest.Mock).mockImplementation(fetchImagesMock);
|
|
||||||
|
|
||||||
await act(async () => {
|
|
||||||
render(<ImageGallery handleDelete={mockHandleDelete} />);
|
|
||||||
});
|
|
||||||
|
|
||||||
await act(async () => {
|
|
||||||
await screen.findByAltText("Image image1.jpg");
|
|
||||||
});
|
|
||||||
|
|
||||||
const deleteButtons = await waitFor(() => screen.findAllByTestId(/gallery-tab-delete-/));
|
|
||||||
fireEvent.click(deleteButtons[0]);
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByText("Voulez-vous supprimer cette image?")).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
const confirmDeleteButton = screen.getByText("Delete");
|
|
||||||
await act(async () => {
|
|
||||||
fireEvent.click(confirmDeleteButton);
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(ApiService.deleteImage).toHaveBeenCalledWith("1");
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.queryByAltText("Image image1.jpg")).toBeNull();
|
|
||||||
expect(screen.getByText("Image supprimée avec succès!")).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should upload an image and display success message", async () => {
|
|
||||||
const importTab = screen.getByRole("tab", { name: /import/i });
|
|
||||||
fireEvent.click(importTab);
|
|
||||||
|
|
||||||
const fileInputs = await screen.findAllByTestId("file-input");
|
|
||||||
const fileInput = fileInputs[1];
|
|
||||||
|
|
||||||
expect(fileInput).toBeInTheDocument();
|
|
||||||
|
|
||||||
const file = new File(["image"], "image.jpg", { type: "image/jpeg" });
|
|
||||||
await userEvent.upload(fileInput, file);
|
|
||||||
|
|
||||||
|
|
||||||
await waitFor(() => screen.getByAltText("Preview"));
|
|
||||||
const previewImage = screen.getByAltText("Preview");
|
|
||||||
|
|
||||||
expect(previewImage).toBeInTheDocument();
|
|
||||||
|
|
||||||
const uploadButton = screen.getByRole('button', { name: /téléverser/i });
|
|
||||||
fireEvent.click(uploadButton);
|
|
||||||
const successMessage = await screen.findByText(/téléversée avec succès/i);
|
|
||||||
expect(successMessage).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should close the image preview dialog when close button is clicked", async () => {
|
|
||||||
const imageCard = screen.getByAltText("Image image1.jpg");
|
|
||||||
fireEvent.click(imageCard);
|
|
||||||
|
|
||||||
const dialogImage = await screen.findByAltText("Enlarged view");
|
|
||||||
expect(dialogImage).toBeInTheDocument();
|
|
||||||
|
|
||||||
const closeButton = screen.getByTestId("close-button");
|
|
||||||
fireEvent.click(closeButton);
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.queryByAltText("Enlarged view")).not.toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should show an error message when no file is selected", async () => {
|
|
||||||
const importTab = screen.getByRole("tab", { name: /import/i });
|
|
||||||
fireEvent.click(importTab);
|
|
||||||
const uploadButton = screen.getByRole('button', { name: /téléverser/i });
|
|
||||||
fireEvent.click(uploadButton);
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByText("Veuillez choisir une image à téléverser.")).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
@ -1,44 +0,0 @@
|
||||||
import React from "react";
|
|
||||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
|
||||||
import ImageGalleryModal from "../../../components/ImageGallery/ImageGalleryModal/ImageGalleryModal";
|
|
||||||
import "@testing-library/jest-dom";
|
|
||||||
|
|
||||||
jest.mock("../../../components/ImageGallery/ImageGallery", () => ({
|
|
||||||
__esModule: true,
|
|
||||||
default: jest.fn(() => <div data-testid="image-gallery" />),
|
|
||||||
}));
|
|
||||||
|
|
||||||
describe("ImageGalleryModal", () => {
|
|
||||||
|
|
||||||
it("renders button correctly", () => {
|
|
||||||
render(<ImageGalleryModal />);
|
|
||||||
|
|
||||||
const button = screen.getByLabelText(/images-open/i);
|
|
||||||
expect(button).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("opens the modal when button is clicked", () => {
|
|
||||||
render(<ImageGalleryModal />);
|
|
||||||
|
|
||||||
const button = screen.getByRole("button", { name: /images/i });
|
|
||||||
fireEvent.click(button);
|
|
||||||
|
|
||||||
const dialog = screen.getByRole("dialog");
|
|
||||||
expect(dialog).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
it("closes the modal when close button is clicked", async () => {
|
|
||||||
render(<ImageGalleryModal />);
|
|
||||||
|
|
||||||
fireEvent.click(screen.getByRole("button", { name: /images/i }));
|
|
||||||
|
|
||||||
const closeButton = screen.getByRole("button", { name: /close/i });
|
|
||||||
fireEvent.click(closeButton);
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
@ -1,309 +0,0 @@
|
||||||
import React, { useState, useEffect } from "react";
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
CircularProgress,
|
|
||||||
Button,
|
|
||||||
IconButton,
|
|
||||||
Card,
|
|
||||||
CardContent,
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogActions,
|
|
||||||
DialogTitle,
|
|
||||||
DialogContentText,
|
|
||||||
Tabs,
|
|
||||||
Tab,
|
|
||||||
TextField, Snackbar,
|
|
||||||
Alert
|
|
||||||
} from "@mui/material";
|
|
||||||
import DeleteIcon from "@mui/icons-material/Delete";
|
|
||||||
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
|
|
||||||
import CloseIcon from "@mui/icons-material/Close";
|
|
||||||
import { ImageType } from "../../Types/ImageType";
|
|
||||||
import ApiService from "../../services/ApiService";
|
|
||||||
import { Upload } from "@mui/icons-material";
|
|
||||||
import { ENV_VARIABLES } from '../../constants';
|
|
||||||
import { escapeForGIFT } from "src/utils/giftUtils";
|
|
||||||
|
|
||||||
interface ImagesProps {
|
|
||||||
handleCopy?: (id: string) => void;
|
|
||||||
handleDelete?: (id: string) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ImageGallery: React.FC<ImagesProps> = ({ handleCopy, handleDelete }) => {
|
|
||||||
const [images, setImages] = useState<ImageType[]>([]);
|
|
||||||
const [totalImg, setTotalImg] = useState(0);
|
|
||||||
const [imgPage, setImgPage] = useState(1);
|
|
||||||
const [imgLimit] = useState(6);
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [selectedImage, setSelectedImage] = useState<ImageType | null>(null);
|
|
||||||
const [openDeleteDialog, setOpenDeleteDialog] = useState(false);
|
|
||||||
const [imageToDelete, setImageToDelete] = useState<ImageType | null>(null);
|
|
||||||
const [tabValue, setTabValue] = useState(0);
|
|
||||||
const [importedImage, setImportedImage] = useState<File | null>(null);
|
|
||||||
const [preview, setPreview] = useState<string | null>(null);
|
|
||||||
const [snackbarOpen, setSnackbarOpen] = useState(false);
|
|
||||||
const [snackbarMessage, setSnackbarMessage] = useState("");
|
|
||||||
const [snackbarSeverity, setSnackbarSeverity] = useState<"success" | "error">("success");
|
|
||||||
|
|
||||||
const fetchImages = async () => {
|
|
||||||
setLoading(true);
|
|
||||||
const data = await ApiService.getUserImages(imgPage, imgLimit);
|
|
||||||
setImages(data.images);
|
|
||||||
setTotalImg(data.total);
|
|
||||||
setLoading(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchImages();
|
|
||||||
}, [imgPage]);
|
|
||||||
|
|
||||||
const defaultHandleDelete = async (id: string) => {
|
|
||||||
if (imageToDelete) {
|
|
||||||
setLoading(true);
|
|
||||||
const isDeleted = await ApiService.deleteImage(id);
|
|
||||||
setLoading(false);
|
|
||||||
|
|
||||||
if (isDeleted) {
|
|
||||||
setImgPage(1);
|
|
||||||
fetchImages();
|
|
||||||
setSnackbarMessage("Image supprimée avec succès!");
|
|
||||||
setSnackbarSeverity("success");
|
|
||||||
} else {
|
|
||||||
setSnackbarMessage("Erreur lors de la suppression de l'image. Veuillez réessayer.");
|
|
||||||
setSnackbarSeverity("error");
|
|
||||||
}
|
|
||||||
|
|
||||||
setSnackbarOpen(true);
|
|
||||||
setSelectedImage(null);
|
|
||||||
setImageToDelete(null);
|
|
||||||
setOpenDeleteDialog(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const defaultHandleCopy = (id: string) => {
|
|
||||||
if (navigator.clipboard) {
|
|
||||||
const link = `${ENV_VARIABLES.IMG_URL}/api/image/get/${id}`;
|
|
||||||
const imgTag = `[markdown]} "texte de l'infobulle") {T}`;
|
|
||||||
setSnackbarMessage("Le lien Markdown de l’image a été copié dans le presse-papiers");
|
|
||||||
setSnackbarSeverity("success");
|
|
||||||
setSnackbarOpen(true);
|
|
||||||
navigator.clipboard.writeText(imgTag);
|
|
||||||
}
|
|
||||||
if(handleCopy) {
|
|
||||||
handleCopy(id);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDeleteFunction = handleDelete || defaultHandleDelete;
|
|
||||||
|
|
||||||
const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const file = event.target.files ? event.target.files[0] : null;
|
|
||||||
setImportedImage(file);
|
|
||||||
if (file) {
|
|
||||||
const objectUrl = URL.createObjectURL(file);
|
|
||||||
setPreview(objectUrl);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSaveImage = async () => {
|
|
||||||
try {
|
|
||||||
if (!importedImage) {
|
|
||||||
setSnackbarMessage("Veuillez choisir une image à téléverser.");
|
|
||||||
setSnackbarSeverity("error");
|
|
||||||
setSnackbarOpen(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const imageUrl = await ApiService.uploadImage(importedImage);
|
|
||||||
|
|
||||||
if (imageUrl.includes("ERROR")) {
|
|
||||||
setSnackbarMessage("Une erreur est survenue. Veuillez réessayer plus tard.");
|
|
||||||
setSnackbarSeverity("error");
|
|
||||||
setSnackbarOpen(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
fetchImages();
|
|
||||||
|
|
||||||
setSnackbarMessage("Téléversée avec succès !");
|
|
||||||
setSnackbarSeverity("success");
|
|
||||||
setSnackbarOpen(true);
|
|
||||||
|
|
||||||
setImportedImage(null);
|
|
||||||
setPreview(null);
|
|
||||||
setTabValue(0);
|
|
||||||
} catch (error) {
|
|
||||||
setSnackbarMessage(`Une erreur est survenue.\n${error}\nVeuillez réessayer plus tard.`);
|
|
||||||
setSnackbarSeverity("error");
|
|
||||||
setSnackbarOpen(true);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCloseSnackbar = () => {
|
|
||||||
setSnackbarOpen(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box p={3}>
|
|
||||||
<Tabs value={tabValue} onChange={(_, newValue) => setTabValue(newValue)}>
|
|
||||||
<Tab label="Galerie" />
|
|
||||||
<Tab label="Import" />
|
|
||||||
</Tabs>
|
|
||||||
{tabValue === 0 && (
|
|
||||||
<>
|
|
||||||
{loading ? (
|
|
||||||
<Box display="flex" justifyContent="center" alignItems="center" height={200}>
|
|
||||||
<CircularProgress />
|
|
||||||
</Box>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Box display="grid" gridTemplateColumns="repeat(3, 1fr)" gridTemplateRows="repeat(2, 1fr)" gap={2} maxWidth="900px" margin="auto">
|
|
||||||
{images.map((obj) => (
|
|
||||||
<Card key={obj.id} sx={{ cursor: "pointer", display: "flex", flexDirection: "column", alignItems: "center" }} onClick={() => setSelectedImage(obj)}>
|
|
||||||
<CardContent sx={{ p: 0 }}>
|
|
||||||
<img
|
|
||||||
src={`data:${obj.mime_type};base64,${obj.file_content}`}
|
|
||||||
alt={`Image ${obj.file_name}`}
|
|
||||||
style={{ width: "100%", height: 250, objectFit: "cover", borderRadius: 8 }}
|
|
||||||
/>
|
|
||||||
</CardContent>
|
|
||||||
<Box display="flex" justifyContent="center" mt={1}>
|
|
||||||
<IconButton onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
defaultHandleCopy(obj.id);
|
|
||||||
}}
|
|
||||||
color="primary"
|
|
||||||
data-testid={`gallery-tab-copy-${obj.id}`} >
|
|
||||||
|
|
||||||
<ContentCopyIcon sx={{ fontSize: 18 }} />
|
|
||||||
</IconButton>
|
|
||||||
|
|
||||||
<IconButton
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
setImageToDelete(obj);
|
|
||||||
setOpenDeleteDialog(true);
|
|
||||||
}}
|
|
||||||
color="error"
|
|
||||||
data-testid={`gallery-tab-delete-${obj.id}`} >
|
|
||||||
|
|
||||||
<DeleteIcon sx={{ fontSize: 18 }} />
|
|
||||||
</IconButton>
|
|
||||||
</Box>
|
|
||||||
</Card>
|
|
||||||
))}
|
|
||||||
</Box>
|
|
||||||
<Box display="flex" justifyContent="center" mt={2}>
|
|
||||||
<Button onClick={() => setImgPage((prev) => Math.max(prev - 1, 1))} disabled={imgPage === 1} color="primary">
|
|
||||||
Précédent
|
|
||||||
</Button>
|
|
||||||
<Button onClick={() => setImgPage((prev) => (prev * imgLimit < totalImg ? prev + 1 : prev))} disabled={imgPage * imgLimit >= totalImg} color="primary">
|
|
||||||
Suivant
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{tabValue === 1 && (
|
|
||||||
<Box display="flex" flexDirection="column" alignItems="center" width="100%" mt={3}>
|
|
||||||
{/* Image Preview at the top */}
|
|
||||||
{preview && (
|
|
||||||
<Box
|
|
||||||
mt={2}
|
|
||||||
mb={2}
|
|
||||||
sx={{
|
|
||||||
width: "100%",
|
|
||||||
maxWidth: 600,
|
|
||||||
textAlign: "center",
|
|
||||||
display: "flex",
|
|
||||||
justifyContent: "center",
|
|
||||||
alignItems: "center",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<img
|
|
||||||
src={preview}
|
|
||||||
alt="Preview"
|
|
||||||
style={{
|
|
||||||
width: "100%",
|
|
||||||
height: "auto",
|
|
||||||
borderRadius: 8,
|
|
||||||
maxHeight: "600px",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
<Box display="flex" flexDirection="row" alignItems="center" width="100%" maxWidth={400}>
|
|
||||||
<TextField
|
|
||||||
type="file"
|
|
||||||
data-testid="file-input"
|
|
||||||
onChange={handleImageUpload}
|
|
||||||
slotProps={{
|
|
||||||
htmlInput: {
|
|
||||||
"data-testid": "file-input",
|
|
||||||
accept: "image/*",
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
sx={{ flexGrow: 1 }}
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
variant="outlined"
|
|
||||||
aria-label="Téléverser"
|
|
||||||
onClick={() => { handleSaveImage() }}
|
|
||||||
sx={{ ml: 2, height: "100%" }}
|
|
||||||
>
|
|
||||||
Téléverser <Upload sx={{ ml: 1 }} />
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
<Dialog open={!!selectedImage} onClose={() => setSelectedImage(null)} maxWidth="md">
|
|
||||||
<IconButton color="primary" onClick={() => setSelectedImage(null)} sx={{ position: "absolute", right: 8, top: 8, zIndex: 1 }}
|
|
||||||
data-testid="close-button">
|
|
||||||
<CloseIcon />
|
|
||||||
</IconButton>
|
|
||||||
<DialogContent>
|
|
||||||
{selectedImage && (
|
|
||||||
<img
|
|
||||||
src={`data:${selectedImage.mime_type};base64,${selectedImage.file_content}`}
|
|
||||||
alt="Enlarged view"
|
|
||||||
style={{ width: "100%", height: "auto", borderRadius: 8, maxHeight: "500px" }}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
|
|
||||||
{/* Delete Confirmation Dialog */}
|
|
||||||
<Dialog open={openDeleteDialog} onClose={() => setOpenDeleteDialog(false)}>
|
|
||||||
<DialogTitle>Supprimer</DialogTitle>
|
|
||||||
<DialogContent>
|
|
||||||
<DialogContentText>Voulez-vous supprimer cette image?</DialogContentText>
|
|
||||||
</DialogContent>
|
|
||||||
<DialogActions>
|
|
||||||
<Button onClick={() => setOpenDeleteDialog(false)} color="primary">
|
|
||||||
Annuler
|
|
||||||
</Button>
|
|
||||||
<Button onClick={() => imageToDelete && handleDeleteFunction(imageToDelete.id)} color="error">
|
|
||||||
Delete
|
|
||||||
</Button>
|
|
||||||
</DialogActions>
|
|
||||||
</Dialog>
|
|
||||||
|
|
||||||
<Snackbar
|
|
||||||
open={snackbarOpen}
|
|
||||||
autoHideDuration={4000}
|
|
||||||
onClose={handleCloseSnackbar}
|
|
||||||
>
|
|
||||||
<Alert
|
|
||||||
onClose={handleCloseSnackbar}
|
|
||||||
severity={snackbarSeverity}
|
|
||||||
sx={{ width: "100%" }}>
|
|
||||||
{snackbarMessage}
|
|
||||||
</Alert>
|
|
||||||
</Snackbar>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default ImageGallery;
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
import React, { useState } from "react";
|
|
||||||
import {
|
|
||||||
Button,
|
|
||||||
IconButton,
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
} from "@mui/material";
|
|
||||||
import CloseIcon from "@mui/icons-material/Close";
|
|
||||||
import ImageGallery from "../ImageGallery";
|
|
||||||
import { ImageSearch } from "@mui/icons-material";
|
|
||||||
|
|
||||||
|
|
||||||
interface ImageGalleryModalProps {
|
|
||||||
handleCopy?: (id: string) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const ImageGalleryModal: React.FC<ImageGalleryModalProps> = ({ handleCopy }) => {
|
|
||||||
const [open, setOpen] = useState<boolean>(false);
|
|
||||||
|
|
||||||
const handleOpen = () => setOpen(true);
|
|
||||||
const handleClose = () => setOpen(false);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Button
|
|
||||||
variant="outlined"
|
|
||||||
aria-label='images-open'
|
|
||||||
onClick={() => handleOpen()}>
|
|
||||||
Images <ImageSearch />
|
|
||||||
</Button>
|
|
||||||
<Dialog open={open} onClose={handleClose} maxWidth="md" fullWidth>
|
|
||||||
<DialogContent sx={{ display: "flex", flexDirection: "column", alignItems: "center", py: 3 }}>
|
|
||||||
<IconButton
|
|
||||||
onClick={handleClose}
|
|
||||||
color="primary"
|
|
||||||
aria-label="close"
|
|
||||||
sx={{
|
|
||||||
position: "absolute",
|
|
||||||
right: 8,
|
|
||||||
top: 8,
|
|
||||||
zIndex: 1,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<CloseIcon />
|
|
||||||
</IconButton>
|
|
||||||
|
|
||||||
<ImageGallery handleCopy={handleCopy}/>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default ImageGalleryModal;
|
|
||||||
|
|
@ -2,7 +2,6 @@
|
||||||
const ENV_VARIABLES = {
|
const ENV_VARIABLES = {
|
||||||
MODE: process.env.MODE || "production",
|
MODE: process.env.MODE || "production",
|
||||||
VITE_BACKEND_URL: process.env.VITE_BACKEND_URL || "",
|
VITE_BACKEND_URL: process.env.VITE_BACKEND_URL || "",
|
||||||
IMG_URL: process.env.MODE == "development" ? process.env.VITE_BACKEND_URL : process.env.VITE_IMG_URL,
|
|
||||||
BACKEND_URL: process.env.SITE_URL != undefined ? `${process.env.SITE_URL}${process.env.USE_PORTS ? `:${process.env.BACKEND_PORT}`:''}` : process.env.VITE_BACKEND_URL || '',
|
BACKEND_URL: process.env.SITE_URL != undefined ? `${process.env.SITE_URL}${process.env.USE_PORTS ? `:${process.env.BACKEND_PORT}`:''}` : process.env.VITE_BACKEND_URL || '',
|
||||||
FRONTEND_URL: process.env.SITE_URL != undefined ? `${process.env.SITE_URL}${process.env.USE_PORTS ? `:${process.env.PORT}`:''}` : ''
|
FRONTEND_URL: process.env.SITE_URL != undefined ? `${process.env.SITE_URL}${process.env.USE_PORTS ? `:${process.env.PORT}`:''}` : ''
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
// EditorQuiz.tsx
|
// EditorQuiz.tsx
|
||||||
import React, { useState, useEffect, CSSProperties } from 'react';
|
import React, { useState, useEffect, useRef, CSSProperties } from 'react';
|
||||||
import { useParams, useNavigate } from 'react-router-dom';
|
import { useParams, useNavigate } from 'react-router-dom';
|
||||||
|
|
||||||
import { FolderType } from '../../../Types/FolderType';
|
import { FolderType } from '../../../Types/FolderType';
|
||||||
|
|
@ -11,13 +11,12 @@ import GIFTTemplatePreview from 'src/components/GiftTemplate/GIFTTemplatePreview
|
||||||
import { QuizType } from '../../../Types/QuizType';
|
import { QuizType } from '../../../Types/QuizType';
|
||||||
|
|
||||||
import './editorQuiz.css';
|
import './editorQuiz.css';
|
||||||
import { Button, TextField, NativeSelect, Divider } from '@mui/material';
|
import { Button, TextField, NativeSelect, Divider, Dialog, DialogTitle, DialogActions, DialogContent } from '@mui/material';
|
||||||
import ReturnButton from 'src/components/ReturnButton/ReturnButton';
|
import ReturnButton from 'src/components/ReturnButton/ReturnButton';
|
||||||
import ImageGalleryModal from 'src/components/ImageGallery/ImageGalleryModal/ImageGalleryModal';
|
|
||||||
|
|
||||||
import ApiService from '../../../services/ApiService';
|
import ApiService from '../../../services/ApiService';
|
||||||
import { escapeForGIFT } from '../../../utils/giftUtils';
|
import { escapeForGIFT } from '../../../utils/giftUtils';
|
||||||
import { ENV_VARIABLES } from '../../../constants';
|
import { Upload } from '@mui/icons-material';
|
||||||
|
|
||||||
interface EditQuizParams {
|
interface EditQuizParams {
|
||||||
id: string;
|
id: string;
|
||||||
|
|
@ -39,6 +38,8 @@ const QuizForm: React.FC = () => {
|
||||||
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
||||||
setSelectedFolder(event.target.value);
|
setSelectedFolder(event.target.value);
|
||||||
};
|
};
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [dialogOpen, setDialogOpen] = useState(false);
|
||||||
const [showScrollButton, setShowScrollButton] = useState(false);
|
const [showScrollButton, setShowScrollButton] = useState(false);
|
||||||
|
|
||||||
const scrollToTop = () => {
|
const scrollToTop = () => {
|
||||||
|
|
@ -165,13 +166,42 @@ const QuizForm: React.FC = () => {
|
||||||
return <div>Chargement...</div>;
|
return <div>Chargement...</div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleCopyToClipboard = async (link: string) => {
|
const handleSaveImage = async () => {
|
||||||
navigator.clipboard.writeText(link);
|
try {
|
||||||
|
const inputElement = document.getElementById('file-input') as HTMLInputElement;
|
||||||
|
|
||||||
|
if (!inputElement?.files || inputElement.files.length === 0) {
|
||||||
|
setDialogOpen(true);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleCopyImage = (id: string) => {
|
if (!inputElement.files || inputElement.files.length === 0) {
|
||||||
const escLink = `${ENV_VARIABLES.IMG_URL}/api/image/get/${id}`;
|
window.alert("Veuillez d'abord choisir une image à téléverser.")
|
||||||
setImageLinks(prevLinks => [...prevLinks, escLink]);
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const imageUrl = await ApiService.uploadImage(inputElement.files[0]);
|
||||||
|
|
||||||
|
// Check for errors
|
||||||
|
if(imageUrl.indexOf("ERROR") >= 0) {
|
||||||
|
window.alert(`Une erreur est survenue.\n Veuillez réessayer plus tard`)
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setImageLinks(prevLinks => [...prevLinks, imageUrl]);
|
||||||
|
|
||||||
|
// Reset the file input element
|
||||||
|
if (fileInputRef.current) {
|
||||||
|
fileInputRef.current.value = '';
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
window.alert(`Une erreur est survenue.\n${error}\nVeuillez réessayer plus tard.`)
|
||||||
|
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCopyToClipboard = async (link: string) => {
|
||||||
|
navigator.clipboard.writeText(link);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
@ -228,11 +258,37 @@ const QuizForm: React.FC = () => {
|
||||||
onEditorChange={handleUpdatePreview} />
|
onEditorChange={handleUpdatePreview} />
|
||||||
|
|
||||||
<div className='images'>
|
<div className='images'>
|
||||||
<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
|
<div className='upload'>
|
||||||
<h4>Mes images :</h4>
|
<label className="dropArea">
|
||||||
<ImageGalleryModal handleCopy={handleCopyImage} />
|
<input type="file" id="file-input" className="file-input"
|
||||||
|
accept="image/jpeg, image/png"
|
||||||
|
multiple
|
||||||
|
ref={fileInputRef} />
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outlined"
|
||||||
|
aria-label='Téléverser'
|
||||||
|
onClick={handleSaveImage}>
|
||||||
|
Téléverser <Upload />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
</label>
|
||||||
|
<Dialog
|
||||||
|
open={dialogOpen}
|
||||||
|
onClose={() => setDialogOpen(false)} >
|
||||||
|
<DialogTitle>Erreur</DialogTitle>
|
||||||
|
<DialogContent>
|
||||||
|
Veuillez d'abord choisir une image à téléverser.
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions>
|
||||||
|
<Button onClick={() => setDialogOpen(false)} color="primary">
|
||||||
|
OK
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<h4>Mes images :</h4>
|
||||||
<div>
|
<div>
|
||||||
<div>
|
<div>
|
||||||
<div style={{ display: "inline" }}>(Voir section </div>
|
<div style={{ display: "inline" }}>(Voir section </div>
|
||||||
|
|
@ -246,7 +302,7 @@ const QuizForm: React.FC = () => {
|
||||||
</div>
|
</div>
|
||||||
<ul>
|
<ul>
|
||||||
{imageLinks.map((link, index) => {
|
{imageLinks.map((link, index) => {
|
||||||
const imgTag = `[markdown]} "texte de l'infobulle") {T}`;
|
const imgTag = `} "texte de l'infobulle")`;
|
||||||
return (
|
return (
|
||||||
<li key={index}>
|
<li key={index}>
|
||||||
<code
|
<code
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ import { jwtDecode } from 'jwt-decode';
|
||||||
import { ENV_VARIABLES } from '../constants';
|
import { ENV_VARIABLES } from '../constants';
|
||||||
|
|
||||||
import { FolderType } from 'src/Types/FolderType';
|
import { FolderType } from 'src/Types/FolderType';
|
||||||
import { ImagesResponse, ImagesParams } from '../Types/Images';
|
|
||||||
import { QuizType } from 'src/Types/QuizType';
|
import { QuizType } from 'src/Types/QuizType';
|
||||||
import { RoomType } from 'src/Types/RoomType';
|
import { RoomType } from 'src/Types/RoomType';
|
||||||
|
|
||||||
|
|
@ -139,22 +138,6 @@ class ApiService {
|
||||||
return object.username;
|
return object.username;
|
||||||
}
|
}
|
||||||
|
|
||||||
public getUserID(): string {
|
|
||||||
const token = localStorage.getItem("jwt");
|
|
||||||
|
|
||||||
if (!token) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
const jsonObj = jwtDecode(token) as { userId: string };
|
|
||||||
|
|
||||||
if (!jsonObj.userId) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
return jsonObj.userId;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Route to know if rooms need authentication to join
|
// Route to know if rooms need authentication to join
|
||||||
public async getRoomsRequireAuth(): Promise<any> {
|
public async getRoomsRequireAuth(): Promise<any> {
|
||||||
const url: string = this.constructRequestUrl(`/auth/getRoomsRequireAuth`);
|
const url: string = this.constructRequestUrl(`/auth/getRoomsRequireAuth`);
|
||||||
|
|
@ -1147,99 +1130,7 @@ public async login(email: string, password: string): Promise<any> {
|
||||||
return `ERROR : Une erreur inattendue s'est produite.`
|
return `ERROR : Une erreur inattendue s'est produite.`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// NOTE : Get Image pas necessaire
|
||||||
public async getImages(page: number, limit: number): Promise<ImagesResponse> {
|
|
||||||
try {
|
|
||||||
const url: string = this.constructRequestUrl(`/image/getImages`);
|
|
||||||
const headers = this.constructRequestHeaders();
|
|
||||||
let params : ImagesParams = { page: page, limit: limit };
|
|
||||||
|
|
||||||
const result: AxiosResponse = await axios.get(url, { params: params, headers: headers });
|
|
||||||
|
|
||||||
if (result.status !== 200) {
|
|
||||||
throw new Error(`L'affichage des images a échoué. Status: ${result.status}`);
|
|
||||||
}
|
|
||||||
const images = result.data;
|
|
||||||
|
|
||||||
return images;
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.log("Error details: ", error);
|
|
||||||
|
|
||||||
if (axios.isAxiosError(error)) {
|
|
||||||
const err = error as AxiosError;
|
|
||||||
const data = err.response?.data as { error: string } | undefined;
|
|
||||||
const msg = data?.error || 'Erreur serveur inconnue lors de la requête.';
|
|
||||||
throw new Error(`L'enregistrement a échoué. Status: ${msg}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`ERROR : Une erreur inattendue s'est produite.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async getUserImages(page: number, limit: number): Promise<ImagesResponse> {
|
|
||||||
try {
|
|
||||||
const url: string = this.constructRequestUrl(`/image/getUserImages`);
|
|
||||||
const headers = this.constructRequestHeaders();
|
|
||||||
let params : ImagesParams = { page: page, limit: limit };
|
|
||||||
|
|
||||||
const uid = this.getUserID();
|
|
||||||
if(uid !== ''){
|
|
||||||
params.uid = uid;
|
|
||||||
}
|
|
||||||
|
|
||||||
const result: AxiosResponse = await axios.get(url, { params: params, headers: headers });
|
|
||||||
|
|
||||||
if (result.status !== 200) {
|
|
||||||
throw new Error(`L'affichage des images de l'utilisateur a échoué. Status: ${result.status}`);
|
|
||||||
}
|
|
||||||
const images = result.data;
|
|
||||||
|
|
||||||
return images;
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.log("Error details: ", error);
|
|
||||||
|
|
||||||
if (axios.isAxiosError(error)) {
|
|
||||||
const err = error as AxiosError;
|
|
||||||
const data = err.response?.data as { error: string } | undefined;
|
|
||||||
const msg = data?.error || 'Erreur serveur inconnue lors de la requête.';
|
|
||||||
throw new Error(`L'enregistrement a échoué. Status: ${msg}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`ERROR : Une erreur inattendue s'est produite.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async deleteImage(imgId: string): Promise<ApiResponse> {
|
|
||||||
try {
|
|
||||||
const url: string = this.constructRequestUrl(`/image/delete`);
|
|
||||||
const headers = this.constructRequestHeaders();
|
|
||||||
const uid = this.getUserID();
|
|
||||||
let params = { uid: uid, imgId: imgId };
|
|
||||||
|
|
||||||
const result: AxiosResponse = await axios.delete(url, { params: params, headers: headers });
|
|
||||||
|
|
||||||
if (result.status !== 200) {
|
|
||||||
throw new Error(`La suppression de l'image a échoué. Status: ${result.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const deleted = result.data.deleted;
|
|
||||||
return deleted;
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.log("Error details: ", error);
|
|
||||||
|
|
||||||
if (axios.isAxiosError(error)) {
|
|
||||||
const err = error as AxiosError;
|
|
||||||
const data = err.response?.data as { error: string } | undefined;
|
|
||||||
const msg = data?.error || 'Erreur serveur inconnue lors de la requête.';
|
|
||||||
throw new Error(`L'enregistrement a échoué. Status: ${msg}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`ERROR : Une erreur inattendue s'est produite.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async getAllQuizIds(): Promise<string[]> {
|
public async getAllQuizIds(): Promise<string[]> {
|
||||||
try {
|
try {
|
||||||
|
|
|
||||||
|
|
@ -7,8 +7,6 @@ services:
|
||||||
context: ./client
|
context: ./client
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
container_name: frontend
|
container_name: frontend
|
||||||
environment:
|
|
||||||
VITE_IMG_URL: http://localhost
|
|
||||||
ports:
|
ports:
|
||||||
- "5173:5173"
|
- "5173:5173"
|
||||||
restart: always
|
restart: always
|
||||||
|
|
@ -56,7 +54,7 @@ services:
|
||||||
image: mongo
|
image: mongo
|
||||||
container_name: mongo
|
container_name: mongo
|
||||||
ports:
|
ports:
|
||||||
- "27019:27017"
|
- "27017:27017"
|
||||||
tty: true
|
tty: true
|
||||||
volumes:
|
volumes:
|
||||||
- mongodb_data:/data/db
|
- mongodb_data:/data/db
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,6 @@ services:
|
||||||
- VITE_BACKEND_URL=
|
- VITE_BACKEND_URL=
|
||||||
# Define empty VITE_BACKEND_SOCKET_URL so it will default to window.location.host
|
# Define empty VITE_BACKEND_SOCKET_URL so it will default to window.location.host
|
||||||
- VITE_BACKEND_SOCKET_URL=
|
- VITE_BACKEND_SOCKET_URL=
|
||||||
- VITE_IMG_URL=https://evalsa.etsmtl.ca
|
|
||||||
ports:
|
ports:
|
||||||
- "5173:5173"
|
- "5173:5173"
|
||||||
restart: always
|
restart: always
|
||||||
|
|
|
||||||
|
|
@ -7,9 +7,6 @@
|
||||||
|
|
||||||
// const BASE_URL = '/image'
|
// const BASE_URL = '/image'
|
||||||
|
|
||||||
const Images = require('../models/images');
|
|
||||||
const ObjectId = require('mongodb').ObjectId;
|
|
||||||
|
|
||||||
describe.skip("POST /upload", () => {
|
describe.skip("POST /upload", () => {
|
||||||
|
|
||||||
describe("when the jwt is not sent", () => {
|
describe("when the jwt is not sent", () => {
|
||||||
|
|
@ -67,289 +64,3 @@ describe.skip("GET /get", () => {
|
||||||
})
|
})
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
jest.mock('mongodb', () => {
|
|
||||||
const originalModule = jest.requireActual('mongodb');
|
|
||||||
return {
|
|
||||||
...originalModule,
|
|
||||||
ObjectId: {
|
|
||||||
...originalModule.ObjectId,
|
|
||||||
createFromHexString: jest.fn().mockReturnValue('507f191e810c19729de860ea'), // Return a valid 24-character ObjectId string
|
|
||||||
},
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('Images', () => {
|
|
||||||
let db;
|
|
||||||
let images;
|
|
||||||
let dbConn;
|
|
||||||
let mockImagesCollection;
|
|
||||||
let mockFindCursor;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
|
|
||||||
const mockImagesCursor = {
|
|
||||||
sort: jest.fn().mockReturnThis(),
|
|
||||||
skip: jest.fn().mockReturnThis(),
|
|
||||||
limit: jest.fn().mockReturnThis(),
|
|
||||||
toArray: jest.fn()
|
|
||||||
};
|
|
||||||
|
|
||||||
const mockFilesCursor = {
|
|
||||||
sort: jest.fn().mockReturnThis(),
|
|
||||||
skip: jest.fn().mockReturnThis(),
|
|
||||||
limit: jest.fn().mockReturnThis(),
|
|
||||||
toArray: jest.fn()
|
|
||||||
};
|
|
||||||
|
|
||||||
mockImagesCollection = {
|
|
||||||
insertOne: jest.fn().mockResolvedValue({ insertedId: 'image123' }),
|
|
||||||
findOne: jest.fn(),
|
|
||||||
find: jest.fn().mockReturnValue(mockImagesCursor),
|
|
||||||
countDocuments: jest.fn(),
|
|
||||||
deleteOne: jest.fn()
|
|
||||||
};
|
|
||||||
|
|
||||||
mockFilesCollection = {
|
|
||||||
find: jest.fn().mockReturnValue(mockFilesCursor)
|
|
||||||
};
|
|
||||||
|
|
||||||
dbConn = {
|
|
||||||
collection: jest.fn((name) => {
|
|
||||||
if (name === 'images') {
|
|
||||||
return mockImagesCollection;
|
|
||||||
} else if (name === 'files') {
|
|
||||||
return mockFilesCollection;
|
|
||||||
}
|
|
||||||
})
|
|
||||||
};
|
|
||||||
|
|
||||||
db = {
|
|
||||||
connect: jest.fn().mockResolvedValue(),
|
|
||||||
getConnection: jest.fn().mockReturnValue(dbConn)
|
|
||||||
};
|
|
||||||
|
|
||||||
images = new Images(db);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('upload', () => {
|
|
||||||
it('should upload an image and return the inserted ID', async () => {
|
|
||||||
const testFile = { originalname: 'test.png', buffer: Buffer.from('dummydata'), mimetype: 'image/png' };
|
|
||||||
const userId = 'user123';
|
|
||||||
|
|
||||||
const result = await images.upload(testFile, userId);
|
|
||||||
|
|
||||||
expect(db.connect).toHaveBeenCalled();
|
|
||||||
expect(db.getConnection).toHaveBeenCalled();
|
|
||||||
expect(dbConn.collection).toHaveBeenCalledWith('images');
|
|
||||||
expect(mockImagesCollection.insertOne).toHaveBeenCalledWith({
|
|
||||||
userId: userId,
|
|
||||||
file_name: 'test.png',
|
|
||||||
file_content: testFile.buffer.toString('base64'),
|
|
||||||
mime_type: 'image/png',
|
|
||||||
created_at: expect.any(Date)
|
|
||||||
});
|
|
||||||
expect(result).toBe('image123');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('get', () => {
|
|
||||||
it('should retrieve the image if found', async () => {
|
|
||||||
const imageId = '65d9a8f9b5e8d1a5e6a8c9f0';
|
|
||||||
const testImage = {
|
|
||||||
file_name: 'test.png',
|
|
||||||
file_content: Buffer.from('dummydata').toString('base64'),
|
|
||||||
mime_type: 'image/png'
|
|
||||||
};
|
|
||||||
mockImagesCollection.findOne.mockResolvedValue(testImage);
|
|
||||||
|
|
||||||
const result = await images.get(imageId);
|
|
||||||
|
|
||||||
expect(db.connect).toHaveBeenCalled();
|
|
||||||
expect(db.getConnection).toHaveBeenCalled();
|
|
||||||
expect(dbConn.collection).toHaveBeenCalledWith('images');
|
|
||||||
expect(mockImagesCollection.findOne).toHaveBeenCalledWith({ _id: ObjectId.createFromHexString(imageId) });
|
|
||||||
expect(result).toEqual({
|
|
||||||
file_name: 'test.png',
|
|
||||||
file_content: Buffer.from('dummydata'),
|
|
||||||
mime_type: 'image/png'
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return null if image is not found', async () => {
|
|
||||||
const imageId = '65d9a8f9b5e8d1a5e6a8c9f0';
|
|
||||||
mockImagesCollection.findOne.mockResolvedValue(null);
|
|
||||||
|
|
||||||
const result = await images.get(imageId);
|
|
||||||
|
|
||||||
expect(result).toBeNull();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('getImages', () => {
|
|
||||||
it('should retrieve a paginated list of images', async () => {
|
|
||||||
const mockImages = [
|
|
||||||
{ _id: '1', userId: 'user1', file_name: 'image1.png', file_content: Buffer.from('data1'), mime_type: 'image/png' },
|
|
||||||
{ _id: '2', userId: 'user2', file_name: 'image2.png', file_content: Buffer.from('data2'), mime_type: 'image/png' }
|
|
||||||
];
|
|
||||||
|
|
||||||
mockImagesCollection.countDocuments.mockResolvedValue(2);
|
|
||||||
// Create a mock cursor for images collection
|
|
||||||
const mockFindCursor = {
|
|
||||||
sort: jest.fn().mockReturnThis(),
|
|
||||||
skip: jest.fn().mockReturnThis(),
|
|
||||||
limit: jest.fn().mockReturnThis(),
|
|
||||||
toArray: jest.fn().mockResolvedValue(mockImages), // Return mock images when toArray is called
|
|
||||||
};
|
|
||||||
|
|
||||||
// Mock the find method to return the mock cursor
|
|
||||||
mockImagesCollection.find.mockReturnValue(mockFindCursor);
|
|
||||||
const result = await images.getImages(1, 10);
|
|
||||||
|
|
||||||
expect(db.connect).toHaveBeenCalled();
|
|
||||||
expect(db.getConnection).toHaveBeenCalled();
|
|
||||||
expect(dbConn.collection).toHaveBeenCalledWith('images');
|
|
||||||
expect(mockImagesCollection.find).toHaveBeenCalledWith({});
|
|
||||||
expect(mockFindCursor.sort).toHaveBeenCalledWith({ created_at: 1 });
|
|
||||||
expect(mockFindCursor.skip).toHaveBeenCalledWith(0);
|
|
||||||
expect(mockFindCursor.limit).toHaveBeenCalledWith(10);
|
|
||||||
expect(result).toEqual({
|
|
||||||
images: [
|
|
||||||
{ id: '1', user: 'user1', file_name: 'image1.png', file_content: 'ZGF0YTE=', mime_type: 'image/png' },
|
|
||||||
{ id: '2', user: 'user2', file_name: 'image2.png', file_content: 'ZGF0YTI=', mime_type: 'image/png' }
|
|
||||||
],
|
|
||||||
total: 2,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return an empty array if no images are found', async () => {
|
|
||||||
mockImagesCollection.countDocuments.mockResolvedValue(0);
|
|
||||||
|
|
||||||
const result = await images.getImages(1, 10);
|
|
||||||
|
|
||||||
expect(result).toEqual({ images: [], total: 0 });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('getUserImages', () => {
|
|
||||||
it('should return empty images array when no images exist', async () => {
|
|
||||||
mockImagesCollection.countDocuments.mockResolvedValue(0);
|
|
||||||
|
|
||||||
const result = await images.getUserImages(1, 10, 'user123');
|
|
||||||
|
|
||||||
expect(result).toEqual({ images: [], total: 0 });
|
|
||||||
expect(db.connect).toHaveBeenCalled();
|
|
||||||
expect(mockImagesCollection.countDocuments).toHaveBeenCalledWith({ userId: 'user123' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return images when they exist', async () => {
|
|
||||||
const mockImages = [
|
|
||||||
{
|
|
||||||
_id: 'img1',
|
|
||||||
userId: 'user123',
|
|
||||||
file_name: 'image1.png',
|
|
||||||
file_content: Buffer.from('testdata'),
|
|
||||||
mime_type: 'image/png'
|
|
||||||
}
|
|
||||||
];
|
|
||||||
|
|
||||||
mockImagesCollection.countDocuments.mockResolvedValue(1);
|
|
||||||
mockImagesCollection.find.mockReturnValue({
|
|
||||||
sort: jest.fn().mockReturnThis(),
|
|
||||||
skip: jest.fn().mockReturnThis(),
|
|
||||||
limit: jest.fn().mockReturnThis(),
|
|
||||||
toArray: jest.fn().mockResolvedValue(mockImages)
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await images.getUserImages(1, 10, 'user123');
|
|
||||||
|
|
||||||
expect(result).toEqual({
|
|
||||||
images: [
|
|
||||||
{
|
|
||||||
id: 'img1',
|
|
||||||
user: 'user123',
|
|
||||||
file_name: 'image1.png',
|
|
||||||
file_content: Buffer.from('testdata').toString('base64'),
|
|
||||||
mime_type: 'image/png'
|
|
||||||
}
|
|
||||||
],
|
|
||||||
total: 1
|
|
||||||
});
|
|
||||||
expect(db.connect).toHaveBeenCalled();
|
|
||||||
expect(mockImagesCollection.countDocuments).toHaveBeenCalledWith({ userId: 'user123' });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
describe('delete', () => {
|
|
||||||
it('should not delete the image when it exists in the files collection', async () => {
|
|
||||||
const uid = 'user123';
|
|
||||||
const imgId = '507f191e810c19729de860ea'; // A valid 24-character ObjectId string
|
|
||||||
|
|
||||||
// Mock the files collection cursor to simulate an image found
|
|
||||||
const mockFilesCursor = {
|
|
||||||
toArray: jest.fn().mockResolvedValue([{ _id: imgId }]) // Image found
|
|
||||||
};
|
|
||||||
|
|
||||||
mockFilesCollection.find.mockReturnValue(mockFilesCursor);
|
|
||||||
mockImagesCollection.deleteOne.mockResolvedValue({ deletedCount: 0 });
|
|
||||||
|
|
||||||
const result = await images.delete(uid, imgId);
|
|
||||||
|
|
||||||
// Ensure the files collection is queried
|
|
||||||
expect(dbConn.collection).toHaveBeenCalledWith('files');
|
|
||||||
expect(mockFilesCollection.find).toHaveBeenCalledWith({
|
|
||||||
userId: uid,
|
|
||||||
content: { $regex: new RegExp(`/api/image/get/${imgId}`) },
|
|
||||||
});
|
|
||||||
|
|
||||||
// Ensure the images collection is queried for deletion
|
|
||||||
expect(dbConn.collection).toHaveBeenCalledWith('files');
|
|
||||||
expect(mockImagesCollection.deleteOne).not.toHaveBeenCalledWith({
|
|
||||||
_id: ObjectId.createFromHexString(imgId), // Ensure the ObjectId is created correctly
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result).toEqual({ deleted: false });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should delete the image if not found in the files collection', async () => {
|
|
||||||
const uid = 'user123';
|
|
||||||
const imgId = '507f191e810c19729de860ea';
|
|
||||||
|
|
||||||
// Mock the files collection cursor to simulate the image not being found
|
|
||||||
const mockFindCursor = {
|
|
||||||
toArray: jest.fn().mockResolvedValue([]) // Empty array means image not found
|
|
||||||
};
|
|
||||||
|
|
||||||
mockFilesCollection.find.mockReturnValue(mockFindCursor);
|
|
||||||
mockImagesCollection.deleteOne.mockResolvedValue({ deletedCount: 1 });
|
|
||||||
|
|
||||||
const result = await images.delete(uid, imgId);
|
|
||||||
|
|
||||||
// Ensure the deleteOne is not called if the image is not found
|
|
||||||
expect(mockImagesCollection.deleteOne).toHaveBeenCalled();
|
|
||||||
expect(result).toEqual({ deleted: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return false if the delete operation fails in the images collection', async () => {
|
|
||||||
const uid = 'user123';
|
|
||||||
const imgId = '507f191e810c19729de860ea';
|
|
||||||
|
|
||||||
// Mock the files collection cursor to simulate the image being found
|
|
||||||
const mockFindCursor = {
|
|
||||||
toArray: jest.fn().mockResolvedValue([{ _id: imgId }]) // Image found
|
|
||||||
};
|
|
||||||
|
|
||||||
mockFilesCollection.find.mockReturnValue(mockFindCursor);
|
|
||||||
mockImagesCollection.deleteOne.mockResolvedValue({ deletedCount: 0 }); // Simulate failure
|
|
||||||
|
|
||||||
const result = await images.delete(uid, imgId);
|
|
||||||
|
|
||||||
// Ensure the images collection deletion is called
|
|
||||||
expect(mockImagesCollection.deleteOne).not.toHaveBeenCalledWith({
|
|
||||||
_id: ObjectId.createFromHexString(imgId), // Ensure the ObjectId is created correctly
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result).toEqual({ deleted: false });
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -50,58 +50,6 @@ class ImagesController {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
getImages = async (req, res, next) => {
|
|
||||||
try {
|
|
||||||
const page = parseInt(req.query.page) || 1;
|
|
||||||
const limit = parseInt(req.query.limit) || 5;
|
|
||||||
const images = await this.images.getImages(page, limit);
|
|
||||||
|
|
||||||
if (!images || images.length === 0) {
|
|
||||||
throw new AppError(IMAGE_NOT_FOUND);
|
|
||||||
}
|
|
||||||
|
|
||||||
res.setHeader('Content-Type', 'application/json');
|
|
||||||
return res.status(200).json(images);
|
|
||||||
} catch (error) {
|
|
||||||
return next(error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
getUserImages = async (req, res, next) => {
|
|
||||||
try {
|
|
||||||
const page = parseInt(req.query.page) || 1;
|
|
||||||
const limit = parseInt(req.query.limit) || 5;
|
|
||||||
const uid = req.query.uid;
|
|
||||||
const images = await this.images.getUserImages(page, limit, uid);
|
|
||||||
|
|
||||||
if (!images || images.length === 0) {
|
|
||||||
throw new AppError(IMAGE_NOT_FOUND);
|
|
||||||
}
|
|
||||||
|
|
||||||
res.setHeader('Content-Type', 'application/json');
|
|
||||||
return res.status(200).json(images);
|
|
||||||
} catch (error) {
|
|
||||||
return next(error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
delete = async (req, res, next) => {
|
|
||||||
try {
|
|
||||||
const uid = req.query.uid;
|
|
||||||
const imgId = req.query.imgId;
|
|
||||||
|
|
||||||
if (!uid || !imgId) {
|
|
||||||
throw new AppError(MISSING_REQUIRED_PARAMETER);
|
|
||||||
}
|
|
||||||
const images = await this.images.delete(uid, imgId);
|
|
||||||
|
|
||||||
res.setHeader('Content-Type', 'application/json');
|
|
||||||
return res.status(200).json(images);
|
|
||||||
} catch (error) {
|
|
||||||
return next(error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = ImagesController;
|
module.exports = ImagesController;
|
||||||
|
|
|
||||||
|
|
@ -42,84 +42,6 @@ class Images {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async getImages(page, limit) {
|
|
||||||
await this.db.connect()
|
|
||||||
const conn = this.db.getConnection();
|
|
||||||
|
|
||||||
const imagesCollection = conn.collection('images');
|
|
||||||
|
|
||||||
|
|
||||||
const total = await imagesCollection.countDocuments();
|
|
||||||
if (!total || total === 0) return { images: [], total };
|
|
||||||
|
|
||||||
const result = await imagesCollection.find({})
|
|
||||||
.sort({ created_at: 1 })
|
|
||||||
.skip((page - 1) * limit)
|
|
||||||
.limit(limit)
|
|
||||||
.toArray();
|
|
||||||
|
|
||||||
const objImages = result.map(image => ({
|
|
||||||
id: image._id,
|
|
||||||
user: image.userId,
|
|
||||||
file_name: image.file_name,
|
|
||||||
file_content: image.file_content.toString('base64'),
|
|
||||||
mime_type: image.mime_type
|
|
||||||
}));
|
|
||||||
|
|
||||||
let respObj = {
|
|
||||||
images: objImages,
|
|
||||||
total: total
|
|
||||||
}
|
|
||||||
|
|
||||||
return respObj;
|
|
||||||
}
|
|
||||||
|
|
||||||
async getUserImages(page, limit, uid) {
|
|
||||||
await this.db.connect()
|
|
||||||
const conn = this.db.getConnection();
|
|
||||||
const imagesCollection = conn.collection('images');
|
|
||||||
const total = await imagesCollection.countDocuments({ userId: uid });
|
|
||||||
if (!total || total === 0) return { images: [], total };
|
|
||||||
|
|
||||||
const result = await imagesCollection.find({ userId: uid })
|
|
||||||
.sort({ created_at: -1 })
|
|
||||||
.skip((page - 1) * limit)
|
|
||||||
.limit(limit)
|
|
||||||
.toArray();
|
|
||||||
|
|
||||||
const objImages = result.map(image => ({
|
|
||||||
id: image._id,
|
|
||||||
user: image.userId,
|
|
||||||
file_name: image.file_name,
|
|
||||||
file_content: image.file_content.toString('base64'),
|
|
||||||
mime_type: image.mime_type
|
|
||||||
}));
|
|
||||||
|
|
||||||
let respObj = {
|
|
||||||
images: objImages,
|
|
||||||
total: total
|
|
||||||
}
|
|
||||||
|
|
||||||
return respObj;
|
|
||||||
}
|
|
||||||
|
|
||||||
async delete(uid, imgId) {
|
|
||||||
let resp = false;
|
|
||||||
await this.db.connect()
|
|
||||||
const conn = this.db.getConnection();
|
|
||||||
const quizColl = conn.collection('files');
|
|
||||||
const rgxImg = new RegExp(`/api/image/get/${imgId}`);
|
|
||||||
|
|
||||||
const result = await quizColl.find({ userId: uid, content: { $regex: rgxImg }}).toArray();
|
|
||||||
if(!result || result.length < 1){
|
|
||||||
const imgsColl = conn.collection('images');
|
|
||||||
const isDeleted = await imgsColl.deleteOne({ _id: ObjectId.createFromHexString(imgId) });
|
|
||||||
if(isDeleted){
|
|
||||||
resp = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { deleted: resp };
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = Images;
|
module.exports = Images;
|
||||||
|
|
|
||||||
|
|
@ -12,8 +12,5 @@ const upload = multer({ storage: storage });
|
||||||
|
|
||||||
router.post("/upload", jwt.authenticate, upload.single('image'), asyncHandler(images.upload));
|
router.post("/upload", jwt.authenticate, upload.single('image'), asyncHandler(images.upload));
|
||||||
router.get("/get/:id", asyncHandler(images.get));
|
router.get("/get/:id", asyncHandler(images.get));
|
||||||
router.get("/getImages", asyncHandler(images.getImages));
|
|
||||||
router.get("/getUserImages", jwt.authenticate, asyncHandler(images.getUserImages));
|
|
||||||
router.delete("/delete", jwt.authenticate, asyncHandler(images.delete));
|
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue