import config from "@/utils/config.json";
import { userDetails } from "@/utils/types";
import * as apiTypes from "@/utils/api/types";
import { getAPI } from "@/utils/api";
const placeID = window.location.pathname.split("/")[3];
/**
* Adds a button to the manage page of places allowing users to quickly download their place files from the website.
*/
export function placeFileExport() {
const publicAPI = getAPI("public");
const internalAPI = getAPI("internal");
if (!publicAPI.enabled || !internalAPI.enabled) {
throw new Error(
"[Poly+] API is disabled, cancelling place file export loading..",
);
}
const retrievePlaceFile = async function () {
const editReq: apiTypes.editApiSchema =
await (await fetch(internalAPI.url + "places/edit/", {
method: "POST",
body: JSON.stringify({
placeID: placeID,
}),
})).json();
if (!editReq.success) {
throw new Error(
"[Poly+] There was an error while retrieving the authenticated user's creator authorization token.",
);
}
const placeContents = await (await fetch(
`${publicAPI.url}places/get-place?id=${placeID}&tokenType=creator`,
{
headers: {
Authorization: editReq.token,
},
},
)).blob();
return placeContents;
};
const container = document.createElement("div");
container.classList.add("form-group", "mt-4");
container.innerHTML = `
`;
const form = document.querySelector('form[action="/create/place/update"]')!;
const button = container.getElementsByTagName("button")[0]!;
form.insertBefore(container, form.children[form.children.length - 1]);
button.addEventListener("click", async () => {
button.innerHTML = `
Loading...
`;
const placeContents = await retrievePlaceFile();
const blob = URL.createObjectURL(placeContents as any);
const link = document.createElement("a");
link.href = blob;
link.download = placeID + ".poly";
document.body.appendChild(link);
link.click();
link.remove();
button.textContent = "Download";
});
}