Files
2024-10-15 21:37:55 +00:00

106 lines
3.2 KiB
TypeScript

import { get } from "http";
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: pterodactyl.workingDirectory,
files: [
{
from: from.attributes.name,
to: newName,
},
],
}),
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
console.log(response);
} 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?directory=${pterodactyl.workingDirectory}`,
{
method: "GET",
headers: await pterodactyl.helpers.authHeader(),
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const sortedFileList = data.data.sort((a: File, b: File) => {
// Sort directories before files
if (!a.attributes.is_file && b.attributes.is_file) return -1;
if (a.attributes.is_file && !b.attributes.is_file) return 1;
// Sort alphabetically by name
return a.attributes.name.localeCompare(b.attributes.name);
});
return data.data;
} catch (error) {
console.error("Error fetching data:", error);
}
},
async getContent(filename: string) {
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_URL}/api/client/servers/${pterodactyl.server_id}/files/contents?file=${filename}`,
{
method: "GET",
headers: await pterodactyl.helpers.authHeader(),
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.text();
return data;
} catch (error) {
console.error("Error fetching data:", error);
}
},
async saveContent(filename: string, content: string) {
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_URL}/api/client/servers/${pterodactyl.server_id}/files/write?file=${filename}`,
{
method: "POST",
headers: await pterodactyl.helpers.authHeader("application/text"),
body: "'test'",
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Error fetching data:", error);
}
},
async createFile(filename: string) {
this.saveContent(filename, "");
},
};
}