add functionality and refactor the code

This commit is contained in:
2024-08-31 08:19:41 +00:00
parent 32d9bc96b5
commit be78e17fb9
7 changed files with 207 additions and 76 deletions

View File

@@ -2,11 +2,12 @@ import React from "react";
interface Props { interface Props {
closeRemapFunction: () => void; closeRemapFunction: () => void;
renameCallback: (file: any, newName: string) => void;
file: any; file: any;
} }
const Rename = (props: Props) => { const Rename = (props: Props) => {
const { closeRemapFunction, file } = props; const { closeRemapFunction, file, renameCallback } = props;
const [newName, setNewName] = React.useState(file.attributes.name); const [newName, setNewName] = React.useState(file.attributes.name);
const handleKeyDown = (event: React.KeyboardEvent) => { const handleKeyDown = (event: React.KeyboardEvent) => {
@@ -19,9 +20,9 @@ const Rename = (props: Props) => {
}; };
const handleRename = (event: React.MouseEvent) => { const handleRename = (event: React.MouseEvent) => {
// console.log("rename"); // use from parent function named putRenameFile
console.log("Renaming file:", file?.attributes.name, "to", newName); // renameFunction(file, newName);
console.log(file); renameCallback(file, newName);
}; };
const ref = React.useRef<HTMLDivElement>(null); const ref = React.useRef<HTMLDivElement>(null);

View File

@@ -1,111 +1,128 @@
"use client"; "use client";
import { formatDistanceToNow } from "date-fns"; import { formatDistanceToNow } from "date-fns";
import React, { useEffect, useState, useRef } from "react"; import React, { useEffect, useState, useCallback } from "react";
import DocumentIcon from "@/components/Icons/Document"; import DocumentIcon from "@/components/Icons/Document";
import FolderIcon from "@/components/Icons/Folder"; import FolderIcon from "@/components/Icons/Folder";
import MenuIcon from "@/components/Icons/Menu"; import MenuIcon from "@/components/Icons/Menu";
import ContextMenuContainer from "./ContextMenu/container"; import ContextMenuContainer from "./ContextMenu/container";
import RenamePopup from "./ContextMenu/rename"; import RenamePopup from "./ContextMenu/rename";
import Pterodactyl from "@/components/Pterodactyl";
const initialContextMenu = { interface FileAttributes {
name: string;
modified_at: string;
size: number;
is_file: boolean;
}
interface FileProps {
attributes: FileAttributes;
}
interface ContextMenuState {
show: boolean;
x: number;
y: number;
file: FileProps | null;
}
interface RenamePopupState {
show: boolean;
}
const initialContextMenuState: ContextMenuState = {
show: false, show: false,
x: 0, x: 0,
y: 0, y: 0,
file: null, file: null,
}; };
const renamePopupProps = { const initialRenamePopupState: RenamePopupState = {
show: false, show: false,
}; };
interface FileProps {
attributes: {
name: string;
modified_at: string;
size: number;
is_file: boolean;
};
}
const Index = () => { const Index = () => {
const [apiKey, setApiKey] = useState(""); const [apiKey, setApiKey] = useState<string>("");
const [fileList, setFileList] = useState([]); const [fileList, setFileList] = useState<FileProps[]>([]);
const [contextMenu, setContextMenu] = useState(initialContextMenu); const [contextMenu, setContextMenu] = useState<ContextMenuState>(
const [renamePopup, setRenamePopup] = useState(renamePopupProps); initialContextMenuState
const [file, setFile] = useState<FileProps | null>(null); );
const [renamePopup, setRenamePopup] = useState<RenamePopupState>(
initialRenamePopupState
);
const [selectedFile, setSelectedFile] = useState<FileProps | null>(null);
const [ptero, setPtero] = useState<Pterodactyl | null>(null);
const [serverId, setServerId] = useState<string>("");
const showRenamePopup = () => { const setCredentials = useCallback(async () => {
console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); setApiKey("ptlc_N77A2hEczFmSwGXm4cEXh4Gw3ZP0Ygr5NaBkGlE7pjU");
setContextMenu(initialContextMenu); setServerId("ec46691a");
}, []);
const showRenamePopup = useCallback(() => {
setContextMenu(initialContextMenuState);
setRenamePopup({ show: true }); setRenamePopup({ show: true });
}; }, []);
const closeRenamePopup = () => { const closeRenamePopup = useCallback(() => {
setRenamePopup(renamePopupProps); setRenamePopup(initialRenamePopupState);
}; }, []);
const handleClickContextMenu = (
e: React.MouseEvent<HTMLDivElement, MouseEvent>,
file: any
) => {
e.preventDefault();
const { pageX, pageY } = e;
setContextMenu({ show: true, x: pageX, y: pageY, file });
};
const handleContextMenuClose = () => {
setContextMenu(initialContextMenu);
};
const setCredentials = async () => {
setApiKey("ptlc_aDGU4VHNQuN5t6dyxNzVon3UZLR5ehuySmdR7xsUbMm");
};
const formateDate = (isoDate: string) => { const formateDate = (isoDate: string) => {
const date = new Date(isoDate); const date = new Date(isoDate);
return formatDistanceToNow(date, { addSuffix: true }); return formatDistanceToNow(date, { addSuffix: true });
}; };
const fetchFiles = async (apiKey: string) => { const handleRenameFile = useCallback(
try { (file: FileProps, newName: string) => {
const response = await fetch( if (ptero) {
"https://ptero.przeqpiciel.com/api/client/servers/0bf192ab/files/list", ptero.files.rename(file, newName);
{
method: "GET",
headers: {
Authorization: `Bearer ${apiKey.toString()}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
} }
const data = await response.json(); setRenamePopup(initialRenamePopupState);
setFileList(data.data); },
} catch (error) { [ptero]
console.error("Error fetching data:", error); );
}
}; const handleClickContextMenu = useCallback(
(e: React.MouseEvent<HTMLDivElement>, file: FileProps) => {
e.preventDefault();
setContextMenu({ show: true, x: e.pageX, y: e.pageY, file });
},
[]
);
const handleContextMenuClose = useCallback(() => {
setContextMenu(initialContextMenuState);
}, []);
const formatDate = useCallback((isoDate: string) => {
return formatDistanceToNow(new Date(isoDate), { addSuffix: true });
}, []);
useEffect(() => { useEffect(() => {
const fetchData = async () => { const setupApplication = async () => {
await setCredentials(); await setCredentials();
while (apiKey === "") { while (!apiKey) {
await new Promise((r) => setTimeout(r, 200)); await new Promise((r) => setTimeout(r, 200));
} }
await fetchFiles(apiKey); const pterodactylInstance = new Pterodactyl(serverId, apiKey);
setPtero(pterodactylInstance);
const files = await pterodactylInstance.files.fetchFiles();
setFileList(files);
}; };
fetchData(); setupApplication();
}, [apiKey]); }, [apiKey, serverId, setCredentials]);
return ( return (
<> <>
{renamePopup.show && ( {renamePopup.show && (
<RenamePopup file={file} closeRemapFunction={closeRenamePopup} /> <RenamePopup
file={selectedFile}
renameCallback={handleRenameFile}
closeRemapFunction={closeRenamePopup}
/>
)} )}
{contextMenu.show && ( {contextMenu.show && (
<ContextMenuContainer <ContextMenuContainer
@@ -113,10 +130,11 @@ const Index = () => {
y={contextMenu.y} y={contextMenu.y}
closeContextMenu={handleContextMenuClose} closeContextMenu={handleContextMenuClose}
renameFunction={showRenamePopup} renameFunction={showRenamePopup}
setFile={setFile} setFile={setSelectedFile}
file={contextMenu.file} file={contextMenu.file}
/> />
)} )}
{fileList.map((file: FileProps) => ( {fileList.map((file: FileProps) => (
<div <div
className="flex justify-between gap-4 bg-content mb-1 hover:bg-neutral-content pl-4 pr-4 pt-1 pb-1 rounded-md" className="flex justify-between gap-4 bg-content mb-1 hover:bg-neutral-content pl-4 pr-4 pt-1 pb-1 rounded-md"

View File

@@ -0,0 +1,56 @@
import { File } from "./interfaces";
export default function files(pterodactyl: any) {
return {
async rename(from: File, newName: string) {
console.log("rename", from);
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_URL}/api/client/servers/${pterodactyl.server_id}/files/rename`,
{
method: "PUT",
headers: await pterodactyl.helpers.authHeader(),
body: JSON.stringify({
root: "/",
files: [
{
from: from.attributes.name,
to: newName,
},
],
}),
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
console.log(response);
if (response.ok) {
// fetchFiles();
}
} catch (error) {
console.error("Error fetching data:", error);
}
},
async fetchFiles() {
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_URL}/api/client/servers/${pterodactyl.server_id}/files/list`,
{
method: "GET",
headers: await pterodactyl.helpers.authHeader(),
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.data;
} catch (error) {
console.error("Error fetching data:", error);
}
},
};
}

View File

@@ -0,0 +1,22 @@
export default function helpers(pterodactyl: any) {
return {
// helper what return auth header
async authHeader() {
return {
Authorization: `Bearer ${pterodactyl.api_key}`,
"Content-Type": "application/json",
Accept: "Application/vnd.pterodactyl.v1+json",
};
},
// setter for api key
async setApiKey(apiKey: string) {
return (pterodactyl.api_key = apiKey);
},
// setter for server id
async setServerID(serverID: string) {
return (pterodactyl.server_id = serverID);
},
};
}

View File

@@ -0,0 +1,18 @@
import filesModule from "./files";
import helpersModule from "./helpers";
class Pterodactyl {
server_id: string;
api_key: string;
files: any;
helpers: any;
constructor(server_id: string, api_key: string) {
this.server_id = server_id;
this.api_key = api_key;
this.files = filesModule(this);
this.helpers = helpersModule(this);
}
}
export default Pterodactyl;

View File

@@ -0,0 +1,17 @@
export interface File {
attributes: {
name: string;
modified_at: string;
size: number;
is_file: boolean;
directory: string;
};
}
export interface Pterodactyl {
server_id: string;
api_key: string;
files: any;
constructor(server_id: string, api_key: string): void;
}

View File

@@ -27,15 +27,14 @@ const Console = () => {
const textareaRef = useRef<HTMLTextAreaElement>(null); // Dodajemy referencję do textarea const textareaRef = useRef<HTMLTextAreaElement>(null); // Dodajemy referencję do textarea
const setCredentials = async () => { const setCredentials = async () => {
setApiKey("ptlc_aDGU4VHNQuN5t6dyxNzVon3UZLR5ehuySmdR7xsUbMm"); setApiKey("ptlc_N77A2hEczFmSwGXm4cEXh4Gw3ZP0Ygr5NaBkGlE7pjU");
}; };
const fetchData = async (apiKey: string) => { const fetchData = async (apiKey: string) => {
console.log("Fetching data..."); console.log("Fetching data...");
console.log(apiKey);
try { try {
const response = await fetch( const response = await fetch(
"https://ptero.przeqpiciel.com/api/client/servers/0bf192ab/websocket", `${process.env.NEXT_PUBLIC_URL}/api/client/servers/ec46691a/websocket`,
{ {
method: "GET", method: "GET",
headers: { headers: {