Add managed Craft addons with secure installation and document editing
This commit is contained in:
1 parent
1afa755d4f
commit
5cb1b463ea
31 files changed
+2274
-15
No files matched your search
@@ -0,0 +1,36 @@
|
||||
<template>
|
||||
<Action
|
||||
v-if="tool"
|
||||
icon="edit_note"
|
||||
:label="t('addons.openWith', { name: tool.name })"
|
||||
@action="router.push({ path: file!.url, query: { craft: tool!.id } })"
|
||||
/>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useAddonsStore } from "@/stores/addons";
|
||||
import Action from "@/components/header/Action.vue";
|
||||
const props = defineProps<{
|
||||
file?: { name: string; url: string; isDir: boolean } | null;
|
||||
}>();
|
||||
const store = useAddonsStore(),
|
||||
auth = useAuthStore(),
|
||||
router = useRouter(),
|
||||
{ t } = useI18n();
|
||||
const tool = computed(() =>
|
||||
!props.file?.isDir && auth.user?.perm.download && auth.user?.perm.modify
|
||||
? store.items.find(
|
||||
(item) =>
|
||||
item.enabled &&
|
||||
item.build &&
|
||||
props.file!.name.toLowerCase().endsWith(item.extension)
|
||||
)
|
||||
: undefined
|
||||
);
|
||||
onMounted(() => {
|
||||
store.refresh().catch(() => {});
|
||||
});
|
||||
</script>
|
||||
@@ -4,7 +4,7 @@
|
||||
</button>
|
||||
<div class="context-menu-separator" />
|
||||
<button
|
||||
v-for="template in fileTemplates"
|
||||
v-for="template in templates"
|
||||
:key="template.id"
|
||||
type="button"
|
||||
class="action"
|
||||
@@ -19,6 +19,23 @@
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useLayoutStore } from "@/stores/layout";
|
||||
import { fileTemplates } from "@/utils/file-templates";
|
||||
import { computed, onMounted } from "vue";
|
||||
import { useAddonsStore } from "@/stores/addons";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
const addons = useAddonsStore(),
|
||||
auth = useAuthStore();
|
||||
const templates = computed(() =>
|
||||
fileTemplates.filter(
|
||||
(template) =>
|
||||
!template.craft ||
|
||||
(addons.available(template.craft) &&
|
||||
auth.user?.perm.modify &&
|
||||
auth.user?.perm.download)
|
||||
)
|
||||
);
|
||||
onMounted(() => {
|
||||
addons.refresh().catch(() => {});
|
||||
});
|
||||
const { t } = useI18n(),
|
||||
layout = useLayoutStore();
|
||||
function open(prompt: string, template?: string) {
|
||||
|
||||
@@ -47,6 +47,7 @@ import { useLayoutStore } from "@/stores/layout";
|
||||
import CreateFilePath from "@/components/prompts/CreateFilePath.vue";
|
||||
|
||||
import { files as api } from "@/api";
|
||||
import { fetchURL, removePrefix } from "@/api/utils";
|
||||
import url from "@/utils/url";
|
||||
|
||||
const $showError = inject<IToastError>("$showError")!;
|
||||
@@ -88,13 +89,26 @@ const submit = async (event: Event) => {
|
||||
uri = uri.replace("//", "/");
|
||||
|
||||
try {
|
||||
await api.post(
|
||||
uri,
|
||||
new Blob([template.value.content], { type: "text/plain;charset=utf-8" })
|
||||
);
|
||||
if (template.value.craft) {
|
||||
await fetchURL(
|
||||
"/api/craft/" +
|
||||
template.value.craft +
|
||||
"/document?path=" +
|
||||
encodeURIComponent(decodeURIComponent(removePrefix(uri))),
|
||||
{ method: "POST" }
|
||||
);
|
||||
} else
|
||||
await api.post(
|
||||
uri,
|
||||
new Blob([template.value.content], { type: "text/plain;charset=utf-8" })
|
||||
);
|
||||
await router.push({
|
||||
path: uri,
|
||||
query: template.value.id === "other" ? {} : { edit: "true" },
|
||||
query: template.value.craft
|
||||
? { craft: template.value.craft }
|
||||
: template.value.id === "other"
|
||||
? {}
|
||||
: { edit: "true" },
|
||||
});
|
||||
layoutStore.closeHovers();
|
||||
} catch (e) {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
<template>
|
||||
<section class="card settings-section settings-wide addons-settings">
|
||||
<h2><AppIcon name="package" />{{ t("addons.title") }}</h2>
|
||||
<p class="field-hint">{{ t("addons.description") }}</p>
|
||||
<p v-if="error" class="document-error" role="alert">{{ error }}</p>
|
||||
<div v-for="addon in store.items" :key="addon.id" class="addon-row">
|
||||
<div>
|
||||
<strong>{{ addon.name }}</strong
|
||||
><small
|
||||
>{{ addon.version || t("addons.notInstalled") }} ·
|
||||
{{ addon.extension }}</small
|
||||
><small v-if="busy(addon)"
|
||||
>{{ t("addons.states." + addon.state)
|
||||
}}<template v-if="addon.total">
|
||||
·
|
||||
{{ Math.round((addon.downloaded / addon.total) * 100) }}%</template
|
||||
></small
|
||||
><small v-if="addon.error" role="alert" class="document-error">{{
|
||||
addon.error
|
||||
}}</small>
|
||||
</div>
|
||||
<label v-if="addon.build" class="addon-enabled"
|
||||
><input
|
||||
type="checkbox"
|
||||
:checked="addon.enabled"
|
||||
:disabled="changing === addon.id"
|
||||
@change="toggle(addon, ($event.target as HTMLInputElement).checked)"
|
||||
/>{{ t("addons.enabled") }}</label
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="button"
|
||||
:disabled="busy(addon) || changing === addon.id"
|
||||
@click="install(addon)"
|
||||
>
|
||||
<AppIcon :name="addon.build ? 'refresh' : 'download'" />{{
|
||||
addon.build ? t("addons.update") : t("addons.install")
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
<p class="field-hint">{{ t("addons.directory") }} <code>./addons</code></p>
|
||||
</section>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onBeforeUnmount, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { fetchURL } from "@/api/utils";
|
||||
import { useAddonsStore, type Addon } from "@/stores/addons";
|
||||
const store = useAddonsStore(),
|
||||
{ t } = useI18n(),
|
||||
error = ref(""),
|
||||
changing = ref("");
|
||||
let timer: ReturnType<typeof setTimeout> | undefined,
|
||||
disposed = false;
|
||||
const busy = (addon: Addon) =>
|
||||
["checking", "downloading", "verifying", "extracting"].includes(addon.state);
|
||||
async function refresh(force = false) {
|
||||
try {
|
||||
await store.refresh(force);
|
||||
} catch (failure) {
|
||||
error.value = String(failure);
|
||||
}
|
||||
if (!disposed && store.items.some(busy)) timer = setTimeout(refresh, 1500);
|
||||
}
|
||||
async function install(addon: Addon) {
|
||||
changing.value = addon.id;
|
||||
error.value = "";
|
||||
try {
|
||||
await fetchURL("/api/addons/" + addon.id + "/install", { method: "POST" });
|
||||
clearTimeout(timer);
|
||||
await refresh(true);
|
||||
} catch (failure) {
|
||||
error.value = String(failure);
|
||||
} finally {
|
||||
changing.value = "";
|
||||
}
|
||||
}
|
||||
async function toggle(addon: Addon, enabled: boolean) {
|
||||
changing.value = addon.id;
|
||||
error.value = "";
|
||||
try {
|
||||
await fetchURL("/api/addons/" + addon.id + "/enabled", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ enabled }),
|
||||
});
|
||||
await refresh();
|
||||
} catch (failure) {
|
||||
error.value = String(failure);
|
||||
} finally {
|
||||
changing.value = "";
|
||||
}
|
||||
}
|
||||
onMounted(refresh);
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true;
|
||||
clearTimeout(timer);
|
||||
});
|
||||
</script>
|
||||
@@ -389,3 +389,104 @@
|
||||
padding: 14px;
|
||||
}
|
||||
}
|
||||
.addon-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
padding: 16px 0;
|
||||
border-top: 1px solid var(--borderPrimary);
|
||||
}
|
||||
.addon-row > div {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.addon-row strong,
|
||||
.addon-row small {
|
||||
display: block;
|
||||
}
|
||||
.addon-row small {
|
||||
margin-top: 5px;
|
||||
font-size: 12px;
|
||||
color: var(--textSecondary);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.addon-enabled {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.addon-row .button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.craft-editor {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 9000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding-top: 64px;
|
||||
background: var(--background);
|
||||
}
|
||||
.craft-frame {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
border: 0;
|
||||
background: var(--surfacePrimary);
|
||||
}
|
||||
.craft-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
padding: 8px 16px;
|
||||
font-size: 12px;
|
||||
border-bottom: 1px solid var(--borderPrimary);
|
||||
}
|
||||
.craft-status strong {
|
||||
color: var(--blue);
|
||||
}
|
||||
.craft-status > span {
|
||||
flex: 1;
|
||||
}
|
||||
.craft-error {
|
||||
margin: 0;
|
||||
padding: 10px 16px;
|
||||
color: var(--red);
|
||||
font-size: 12px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.craft-save-as {
|
||||
display: flex;
|
||||
align-items: end;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
padding: 12px 16px;
|
||||
border-bottom: 1px solid var(--borderPrimary);
|
||||
}
|
||||
.craft-save-as label {
|
||||
flex: 1;
|
||||
min-width: 180px;
|
||||
}
|
||||
.craft-save-as input {
|
||||
width: 100%;
|
||||
margin-top: 6px;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.addon-row {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.addon-row > div {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
.addon-row .button {
|
||||
margin-inline-start: auto;
|
||||
}
|
||||
.craft-status {
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
@@ -410,6 +410,39 @@
|
||||
"json": "JSON file",
|
||||
"html": "HTML page",
|
||||
"xml": "XML file",
|
||||
"other": "Other file"
|
||||
"other": "Other file",
|
||||
"xlsx": "Excel workbook",
|
||||
"pdf": "PDF document"
|
||||
},
|
||||
"addons": {
|
||||
"title": "Addons",
|
||||
"description": "Editors run in your browser. Install official Artcraft releases with SHA-256 verification.",
|
||||
"notInstalled": "Not installed",
|
||||
"enabled": "Enabled",
|
||||
"install": "Download",
|
||||
"update": "Update",
|
||||
"directory": "Addon directory:",
|
||||
"openWith": "Open in {name}",
|
||||
"saving": "Saving to server…",
|
||||
"saved": "Saved to server",
|
||||
"loaded": "File opened",
|
||||
"unsaved": "Unsaved changes",
|
||||
"retrySave": "Retry save",
|
||||
"downloadCopy": "Download a copy",
|
||||
"saveAs": "Save as",
|
||||
"leaveUnsaved": "Changes have not been saved to the server. Leave the editor?",
|
||||
"conflict": "The server file changed or the name already exists. Save under another name or download a copy; the original was not overwritten.",
|
||||
"saveFailed": "Could not save to the server.",
|
||||
"invalidName": "Enter a valid .xlsx or .pdf filename without a path.",
|
||||
"tooLarge": "Documents are limited to 64 MiB.",
|
||||
"unavailable": "Editor is not installed, disabled, or editing is not permitted.",
|
||||
"startFailed": "Editor failed to start. Check WebGL2/WebGPU support and the installed addon version.",
|
||||
"states": {
|
||||
"checking": "Checking release",
|
||||
"downloading": "Downloading",
|
||||
"verifying": "Verifying SHA-256",
|
||||
"extracting": "Installing"
|
||||
},
|
||||
"sessionExpired": "Session expired. Sign in in another tab, then retry saving."
|
||||
}
|
||||
}
|
||||
@@ -407,6 +407,39 @@
|
||||
"json": "Файл JSON",
|
||||
"html": "Страница HTML",
|
||||
"xml": "Файл XML",
|
||||
"other": "Другой файл"
|
||||
"other": "Другой файл",
|
||||
"xlsx": "Таблица Excel",
|
||||
"pdf": "Документ PDF"
|
||||
},
|
||||
"addons": {
|
||||
"title": "Аддоны",
|
||||
"description": "Редакторы работают в браузере. Установка и обновление — из официальных релизов Artcraft с проверкой SHA-256.",
|
||||
"notInstalled": "Не установлен",
|
||||
"enabled": "Включён",
|
||||
"install": "Скачать",
|
||||
"update": "Обновить",
|
||||
"directory": "Каталог аддонов:",
|
||||
"openWith": "Открыть в {name}",
|
||||
"saving": "Сохранение на сервер…",
|
||||
"saved": "Сохранено на сервере",
|
||||
"loaded": "Файл открыт",
|
||||
"unsaved": "Есть несохранённые изменения",
|
||||
"retrySave": "Повторить сохранение",
|
||||
"downloadCopy": "Скачать копию",
|
||||
"saveAs": "Сохранить как",
|
||||
"leaveUnsaved": "Изменения ещё не сохранены на сервере. Покинуть редактор?",
|
||||
"conflict": "Файл изменился на сервере или имя уже занято. Сохраните под другим именем либо скачайте копию; исходный файл не перезаписан.",
|
||||
"saveFailed": "Не удалось сохранить на сервере.",
|
||||
"invalidName": "Укажите корректное имя с расширением .xlsx или .pdf, без пути.",
|
||||
"tooLarge": "Документы ограничены 64 МиБ.",
|
||||
"unavailable": "Редактор не установлен, отключён или нет разрешения на редактирование.",
|
||||
"startFailed": "Редактор не запустился. Проверьте поддержку WebGL2/WebGPU и установленную версию аддона.",
|
||||
"states": {
|
||||
"checking": "Проверка релиза",
|
||||
"downloading": "Скачивание",
|
||||
"verifying": "Проверка SHA-256",
|
||||
"extracting": "Установка"
|
||||
},
|
||||
"sessionExpired": "Сессия истекла. Войдите в соседней вкладке, затем повторите сохранение."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { fetchJSON } from "@/api/utils";
|
||||
export interface Addon {
|
||||
id: string;
|
||||
name: string;
|
||||
extension: string;
|
||||
version: string;
|
||||
build: string;
|
||||
enabled: boolean;
|
||||
state: string;
|
||||
error?: string;
|
||||
downloaded: number;
|
||||
total: number;
|
||||
}
|
||||
let request: Promise<void> | undefined;
|
||||
export const useAddonsStore = defineStore("addons", {
|
||||
state: () => ({ items: [] as Addon[], loaded: false }),
|
||||
actions: {
|
||||
async refresh(force = false): Promise<void> {
|
||||
if (request)
|
||||
return request.then(() => (force ? this.refresh() : undefined));
|
||||
request = fetchJSON<Addon[]>("/api/addons")
|
||||
.then((items) => {
|
||||
this.items = items;
|
||||
this.loaded = true;
|
||||
})
|
||||
.finally(() => {
|
||||
request = undefined;
|
||||
});
|
||||
return request;
|
||||
},
|
||||
available(id: string) {
|
||||
return this.items.some(
|
||||
(item) => item.id === id && item.enabled && !!item.build
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { craftMessage, safeCraftName } from "../craft";
|
||||
it("accepts messages only from the specific same-origin editor frame", () => {
|
||||
const frame = {} as Window,
|
||||
origin = "https://files.test";
|
||||
const message = {
|
||||
origin,
|
||||
source: frame,
|
||||
data: {
|
||||
type: "gridcraft:save",
|
||||
name: "book.xlsx",
|
||||
bytes: new ArrayBuffer(1),
|
||||
},
|
||||
} as MessageEvent;
|
||||
expect(craftMessage(message, frame, "gridcraft", origin)?.name).toBe(
|
||||
"book.xlsx"
|
||||
);
|
||||
expect(
|
||||
craftMessage(
|
||||
{ ...message, origin: "https://evil.test" } as MessageEvent,
|
||||
frame,
|
||||
"gridcraft",
|
||||
origin
|
||||
)
|
||||
).toBeNull();
|
||||
expect(
|
||||
craftMessage(
|
||||
{ ...message, source: {} } as MessageEvent,
|
||||
frame,
|
||||
"gridcraft",
|
||||
origin
|
||||
)
|
||||
).toBeNull();
|
||||
expect(craftMessage(message, frame, "pdfcraft", origin)).toBeNull();
|
||||
expect(craftMessage(message, null, "gridcraft", origin)).toBeNull();
|
||||
expect(
|
||||
craftMessage(
|
||||
{ ...message, data: null } as MessageEvent,
|
||||
frame,
|
||||
"gridcraft",
|
||||
origin
|
||||
)
|
||||
).toBeNull();
|
||||
});
|
||||
it("validates save-as filenames without allowing paths or another file type", () => {
|
||||
expect(safeCraftName("Report.XLSX", ".xlsx")).toBe("Report.XLSX");
|
||||
for (const name of [
|
||||
"../book.xlsx",
|
||||
"a/book.xlsx",
|
||||
"a\\book.xlsx",
|
||||
"C:book.xlsx",
|
||||
"book.xlsx\u0000",
|
||||
"book.html",
|
||||
"book.xlsx/",
|
||||
"a?.xlsx",
|
||||
])
|
||||
expect(safeCraftName(name, ".xlsx")).toBeNull();
|
||||
});
|
||||
@@ -20,7 +20,7 @@ it("provides valid starter content and a safe fallback for unknown template IDs"
|
||||
);
|
||||
expect(
|
||||
fileTemplates.some((template) =>
|
||||
[".docx", ".xlsx", ".pptx"].includes(template.extension)
|
||||
[".docx", ".pptx"].includes(template.extension)
|
||||
)
|
||||
).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
export function safeCraftName(name: unknown, extension: string): string | null {
|
||||
if (
|
||||
typeof name !== "string" ||
|
||||
!name.trim() ||
|
||||
name.length > 240 ||
|
||||
/[\\/\x00-\x1f\x7f]/.test(name) ||
|
||||
name === "." ||
|
||||
name === ".." ||
|
||||
/[<>:"|?*]/.test(name)
|
||||
)
|
||||
return null;
|
||||
const value = name.trim();
|
||||
return value.toLowerCase().endsWith(extension) ? value : null;
|
||||
}
|
||||
export function craftMessage(
|
||||
event: MessageEvent,
|
||||
frame: Window | null,
|
||||
id: string,
|
||||
origin: string
|
||||
) {
|
||||
if (
|
||||
event.origin !== origin ||
|
||||
event.source !== frame ||
|
||||
!frame ||
|
||||
!event.data ||
|
||||
typeof event.data.type !== "string" ||
|
||||
!event.data.type.startsWith(id + ":")
|
||||
)
|
||||
return null;
|
||||
return event.data as {
|
||||
type: string;
|
||||
name?: string;
|
||||
bytes?: ArrayBuffer;
|
||||
dirty?: boolean;
|
||||
saveAs?: boolean;
|
||||
error?: string;
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,25 @@
|
||||
export const fileTemplates = [
|
||||
interface FileTemplate {
|
||||
id: string;
|
||||
extension: string;
|
||||
icon: string;
|
||||
content: string;
|
||||
craft?: string;
|
||||
}
|
||||
export const fileTemplates: readonly FileTemplate[] = [
|
||||
{
|
||||
id: "xlsx",
|
||||
extension: ".xlsx",
|
||||
icon: "table",
|
||||
content: "",
|
||||
craft: "gridcraft",
|
||||
},
|
||||
{
|
||||
id: "pdf",
|
||||
extension: ".pdf",
|
||||
icon: "picture_as_pdf",
|
||||
content: "",
|
||||
craft: "pdfcraft",
|
||||
},
|
||||
{ id: "text", extension: ".txt", icon: "article", content: "" },
|
||||
{ id: "markdown", extension: ".md", icon: "edit_note", content: "" },
|
||||
{ id: "csv", extension: ".csv", icon: "table", content: "" },
|
||||
@@ -17,7 +38,7 @@ export const fileTemplates = [
|
||||
content: '<?xml version="1.0" encoding="UTF-8"?>\n<root />\n',
|
||||
},
|
||||
{ id: "other", extension: "", icon: "note_add", content: "" },
|
||||
] as const;
|
||||
];
|
||||
export function fileTemplate(id: unknown) {
|
||||
return (
|
||||
fileTemplates.find((template) => template.id === id) ||
|
||||
|
||||
@@ -7,7 +7,11 @@
|
||||
/>
|
||||
|
||||
<errors v-if="error" :errorCode="error.status" />
|
||||
<component v-else-if="currentView" :is="currentView"></component>
|
||||
<component
|
||||
v-else-if="currentView"
|
||||
:is="currentView"
|
||||
:key="route.query.craft ? route.fullPath : undefined"
|
||||
></component>
|
||||
<div v-else>
|
||||
<h2 class="message delayed">
|
||||
<div class="spinner">
|
||||
@@ -46,6 +50,9 @@ import { name } from "../utils/constants";
|
||||
|
||||
const Editor = defineAsyncComponent(() => import("@/views/files/Editor.vue"));
|
||||
const Preview = defineAsyncComponent(() => import("@/views/files/Preview.vue"));
|
||||
const CraftEditor = defineAsyncComponent(
|
||||
() => import("@/views/files/CraftEditor.vue")
|
||||
);
|
||||
|
||||
const layoutStore = useLayoutStore();
|
||||
const fileStore = useFileStore();
|
||||
@@ -61,6 +68,7 @@ let fetchDataController = new AbortController();
|
||||
const error = ref<StatusError | null>(null);
|
||||
|
||||
const currentView = computed(() => {
|
||||
if (route.query.craft && layoutStore.loading) return null;
|
||||
if (fileStore.req?.type === undefined) {
|
||||
return null;
|
||||
}
|
||||
@@ -68,6 +76,8 @@ const currentView = computed(() => {
|
||||
if (fileStore.req.isDir) {
|
||||
return FileListing;
|
||||
}
|
||||
if (["gridcraft", "pdfcraft"].includes(String(route.query.craft)))
|
||||
return CraftEditor;
|
||||
if (
|
||||
route.query.edit === "true" &&
|
||||
["text", "textImmutable"].includes(fileStore.req.type)
|
||||
@@ -100,6 +110,10 @@ watch(route, () => {
|
||||
fetchData();
|
||||
});
|
||||
watch(reload, (newValue) => {
|
||||
if (newValue && route.query.craft) {
|
||||
fileStore.reload = false;
|
||||
return;
|
||||
}
|
||||
newValue && fetchData();
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,409 @@
|
||||
<template>
|
||||
<div class="craft-editor">
|
||||
<header-bar
|
||||
><Action
|
||||
icon="close"
|
||||
:label="t('buttons.close')"
|
||||
@action="close"
|
||||
/><title>{{ currentName }}</title></header-bar
|
||||
>
|
||||
<div class="craft-status" role="status">
|
||||
<strong>{{ title }}</strong
|
||||
><span>{{
|
||||
saving
|
||||
? t("addons.saving")
|
||||
: pending
|
||||
? t("addons.unsaved")
|
||||
: frameDirty
|
||||
? t("addons.unsaved")
|
||||
: status
|
||||
}}</span
|
||||
><button
|
||||
v-if="pending && !saveAs && !saving"
|
||||
type="button"
|
||||
class="button button--flat"
|
||||
@click="persist"
|
||||
>
|
||||
{{ t("addons.retrySave") }}</button
|
||||
><button
|
||||
v-if="pending && !saveAs && !saving"
|
||||
type="button"
|
||||
class="button button--flat"
|
||||
@click="
|
||||
newName = pending.name;
|
||||
saveAs = true;
|
||||
"
|
||||
>
|
||||
{{ t("addons.saveAs") }}</button
|
||||
><button
|
||||
v-if="pending"
|
||||
type="button"
|
||||
class="button button--flat"
|
||||
@click="downloadCopy"
|
||||
>
|
||||
{{ t("addons.downloadCopy") }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="error" class="craft-error" role="alert">
|
||||
{{ error }}
|
||||
<a
|
||||
v-if="authExpired"
|
||||
:href="baseURL + '/auth/login'"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>{{ t("sidebar.login") }}</a
|
||||
>
|
||||
</p>
|
||||
<form v-if="saveAs" class="craft-save-as" @submit.prevent="confirmSaveAs">
|
||||
<label
|
||||
>{{ t("addons.saveAs")
|
||||
}}<input class="input" v-model.trim="newName" required /></label
|
||||
><button class="button" :disabled="saving">{{ t("buttons.save") }}</button
|
||||
><button
|
||||
type="button"
|
||||
class="button button--flat"
|
||||
@click="saveAs = false"
|
||||
>
|
||||
{{ t("buttons.cancel") }}
|
||||
</button>
|
||||
</form>
|
||||
<iframe
|
||||
v-if="frameURL"
|
||||
ref="frame"
|
||||
class="craft-frame"
|
||||
:src="frameURL"
|
||||
:title="title"
|
||||
allow="clipboard-read; clipboard-write; fullscreen"
|
||||
@load="connectActivity"
|
||||
sandbox="allow-scripts allow-same-origin allow-downloads allow-modals allow-popups"
|
||||
/>
|
||||
<p v-else-if="!error" role="status">{{ t("files.loading") }}</p>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, onMounted, onBeforeUnmount } from "vue";
|
||||
import {
|
||||
useRoute,
|
||||
useRouter,
|
||||
onBeforeRouteLeave,
|
||||
onBeforeRouteUpdate,
|
||||
} from "vue-router";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import HeaderBar from "@/components/header/HeaderBar.vue";
|
||||
import Action from "@/components/header/Action.vue";
|
||||
import { useFileStore } from "@/stores/file";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useAddonsStore } from "@/stores/addons";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
import { fetchURL, StatusError } from "@/api/utils";
|
||||
import { craftMessage, safeCraftName } from "@/utils/craft";
|
||||
const route = useRoute(),
|
||||
router = useRouter(),
|
||||
store = useAddonsStore(),
|
||||
files = useFileStore(),
|
||||
auth = useAuthStore(),
|
||||
{ t } = useI18n();
|
||||
// Bind the editor to the file opened at mount; later store navigation must not redirect a save.
|
||||
const file = files.req,
|
||||
id = String(route.query.craft || ""),
|
||||
sourcePath = file?.path || "";
|
||||
const currentPath = ref(sourcePath),
|
||||
currentName = ref(file?.name || "");
|
||||
const title = computed(
|
||||
() => store.items.find((item) => item.id === id)?.name || id
|
||||
);
|
||||
const frame = ref<HTMLIFrameElement>(),
|
||||
frameURL = ref(""),
|
||||
error = ref(""),
|
||||
status = ref(""),
|
||||
frameDirty = ref(false),
|
||||
saving = ref(false),
|
||||
saveAs = ref(false),
|
||||
newName = ref("");
|
||||
interface Save {
|
||||
bytes: ArrayBuffer;
|
||||
name: string;
|
||||
path: string;
|
||||
create: boolean;
|
||||
revision: number;
|
||||
}
|
||||
const pending = ref<Save>();
|
||||
const authExpired = ref(false);
|
||||
let activityDocument: Document | null = null,
|
||||
lastActivity = 0;
|
||||
const activityEvents = [
|
||||
"keydown",
|
||||
"pointerdown",
|
||||
"input",
|
||||
"wheel",
|
||||
"touchstart",
|
||||
];
|
||||
function disconnectActivity() {
|
||||
for (const name of activityEvents)
|
||||
activityDocument?.removeEventListener(name, activity, true);
|
||||
activityDocument = null;
|
||||
}
|
||||
function connectActivity() {
|
||||
disconnectActivity();
|
||||
activityDocument = frame.value?.contentDocument || null;
|
||||
for (const name of activityEvents)
|
||||
activityDocument?.addEventListener(name, activity, {
|
||||
capture: true,
|
||||
passive: true,
|
||||
});
|
||||
}
|
||||
function activity(event: Event) {
|
||||
if (
|
||||
!event.isTrusted ||
|
||||
document.visibilityState !== "visible" ||
|
||||
Date.now() - lastActivity < 60000
|
||||
)
|
||||
return;
|
||||
lastActivity = Date.now();
|
||||
fetchURL("/api/session", { signal: controller.signal }, false)
|
||||
.then((response) => {
|
||||
authExpired.value = false;
|
||||
response.body?.cancel();
|
||||
})
|
||||
.catch((failure) => {
|
||||
if (failure instanceof StatusError && failure.status === 401) {
|
||||
authExpired.value = true;
|
||||
error.value = t("addons.sessionExpired");
|
||||
}
|
||||
});
|
||||
}
|
||||
let tag = "",
|
||||
revision = 0,
|
||||
disposed = false,
|
||||
opened = false,
|
||||
startup: ReturnType<typeof setTimeout> | undefined;
|
||||
const controller = new AbortController();
|
||||
let original: ArrayBuffer | undefined;
|
||||
function endpoint(path: string) {
|
||||
return "/api/craft/" + id + "/document?path=" + encodeURIComponent(path);
|
||||
}
|
||||
const unsaved = computed(
|
||||
() => !!pending.value || saving.value || frameDirty.value
|
||||
);
|
||||
function mayLeave() {
|
||||
return !unsaved.value || window.confirm(t("addons.leaveUnsaved"));
|
||||
}
|
||||
onBeforeRouteLeave(mayLeave);
|
||||
onBeforeRouteUpdate(mayLeave);
|
||||
function beforeUnload(event: BeforeUnloadEvent) {
|
||||
if (unsaved.value) event.preventDefault();
|
||||
}
|
||||
function close() {
|
||||
router.push({
|
||||
path: file?.url.slice(0, file.url.lastIndexOf("/") + 1) || "/files/",
|
||||
});
|
||||
}
|
||||
async function persist() {
|
||||
const payload = pending.value;
|
||||
if (!payload || saving.value) return;
|
||||
saving.value = true;
|
||||
error.value = "";
|
||||
let success = false;
|
||||
try {
|
||||
const response = await fetchURL(
|
||||
endpoint(payload.path),
|
||||
{
|
||||
method: "PUT",
|
||||
headers: payload.create
|
||||
? { "If-None-Match": "*" }
|
||||
: { "If-Match": tag },
|
||||
body: payload.bytes,
|
||||
signal: controller.signal,
|
||||
},
|
||||
false
|
||||
);
|
||||
if (disposed) return;
|
||||
success = true;
|
||||
authExpired.value = false;
|
||||
if (
|
||||
payload.path.toLowerCase().endsWith(id === "gridcraft" ? ".xlsx" : ".pdf")
|
||||
) {
|
||||
tag = response.headers.get("ETag") || "";
|
||||
currentPath.value = payload.path;
|
||||
currentName.value = payload.name;
|
||||
}
|
||||
if (pending.value === payload) {
|
||||
pending.value = undefined;
|
||||
status.value = t("addons.saved");
|
||||
if (revision === payload.revision) frameDirty.value = false;
|
||||
}
|
||||
} catch (failure) {
|
||||
if (!disposed) {
|
||||
if (failure instanceof StatusError && failure.status === 401)
|
||||
authExpired.value = true;
|
||||
error.value =
|
||||
failure instanceof StatusError &&
|
||||
[409, 412].includes(failure.status || 0)
|
||||
? t("addons.conflict")
|
||||
: t("addons.saveFailed") + " " + String(failure);
|
||||
}
|
||||
} finally {
|
||||
saving.value = false;
|
||||
if (success && pending.value && pending.value !== payload && !saveAs.value)
|
||||
queueMicrotask(persist);
|
||||
}
|
||||
}
|
||||
function confirmSaveAs() {
|
||||
if (!pending.value) return;
|
||||
const ext = pending.value.name.toLowerCase().endsWith(".pdf")
|
||||
? ".pdf"
|
||||
: id === "gridcraft"
|
||||
? ".xlsx"
|
||||
: ".pdf";
|
||||
const name = safeCraftName(newName.value, ext);
|
||||
if (!name) {
|
||||
error.value = t("addons.invalidName");
|
||||
return;
|
||||
}
|
||||
pending.value = {
|
||||
...pending.value,
|
||||
name,
|
||||
path:
|
||||
currentPath.value.slice(0, currentPath.value.lastIndexOf("/") + 1) + name,
|
||||
create: true,
|
||||
};
|
||||
saveAs.value = false;
|
||||
persist();
|
||||
}
|
||||
function downloadCopy() {
|
||||
if (!pending.value) return;
|
||||
const url = URL.createObjectURL(new Blob([pending.value.bytes]));
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = pending.value.name;
|
||||
link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
function receive(event: MessageEvent) {
|
||||
const message = craftMessage(
|
||||
event,
|
||||
frame.value?.contentWindow || null,
|
||||
id,
|
||||
window.location.origin
|
||||
);
|
||||
if (!message) return;
|
||||
if (message.type === id + ":ready") {
|
||||
if (opened || !original) return;
|
||||
opened = true;
|
||||
clearTimeout(startup);
|
||||
frame.value!.contentWindow!.postMessage(
|
||||
{ type: id + ":open", name: file!.name, bytes: original },
|
||||
window.location.origin,
|
||||
[original]
|
||||
);
|
||||
original = undefined;
|
||||
status.value = t("addons.loaded");
|
||||
} else if (message.type === id + ":failed") {
|
||||
clearTimeout(startup);
|
||||
error.value = String(message.error || t("addons.startFailed"));
|
||||
} else if (message.type === id + ":dirty") {
|
||||
frameDirty.value = message.dirty === true;
|
||||
if (frameDirty.value) revision++;
|
||||
} else if (message.type === id + ":save") {
|
||||
if (
|
||||
!(message.bytes instanceof ArrayBuffer) ||
|
||||
message.bytes.byteLength > 64 * 1024 * 1024
|
||||
) {
|
||||
error.value = t("addons.tooLarge");
|
||||
return;
|
||||
}
|
||||
const extension = message.name?.toLowerCase().endsWith(".pdf")
|
||||
? ".pdf"
|
||||
: id === "gridcraft"
|
||||
? ".xlsx"
|
||||
: ".pdf";
|
||||
const name = safeCraftName(message.name, extension);
|
||||
if (!name) {
|
||||
error.value = t("addons.invalidName");
|
||||
return;
|
||||
}
|
||||
const create = !!message.saveAs || name !== currentName.value;
|
||||
pending.value = {
|
||||
bytes: message.bytes,
|
||||
name,
|
||||
path: currentPath.value,
|
||||
create,
|
||||
revision,
|
||||
};
|
||||
if (create) {
|
||||
newName.value = name;
|
||||
saveAs.value = true;
|
||||
} else persist();
|
||||
}
|
||||
}
|
||||
onMounted(async () => {
|
||||
window.addEventListener("message", receive);
|
||||
window.addEventListener("beforeunload", beforeUnload);
|
||||
try {
|
||||
await store.refresh();
|
||||
const addon = store.items.find(
|
||||
(item) => item.id === id && item.enabled && item.build
|
||||
);
|
||||
if (
|
||||
!addon ||
|
||||
!auth.user?.perm.modify ||
|
||||
!auth.user?.perm.download ||
|
||||
!sourcePath.toLowerCase().endsWith(addon.extension)
|
||||
)
|
||||
throw new Error(t("addons.unavailable"));
|
||||
// Bound streamed data even when Content-Length is missing.
|
||||
const response = await fetchURL(endpoint(sourcePath), {
|
||||
signal: controller.signal,
|
||||
});
|
||||
tag = response.headers.get("ETag") || "";
|
||||
if (!tag) throw new Error("Missing document version");
|
||||
if (Number(response.headers.get("Content-Length")) > 64 * 1024 * 1024) {
|
||||
await response.body?.cancel();
|
||||
throw new Error(t("addons.tooLarge"));
|
||||
}
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) throw new Error("Empty document");
|
||||
let length = 0;
|
||||
const chunks: Uint8Array[] = [];
|
||||
while (true) {
|
||||
const part = await reader.read();
|
||||
if (part.done) break;
|
||||
length += part.value.length;
|
||||
if (length > 64 * 1024 * 1024) {
|
||||
await reader.cancel();
|
||||
throw new Error(t("addons.tooLarge"));
|
||||
}
|
||||
chunks.push(part.value);
|
||||
}
|
||||
const data = new Uint8Array(length);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
data.set(chunk, offset);
|
||||
offset += chunk.length;
|
||||
}
|
||||
original = data.buffer;
|
||||
if (disposed) return;
|
||||
frameURL.value =
|
||||
baseURL +
|
||||
"/addons/" +
|
||||
id +
|
||||
"/" +
|
||||
addon.build +
|
||||
"/index.html?host=parent&author=" +
|
||||
encodeURIComponent(auth.user.profileName || auth.user.username);
|
||||
startup = setTimeout(() => {
|
||||
error.value = t("addons.startFailed");
|
||||
}, 45000);
|
||||
} catch (failure) {
|
||||
if (!disposed) error.value = String(failure);
|
||||
}
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
disconnectActivity();
|
||||
disposed = true;
|
||||
controller.abort();
|
||||
clearTimeout(startup);
|
||||
window.removeEventListener("message", receive);
|
||||
window.removeEventListener("beforeunload", beforeUnload);
|
||||
});
|
||||
</script>
|
||||
@@ -176,6 +176,13 @@
|
||||
:pos="contextMenuPos"
|
||||
@hide="hideContextMenu"
|
||||
>
|
||||
<CraftAction
|
||||
:file="
|
||||
fileStore.selectedCount === 1
|
||||
? fileStore.req?.items[fileStore.selected[0]]
|
||||
: null
|
||||
"
|
||||
/>
|
||||
<action
|
||||
v-if="headerButtons.share"
|
||||
icon="share"
|
||||
@@ -284,6 +291,7 @@ import Search from "@/components/Search.vue";
|
||||
import Item from "@/components/files/ListingItem.vue";
|
||||
import CreateMenu from "@/components/files/CreateMenu.vue";
|
||||
import ContextMenu from "@/components/ContextMenu.vue";
|
||||
import CraftAction from "@/components/files/CraftAction.vue";
|
||||
import {
|
||||
computed,
|
||||
inject,
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
/>
|
||||
|
||||
<template #actions>
|
||||
<CraftAction :file="fileStore.req" />
|
||||
<action
|
||||
:disabled="layoutStore.loading"
|
||||
v-if="authStore.user?.perm.rename"
|
||||
@@ -179,6 +180,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import CraftAction from "@/components/files/CraftAction.vue";
|
||||
import { useStorage } from "@vueuse/core";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useFileStore } from "@/stores/file";
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
><small>{{ t("explorer.usersHint") }}</small></span
|
||||
><AppIcon name="chevron_right" />
|
||||
</button>
|
||||
<Addons />
|
||||
<section class="card settings-section">
|
||||
<h2><AppIcon name="archive" />{{ t("settings.downloadsTitle") }}</h2>
|
||||
<label class="settings-field"
|
||||
@@ -131,6 +132,7 @@
|
||||
<script setup lang="ts">
|
||||
import { useRoute } from "vue-router";
|
||||
import { settings as api } from "@/api";
|
||||
import Addons from "@/components/settings/Addons.vue";
|
||||
import { StatusError } from "@/api/utils";
|
||||
import Rules from "@/components/settings/Rules.vue";
|
||||
import Themes from "@/components/settings/Themes.vue";
|
||||
|
||||
Reference in new issue
Block a user