feat: improve ArtCraft integration and configurable file opening
No files matched your search
@@ -39,7 +39,7 @@
|
||||
"pinia": "^3.0.4",
|
||||
"pretty-bytes": "^7.2.0",
|
||||
"tus-js-client": "^4.3.1",
|
||||
"utif": "^3.2.0",
|
||||
"utif": "^3.1.0",
|
||||
"video.js": "^8.24.2",
|
||||
"videojs-hotkeys": "^0.2.30",
|
||||
"videojs-mobile-ui": "^1.2.7",
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
Original application icons downloaded from https://getartcraft.com/images/apps/<app>/icon.webp on 2026-11-01.
|
||||
|
||||
Applications and original artwork: ArtCraft / storytold. These icons identify the corresponding third-party applications and do not imply affiliation.
|
||||
|
||||
Official application pages: https://getartcraft.com/apps
|
||||
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 5.4 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 7.8 KiB |
@@ -0,0 +1,143 @@
|
||||
const fs = require("node:fs"),
|
||||
path = require("node:path"),
|
||||
assert = require("node:assert/strict");
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE);
|
||||
(async () => {
|
||||
const base = process.env.FILEBROWSER_QA_URL,
|
||||
out = process.env.FILEBROWSER_QA_OUTPUT;
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.BROWSER_EXECUTABLE,
|
||||
headless: true,
|
||||
args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"],
|
||||
});
|
||||
try {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: 1440, height: 1000 },
|
||||
}),
|
||||
page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on("pageerror", (error) => errors.push(String(error)));
|
||||
await page.goto(base + "/files/");
|
||||
await page.locator(".item").first().waitFor();
|
||||
await page.locator(".workspace-actions-button").click();
|
||||
const root = page.locator(".context-menu:not(.context-submenu)");
|
||||
assert.equal(
|
||||
await root
|
||||
.getByRole("menuitem", { name: "Создать папку", exact: true })
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
await root
|
||||
.getByRole("menuitem", { name: "Создать файл", exact: true })
|
||||
.click();
|
||||
const fileMenu = page.locator(".context-submenu").first();
|
||||
assert.equal(
|
||||
await fileMenu
|
||||
.getByRole("button", { name: "Создать папку", exact: true })
|
||||
.count(),
|
||||
0
|
||||
);
|
||||
await fileMenu
|
||||
.getByRole("menuitem", { name: "ArtCraft", exact: true })
|
||||
.click();
|
||||
const craftMenu = page.locator(".context-submenu").last();
|
||||
await craftMenu
|
||||
.getByRole("menuitem", { name: "WordCraft (.docx)", exact: true })
|
||||
.waitFor();
|
||||
assert.equal(await craftMenu.locator(".create-app-icon").count(), 4);
|
||||
await page.screenshot({ path: path.join(out, "create-file-artcraft.png") });
|
||||
await craftMenu
|
||||
.getByRole("menuitem", { name: "WordCraft (.docx)", exact: true })
|
||||
.click();
|
||||
await page.locator("#focus-prompt").waitFor();
|
||||
assert.equal(await page.locator(".context-menu").count(), 0);
|
||||
await page
|
||||
.getByRole("button", { name: "Отмена", exact: true })
|
||||
.last()
|
||||
.click();
|
||||
await page
|
||||
.locator('.item[aria-label="document.docx"]')
|
||||
.click({ button: "right" });
|
||||
await root.locator(".action-app-icon").first().waitFor();
|
||||
assert(
|
||||
await root
|
||||
.locator(".action-app-icon")
|
||||
.first()
|
||||
.evaluate((icon) => icon.complete && icon.naturalWidth > 0)
|
||||
);
|
||||
await page.keyboard.press("Escape");
|
||||
await page.goto(base + "/settings/profile");
|
||||
await page
|
||||
.getByRole("button", { name: "Настройки автооткрытия", exact: true })
|
||||
.click();
|
||||
const dialog = page.getByRole("dialog", { name: "Настройки автооткрытия" });
|
||||
assert((await dialog.locator(".auto-open-row").count()) > 200);
|
||||
await dialog.getByRole("searchbox").fill(".jpg");
|
||||
await dialog
|
||||
.locator('select[aria-label=".jpg"]')
|
||||
.selectOption("photocraft");
|
||||
await dialog.getByRole("searchbox").fill(".wav");
|
||||
await dialog.locator('select[aria-label=".wav"]').selectOption("download");
|
||||
await page.screenshot({ path: path.join(out, "auto-open-search.png") });
|
||||
await dialog.locator("footer button").click();
|
||||
const saved = page.waitForResponse(
|
||||
(r) => r.request().method() === "PUT" && r.url().includes("/api/users/")
|
||||
);
|
||||
await page.locator(".settings-save button").click();
|
||||
assert.equal((await saved).status(), 200);
|
||||
let user = await (await page.request.get(base + "/api/session")).json();
|
||||
assert.equal(user.autoOpen[".jpg"], "photocraft");
|
||||
assert.equal(user.autoOpen[".wav"], "download");
|
||||
await page.reload();
|
||||
await page
|
||||
.getByRole("button", { name: "Настройки автооткрытия", exact: true })
|
||||
.click();
|
||||
await dialog.getByRole("searchbox").fill(".jpg");
|
||||
assert.equal(
|
||||
await dialog.locator('select[aria-label=".jpg"]').inputValue(),
|
||||
"photocraft"
|
||||
);
|
||||
await page.keyboard.press("Escape");
|
||||
await page.goto(base + "/files/");
|
||||
const popup = context.waitForEvent("page");
|
||||
await page.locator('.item[aria-label="photo.jpg"]').dblclick();
|
||||
const editor = await popup;
|
||||
await editor.waitForURL("**/editor/photocraft?**");
|
||||
await editor.close();
|
||||
const download = page.waitForEvent("download");
|
||||
await page.locator('.item[aria-label="tone.wav"]').dblclick();
|
||||
assert.equal((await download).suggestedFilename(), "tone.wav");
|
||||
await page.goto(base + "/settings/global");
|
||||
const status = await (
|
||||
await page.request.get(base + "/api/media/status")
|
||||
).json();
|
||||
assert.equal(status.available, true);
|
||||
await page.getByRole("heading", { name: "FFmpeg", exact: true }).waitFor();
|
||||
await page.getByText("Доступен", { exact: true }).waitFor();
|
||||
await page.screenshot({ path: path.join(out, "ffmpeg-status.png") });
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.goto(base + "/files/");
|
||||
await page.locator(".workspace-actions-button").click();
|
||||
await root
|
||||
.getByRole("menuitem", { name: "Создать файл", exact: true })
|
||||
.click();
|
||||
await page
|
||||
.locator(".context-submenu")
|
||||
.first()
|
||||
.getByRole("menuitem", { name: "ArtCraft", exact: true })
|
||||
.click();
|
||||
await craftMenu
|
||||
.getByRole("menuitem", { name: "WordCraft (.docx)", exact: true })
|
||||
.waitFor();
|
||||
const bounds = await craftMenu.boundingBox();
|
||||
assert(bounds.x >= 0 && bounds.x + bounds.width <= 390);
|
||||
await page.screenshot({ path: path.join(out, "menus-mobile.png") });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log(
|
||||
"ArtCraft menus/icons, folder action, persisted auto-open preferences, editor/download routing, FFmpeg status and mobile submenu passed"
|
||||
);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
})();
|
||||
@@ -63,8 +63,8 @@
|
||||
<button
|
||||
v-if="file.isFiles && file.req?.isDir && auth.user.perm.create"
|
||||
@click="layout.showHover('create')"
|
||||
:title="t('buttons.create')"
|
||||
:aria-label="t('buttons.create')"
|
||||
:title="t('explorer.createFile')"
|
||||
:aria-label="t('explorer.createFile')"
|
||||
>
|
||||
<AppIcon name="add" />
|
||||
</button>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<Action
|
||||
v-for="tool in tools"
|
||||
:key="tool.id"
|
||||
icon="edit_note"
|
||||
:icon-src="baseURL + '/static/img/artcraft/' + tool.id + '.webp'"
|
||||
:label="t('addons.openWith', { name: tool.name })"
|
||||
@action="openCraftTab(router, tool.id, file!.url)"
|
||||
/>
|
||||
@@ -15,6 +15,7 @@ import { useI18n } from "vue-i18n";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useAddonsStore } from "@/stores/addons";
|
||||
import Action from "@/components/header/Action.vue";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
const props = defineProps<{
|
||||
file?: { name: string; url: string; isDir: boolean } | null;
|
||||
}>();
|
||||
|
||||
@@ -8,7 +8,9 @@
|
||||
@click.stop="expanded = !expanded"
|
||||
@keydown.right.stop.prevent="expand"
|
||||
>
|
||||
<AppIcon name="add" /><span>{{ t("buttons.create") }}</span
|
||||
<AppIcon :name="craftOnly ? 'package' : 'note_add'" /><span>{{
|
||||
craftOnly ? "ArtCraft" : t("explorer.createFile")
|
||||
}}</span
|
||||
><AppIcon name="chevron_right" />
|
||||
</button>
|
||||
<Teleport to="body">
|
||||
@@ -18,7 +20,7 @@
|
||||
class="context-menu context-submenu"
|
||||
role="menu"
|
||||
:data-context-owner="owner?.id"
|
||||
:aria-label="t('buttons.create')"
|
||||
:aria-label="craftOnly ? 'ArtCraft' : t('explorer.createFile')"
|
||||
:style="{ left: left + 'px', top: top + 'px' }"
|
||||
@click.stop="choose"
|
||||
@contextmenu.prevent.stop
|
||||
@@ -30,9 +32,11 @@
|
||||
class="action"
|
||||
@click.stop="collapse"
|
||||
>
|
||||
<AppIcon name="arrow_back" /><span>{{ t("buttons.create") }}</span>
|
||||
<AppIcon name="arrow_back" /><span>{{
|
||||
craftOnly ? "ArtCraft" : t("explorer.createFile")
|
||||
}}</span>
|
||||
</button>
|
||||
<CreateOptions />
|
||||
<CreateOptions :craft-only="craftOnly" />
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -41,6 +45,7 @@ import { inject, nextTick, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { contextMenuKey, submenuPosition } from "@/utils/context-menu";
|
||||
import CreateOptions from "./CreateOptions.vue";
|
||||
defineProps<{ craftOnly?: boolean }>();
|
||||
const { t } = useI18n(),
|
||||
owner = inject(contextMenuKey);
|
||||
const expanded = ref(false),
|
||||
@@ -51,10 +56,9 @@ const submenu = ref<HTMLElement>(),
|
||||
trigger = ref<HTMLElement>();
|
||||
function position() {
|
||||
if (!submenu.value || !trigger.value) return;
|
||||
const parent = trigger.value
|
||||
.closest(".context-menu")
|
||||
?.getBoundingClientRect();
|
||||
if (!parent) return;
|
||||
const parent =
|
||||
trigger.value.closest(".context-menu")?.getBoundingClientRect() ||
|
||||
trigger.value.getBoundingClientRect();
|
||||
const row = trigger.value.getBoundingClientRect(),
|
||||
panel = submenu.value.getBoundingClientRect();
|
||||
compact.value = window.innerWidth < parent.width + panel.width + 24;
|
||||
@@ -80,6 +84,11 @@ function collapse() {
|
||||
trigger.value?.focus({ preventScroll: true });
|
||||
}
|
||||
function choose(event: MouseEvent) {
|
||||
if (
|
||||
event.target instanceof Element &&
|
||||
event.target.closest('button[aria-haspopup="menu"]')
|
||||
)
|
||||
return;
|
||||
if (!(event.target instanceof Element) || !event.target.closest("button"))
|
||||
return;
|
||||
expanded.value = false;
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
<template>
|
||||
<button type="button" class="action" @click="open('newDir')">
|
||||
<AppIcon name="folder" /><span>{{ t("sidebar.newFolder") }}</span>
|
||||
</button>
|
||||
<div class="context-menu-separator" />
|
||||
<button
|
||||
v-for="template in templates"
|
||||
:key="template.id"
|
||||
@@ -10,10 +6,22 @@
|
||||
class="action"
|
||||
@click="open('newFile', template.id)"
|
||||
>
|
||||
<AppIcon :name="template.icon" /><span>{{
|
||||
t("createTypes." + template.id)
|
||||
<img
|
||||
v-if="template.craft"
|
||||
class="create-app-icon"
|
||||
:src="baseURL + '/static/img/artcraft/' + template.craft + '.webp'"
|
||||
alt=""
|
||||
/><AppIcon v-else :name="template.icon" /><span>{{
|
||||
template.craft
|
||||
? (addons.items.find((item) => item.id === template.craft)?.name ||
|
||||
template.craft) +
|
||||
" (" +
|
||||
template.extension +
|
||||
")"
|
||||
: t("createTypes." + template.id)
|
||||
}}</span>
|
||||
</button>
|
||||
<CreateMenu v-if="!craftOnly && hasCraftTemplates" craft-only />
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from "vue-i18n";
|
||||
@@ -22,9 +30,12 @@ import { fileTemplates } from "@/utils/file-templates";
|
||||
import { computed, onMounted } from "vue";
|
||||
import { useAddonsStore } from "@/stores/addons";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import CreateMenu from "./CreateMenu.vue";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
const props = defineProps<{ craftOnly?: boolean }>();
|
||||
const addons = useAddonsStore(),
|
||||
auth = useAuthStore();
|
||||
const templates = computed(() =>
|
||||
const availableTemplates = computed(() =>
|
||||
fileTemplates.filter(
|
||||
(template) =>
|
||||
!template.craft ||
|
||||
@@ -33,6 +44,14 @@ const templates = computed(() =>
|
||||
auth.user?.perm.download)
|
||||
)
|
||||
);
|
||||
const templates = computed(() =>
|
||||
availableTemplates.value.filter(
|
||||
(template) => !!template.craft === !!props.craftOnly
|
||||
)
|
||||
);
|
||||
const hasCraftTemplates = computed(() =>
|
||||
availableTemplates.value.some((template) => template.craft)
|
||||
);
|
||||
onMounted(() => {
|
||||
addons.refresh().catch(() => {});
|
||||
});
|
||||
@@ -43,3 +62,11 @@ function open(prompt: string, template?: string) {
|
||||
layout.showHover({ prompt, props: { template } });
|
||||
}
|
||||
</script>
|
||||
<style scoped>
|
||||
.create-app-icon {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
object-fit: contain;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,111 @@
|
||||
<template>
|
||||
<div class="directory-node">
|
||||
<div
|
||||
class="directory-entry"
|
||||
:class="{
|
||||
active: selectedPath.replace(/\/$/, '') === path.replace(/\/$/, ''),
|
||||
}"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="tree-expand"
|
||||
:aria-expanded="expanded"
|
||||
:aria-label="label"
|
||||
@click="expand"
|
||||
>
|
||||
{{ expanded ? "▾" : "▸" }}
|
||||
</button>
|
||||
<button type="button" class="tree-folder" @click="$emit('select', path)">
|
||||
<AppIcon name="folder" />{{ label }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="error" class="document-error" role="alert">{{ error }}</p>
|
||||
<div v-if="expanded" class="directory-children">
|
||||
<DirectoryTree
|
||||
v-for="folder in folders"
|
||||
:key="folder.path"
|
||||
:path="folder.path"
|
||||
:label="folder.name"
|
||||
:selected-path="selectedPath"
|
||||
@select="$emit('select', $event)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onBeforeUnmount, ref } from "vue";
|
||||
import * as api from "@/api/files";
|
||||
import { encodePath } from "@/utils/url";
|
||||
const props = defineProps<{
|
||||
path: string;
|
||||
label: string;
|
||||
selectedPath: string;
|
||||
}>();
|
||||
defineEmits<{ select: [path: string] }>();
|
||||
const expanded = ref(false),
|
||||
folders = ref<ResourceItem[]>([]),
|
||||
error = ref("");
|
||||
let loaded = false;
|
||||
const controller = new AbortController();
|
||||
async function expand() {
|
||||
expanded.value = !expanded.value;
|
||||
if (!expanded.value || loaded) return;
|
||||
try {
|
||||
const data = await api.fetch(
|
||||
"/files" + encodePath(props.path),
|
||||
controller.signal
|
||||
);
|
||||
folders.value = data.items
|
||||
.filter((item) => item.isDir)
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
loaded = true;
|
||||
} catch (failure) {
|
||||
if (!controller.signal.aborted) error.value = String(failure);
|
||||
}
|
||||
}
|
||||
onMounted(() => {
|
||||
if (
|
||||
props.path === "/" ||
|
||||
props.selectedPath.startsWith(props.path.replace(/\/$/, "") + "/")
|
||||
)
|
||||
expand();
|
||||
});
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
<style scoped>
|
||||
.directory-entry {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.directory-entry:hover,
|
||||
.directory-entry.active {
|
||||
background: var(--surfaceSecondary);
|
||||
}
|
||||
.directory-entry button {
|
||||
color: inherit;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
padding: 8px 3px;
|
||||
}
|
||||
.tree-expand {
|
||||
width: 24px;
|
||||
flex: none;
|
||||
}
|
||||
.tree-folder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
text-align: left;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.tree-folder .app-icon {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
flex: none;
|
||||
}
|
||||
.directory-children {
|
||||
padding-left: 14px;
|
||||
}
|
||||
</style>
|
||||
@@ -51,7 +51,11 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useAddonsStore } from "@/stores/addons";
|
||||
import { defaultCraftTool, openCraftTab } from "@/utils/craft";
|
||||
import {
|
||||
defaultCraftTool,
|
||||
fileOpenPreference,
|
||||
openCraftTab,
|
||||
} from "@/utils/craft";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useFileStore } from "@/stores/file";
|
||||
import { useLayoutStore } from "@/stores/layout";
|
||||
@@ -383,12 +387,26 @@ const click = (event: Event | KeyboardEvent) => {
|
||||
};
|
||||
|
||||
const open = () => {
|
||||
if (
|
||||
!props.isDir &&
|
||||
!props.readOnly &&
|
||||
authStore.user?.perm.download &&
|
||||
fileOpenPreference(authStore.user.autoOpen, props.name) === "download"
|
||||
) {
|
||||
api.download(null, props.url);
|
||||
return;
|
||||
}
|
||||
const tool =
|
||||
!props.readOnly &&
|
||||
!props.isDir &&
|
||||
authStore.user?.perm.modify &&
|
||||
authStore.user?.perm.download
|
||||
? defaultCraftTool(addons.items, props.name, props.type)
|
||||
? defaultCraftTool(
|
||||
addons.items,
|
||||
props.name,
|
||||
props.type,
|
||||
authStore.user?.autoOpen
|
||||
)
|
||||
: undefined;
|
||||
if (tool) {
|
||||
openCraftTab(router, tool.id, props.url);
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
<template>
|
||||
<div class="media-player" @keydown.stop>
|
||||
<audio
|
||||
v-if="audio"
|
||||
ref="audioElement"
|
||||
:key="activeSource"
|
||||
:src="activeSource"
|
||||
controls
|
||||
preload="metadata"
|
||||
:autoplay="autoplay"
|
||||
@play="$emit('play')"
|
||||
@error="failed = true"
|
||||
/>
|
||||
<VideoPlayer
|
||||
v-else
|
||||
:key="activeSource"
|
||||
:source="activeSource"
|
||||
:subtitles="subtitles"
|
||||
:options="{ autoplay }"
|
||||
@error="failed = true"
|
||||
/>
|
||||
<div v-if="failed || converted" class="media-feedback" role="status">
|
||||
<p>
|
||||
{{ t(converted ? "files.mediaConverted" : "files.mediaCodecError") }}
|
||||
</p>
|
||||
<button
|
||||
v-if="failed && fallback && !converted"
|
||||
class="button"
|
||||
@click="convert"
|
||||
>
|
||||
{{ t("files.mediaConvert") }}
|
||||
</button>
|
||||
<p v-if="failed && converted">{{ t("files.mediaUnavailable") }}</p>
|
||||
<a :href="source" download>{{ t("buttons.download") }}</a>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch, defineAsyncComponent } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
const VideoPlayer = defineAsyncComponent(() => import("./VideoPlayer.vue"));
|
||||
const props = defineProps<{
|
||||
source: string;
|
||||
audio?: boolean;
|
||||
autoplay?: boolean;
|
||||
subtitles?: string[];
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
defineEmits<{ play: [] }>();
|
||||
const audioElement = ref<HTMLAudioElement>();
|
||||
defineExpose({
|
||||
get paused() {
|
||||
return audioElement.value?.paused;
|
||||
},
|
||||
get ended() {
|
||||
return audioElement.value?.ended;
|
||||
},
|
||||
});
|
||||
const failed = ref(false),
|
||||
converted = ref(false);
|
||||
const fallback = computed(() => {
|
||||
const url = new URL(props.source, location.origin);
|
||||
const prefix = baseURL + "/api/raw";
|
||||
if (url.origin !== location.origin || !url.pathname.startsWith(prefix + "/"))
|
||||
return "";
|
||||
return (
|
||||
baseURL +
|
||||
"/api/media/play?path=" +
|
||||
encodeURIComponent(decodeURIComponent(url.pathname.slice(prefix.length))) +
|
||||
(props.audio ? "&audio=true" : "")
|
||||
);
|
||||
});
|
||||
const activeSource = computed(() =>
|
||||
converted.value ? fallback.value : props.source
|
||||
);
|
||||
function convert() {
|
||||
converted.value = true;
|
||||
failed.value = false;
|
||||
}
|
||||
watch(
|
||||
() => props.source,
|
||||
() => {
|
||||
failed.value = false;
|
||||
converted.value = false;
|
||||
}
|
||||
);
|
||||
</script>
|
||||
<style scoped>
|
||||
.media-player {
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 16px;
|
||||
}
|
||||
.media-player audio {
|
||||
width: min(640px, 100%);
|
||||
}
|
||||
.media-feedback {
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
max-width: 640px;
|
||||
padding: 12px;
|
||||
color: var(--textSecondary);
|
||||
}
|
||||
.media-feedback p {
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
.media-feedback a {
|
||||
display: inline-block;
|
||||
margin: 0 12px;
|
||||
}
|
||||
</style>
|
||||
@@ -25,19 +25,10 @@
|
||||
class="resource-image"
|
||||
@error="failed = true"
|
||||
/>
|
||||
<audio
|
||||
v-else-if="kind === 'audio'"
|
||||
:src="source"
|
||||
controls
|
||||
preload="metadata"
|
||||
@error="failed = true"
|
||||
/>
|
||||
<video
|
||||
v-else-if="kind === 'video'"
|
||||
:src="source"
|
||||
controls
|
||||
preload="metadata"
|
||||
@error="failed = true"
|
||||
<MediaPlayer
|
||||
v-else-if="kind === 'audio' || kind === 'video'"
|
||||
:source="source"
|
||||
:audio="kind === 'audio'"
|
||||
/>
|
||||
<EpubPreview v-else-if="kind === 'epub'" :source="source" />
|
||||
<template v-else>
|
||||
@@ -86,6 +77,7 @@ const DicomViewer = defineAsyncComponent(() => import("./DicomViewer.vue"));
|
||||
const CsvViewer = defineAsyncComponent(() => import("./CsvViewer.vue"));
|
||||
const EpubPreview = defineAsyncComponent(() => import("./EpubPreview.vue"));
|
||||
const ZipPreview = defineAsyncComponent(() => import("./ZipPreview.vue"));
|
||||
const MediaPlayer = defineAsyncComponent(() => import("./MediaPlayer.vue"));
|
||||
const props = defineProps<{
|
||||
source: string;
|
||||
name: string;
|
||||
|
||||
@@ -9,13 +9,15 @@
|
||||
class="server-picker"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="t('addons.serverOpen')"
|
||||
:aria-label="t(intent === 'save' ? 'addons.saveAs' : 'addons.serverOpen')"
|
||||
ref="dialog"
|
||||
tabindex="-1"
|
||||
>
|
||||
<div class="picker-header">
|
||||
<div>
|
||||
<h2>{{ t("addons.serverOpen") }}</h2>
|
||||
<h2>
|
||||
{{ t(intent === "save" ? "addons.saveAs" : "addons.serverOpen") }}
|
||||
</h2>
|
||||
<p>{{ t("addons.serverOpenHint") }}</p>
|
||||
</div>
|
||||
<button
|
||||
@@ -40,37 +42,61 @@
|
||||
<p v-if="error || externalError" role="alert" class="document-error">
|
||||
{{ error || externalError }}
|
||||
</p>
|
||||
<p v-if="busy" class="picker-status">{{ t("files.loading") }}</p>
|
||||
<ul v-else>
|
||||
<li v-for="item in visible" :key="item.path">
|
||||
<button
|
||||
:class="{ selected: selected?.path === item.path }"
|
||||
@click="item.isDir ? load(item.path) : (selected = item)"
|
||||
@dblclick="!item.isDir && open(item)"
|
||||
>
|
||||
<FileIcon :name="item.name" :directory="item.isDir" /><span>{{
|
||||
item.name
|
||||
}}</span
|
||||
><small>{{ item.isDir ? "" : filesize(item.size) }}</small>
|
||||
</button>
|
||||
</li>
|
||||
<li v-if="!visible.length" class="picker-status">
|
||||
{{ t("files.noItems") }}
|
||||
</li>
|
||||
</ul>
|
||||
<div class="picker-browser">
|
||||
<aside>
|
||||
<DirectoryTree
|
||||
path="/"
|
||||
:label="t('sidebar.myFiles')"
|
||||
:selected-path="path"
|
||||
@select="load"
|
||||
/>
|
||||
</aside>
|
||||
<p v-if="busy" class="picker-status">{{ t("files.loading") }}</p>
|
||||
<ul v-else>
|
||||
<li v-for="item in visible" :key="item.path">
|
||||
<button
|
||||
:class="{ selected: selected?.path === item.path }"
|
||||
@click="select(item)"
|
||||
@dblclick="!item.isDir && intent !== 'save' && open(item)"
|
||||
>
|
||||
<FileIcon :name="item.name" :directory="item.isDir" /><span>{{
|
||||
item.name
|
||||
}}</span
|
||||
><small>{{ item.isDir ? "" : filesize(item.size) }}</small>
|
||||
</button>
|
||||
</li>
|
||||
<li v-if="!visible.length" class="picker-status">
|
||||
{{ t("files.noItems") }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<footer>
|
||||
<span :title="selected?.name">{{ selected?.name }}</span
|
||||
<label v-if="intent === 'save'" class="picker-filename"
|
||||
>{{ t("files.name")
|
||||
}}<input
|
||||
v-model="filename"
|
||||
class="input"
|
||||
@keydown.enter.prevent="save"
|
||||
/></label>
|
||||
<span v-else :title="selected?.name">{{ selected?.name }}</span
|
||||
><button class="button button--flat" @click="$emit('cancel')">
|
||||
{{ t("buttons.cancel") }}</button
|
||||
><button
|
||||
v-if="selected && canOpen(selected)"
|
||||
v-if="intent === 'save'"
|
||||
class="button"
|
||||
:disabled="busy || !filename.trim()"
|
||||
@click="save"
|
||||
>
|
||||
{{ t("buttons.save") }}</button
|
||||
><button
|
||||
v-if="selected && canOpen(selected) && intent === 'open'"
|
||||
class="button"
|
||||
:disabled="busy"
|
||||
@click="open(selected)"
|
||||
>
|
||||
{{ t("buttons.open") }}</button
|
||||
><button
|
||||
v-if="selected && intent !== 'open'"
|
||||
v-if="selected && intent === 'choose'"
|
||||
class="button button--flat"
|
||||
:disabled="busy"
|
||||
@click="$emit('import', selected)"
|
||||
@@ -88,18 +114,40 @@ import * as api from "@/api/files";
|
||||
import { encodePath } from "@/utils/url";
|
||||
import { filesize } from "filesize";
|
||||
import FileIcon from "./FileIcon.vue";
|
||||
import DirectoryTree from "./DirectoryTree.vue";
|
||||
const props = defineProps<{
|
||||
initialPath: string;
|
||||
extensions: string[];
|
||||
intent: string;
|
||||
externalError?: string;
|
||||
suggestedName?: string;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
open: [item: ResourceItem];
|
||||
import: [item: ResourceItem];
|
||||
cancel: [];
|
||||
save: [directory: string, name: string, existing?: ResourceItem];
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const filename = ref(props.suggestedName || "");
|
||||
function select(item: ResourceItem) {
|
||||
if (item.isDir) load(item.path);
|
||||
else {
|
||||
selected.value = item;
|
||||
if (props.intent === "save") filename.value = item.name;
|
||||
}
|
||||
}
|
||||
function save() {
|
||||
if (!busy.value && filename.value.trim())
|
||||
emit(
|
||||
"save",
|
||||
path.value,
|
||||
filename.value.trim(),
|
||||
items.value.find(
|
||||
(item) => !item.isDir && item.name === filename.value.trim()
|
||||
)
|
||||
);
|
||||
}
|
||||
const path = ref("/"),
|
||||
query = ref(""),
|
||||
items = ref<ResourceItem[]>([]),
|
||||
@@ -116,7 +164,7 @@ const visible = computed(() =>
|
||||
(i) =>
|
||||
i.isDir ||
|
||||
(i.name.toLowerCase().includes(query.value.toLowerCase()) &&
|
||||
(props.intent !== "open" || canOpen(i)))
|
||||
(!props.extensions.length || canOpen(i)))
|
||||
)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
@@ -243,6 +291,20 @@ onBeforeUnmount(() => {
|
||||
flex: 1;
|
||||
min-height: 180px;
|
||||
}
|
||||
.picker-browser {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 180px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.picker-browser aside {
|
||||
width: 220px;
|
||||
flex: none;
|
||||
padding: 8px;
|
||||
overflow: auto;
|
||||
border-right: 1px solid var(--borderPrimary);
|
||||
font-size: 13px;
|
||||
}
|
||||
.server-picker li button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -287,7 +349,22 @@ onBeforeUnmount(() => {
|
||||
.picker-status {
|
||||
padding: 20px;
|
||||
}
|
||||
.picker-filename {
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
.picker-filename input {
|
||||
margin: 0;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.picker-browser aside {
|
||||
width: 120px;
|
||||
}
|
||||
.server-picker-backdrop {
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import "videojs-mobile-ui/dist/videojs-mobile-ui.css";
|
||||
|
||||
const videoPlayer = ref<HTMLElement | null>(null);
|
||||
const player = ref<Player | null>(null);
|
||||
const emit = defineEmits<{ error: [] }>();
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
@@ -81,11 +82,13 @@ const initVideoPlayer = async () => {
|
||||
playbackRatesOpt
|
||||
);
|
||||
player.value = videojs(videoPlayer.value!, options, () => {});
|
||||
player.value.on("error", () => emit("error"));
|
||||
|
||||
// TODO: need to test on mobile
|
||||
// @ts-expect-error no ts definition for mobileUi
|
||||
player.value!.mobileUi();
|
||||
} catch (error) {
|
||||
emit("error");
|
||||
console.error("Error initializing video player:", error);
|
||||
}
|
||||
};
|
||||
@@ -113,11 +116,11 @@ const getOptions = (...srcOpt: any[]) => {
|
||||
return videojs.obj.merge(options, ...srcOpt);
|
||||
};
|
||||
|
||||
// Attempting to fix the issue of being unable to play .MKV format video files
|
||||
// Preserve the real container type; renaming MKV to MP4 cannot add a decoder.
|
||||
const getSourceType = (source: string) => {
|
||||
const fileExtension = source ? source.split("?")[0].split(".").pop() : "";
|
||||
if (fileExtension?.toLowerCase() === "mkv") {
|
||||
return "video/mp4";
|
||||
return "video/x-matroska";
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<template>
|
||||
<button @click="action" :aria-label="label" :title="label" class="action">
|
||||
<AppIcon :name="icon" />
|
||||
<img v-if="iconSrc" :src="iconSrc" class="action-app-icon" alt="" /><AppIcon
|
||||
v-else
|
||||
:name="icon"
|
||||
/>
|
||||
<span>{{ label }}</span>
|
||||
<span v-if="counter && counter > 0" class="counter">{{ counter }}</span>
|
||||
</button>
|
||||
@@ -11,6 +14,7 @@ import { useLayoutStore } from "@/stores/layout";
|
||||
|
||||
const props = defineProps<{
|
||||
icon?: string;
|
||||
iconSrc?: string;
|
||||
label?: string;
|
||||
counter?: number;
|
||||
show?: string;
|
||||
@@ -30,3 +34,11 @@ const action = () => {
|
||||
emit("action");
|
||||
};
|
||||
</script>
|
||||
<style scoped>
|
||||
.action-app-icon {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
object-fit: contain;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div class="card floating">
|
||||
<div class="card-title">
|
||||
<h2>{{ t("buttons.create") }}</h2>
|
||||
<h2>{{ t("explorer.createFile") }}</h2>
|
||||
</div>
|
||||
<div class="create-type-options"><CreateOptions /></div>
|
||||
</div>
|
||||
|
||||
@@ -3,10 +3,20 @@
|
||||
<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 class="addon-grid">
|
||||
<article v-for="addon in store.items" :key="addon.id" class="addon-card">
|
||||
<div class="addon-details">
|
||||
<AppIcon :name="addon.icon || 'package'" />
|
||||
<div class="addon-table" role="table" :aria-label="t('addons.title')">
|
||||
<article
|
||||
v-for="addon in store.items"
|
||||
:key="addon.id"
|
||||
class="addon-row"
|
||||
:class="{ 'is-incompatible': addon.compatibilityIssue }"
|
||||
role="row"
|
||||
>
|
||||
<div class="addon-details" role="cell">
|
||||
<img
|
||||
class="addon-logo"
|
||||
:src="baseURL + '/static/img/artcraft/' + addon.id + '.webp'"
|
||||
alt=""
|
||||
/>
|
||||
<div>
|
||||
<strong>{{ addon.name }}</strong
|
||||
><small
|
||||
@@ -27,17 +37,16 @@
|
||||
}}</small>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="addon.compatibilityIssue" class="addon-incompatible">
|
||||
<strong>{{ t("addons.incompatible") }}</strong> ·
|
||||
{{ t("addons.compatibility." + addon.compatibilityIssue) }}
|
||||
</p>
|
||||
<p v-if="addon.id === 'deckcraft'" class="field-hint">
|
||||
{{ t("addons.deckcraftFormat") }}
|
||||
</p>
|
||||
<p v-if="addon.id === 'lightcraft'" class="field-hint">
|
||||
{{ t("addons.rawCopies") }}
|
||||
</p>
|
||||
<div class="addon-controls">
|
||||
<div role="cell" class="addon-note-cell">
|
||||
<span
|
||||
v-if="note(addon)"
|
||||
class="addon-note"
|
||||
tabindex="0"
|
||||
:aria-label="note(addon)"
|
||||
>ⓘ<span role="tooltip">{{ note(addon) }}</span></span
|
||||
>
|
||||
</div>
|
||||
<div class="addon-controls" role="cell">
|
||||
<label v-if="addon.build" class="settings-toggle"
|
||||
><span>{{ t("addons.enabled") }}</span
|
||||
><input
|
||||
@@ -51,13 +60,22 @@
|
||||
<button
|
||||
type="button"
|
||||
class="button"
|
||||
:disabled="busy(addon) || changing === addon.id"
|
||||
:disabled="
|
||||
busy(addon) || changing === addon.id || !!addon.compatibilityIssue
|
||||
"
|
||||
@click="install(addon)"
|
||||
>
|
||||
<AppIcon :name="addon.build ? 'refresh' : 'download'" />{{
|
||||
addon.build ? t("addons.update") : t("addons.install")
|
||||
}}
|
||||
</button>
|
||||
<a
|
||||
class="button button--flat"
|
||||
:href="'https://getartcraft.com/apps/' + addon.id"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>{{ t("addons.about") }}</a
|
||||
>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
@@ -69,10 +87,24 @@ import { onMounted, onBeforeUnmount, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { fetchURL } from "@/api/utils";
|
||||
import { useAddonsStore, type Addon } from "@/stores/addons";
|
||||
import { baseURL } from "@/utils/constants";
|
||||
const store = useAddonsStore(),
|
||||
{ t } = useI18n(),
|
||||
error = ref(""),
|
||||
changing = ref("");
|
||||
function note(addon: Addon) {
|
||||
return addon.compatibilityIssue
|
||||
? t("addons.incompatible") +
|
||||
": " +
|
||||
t("addons.compatibility." + addon.compatibilityIssue)
|
||||
: addon.id === "deckcraft"
|
||||
? t("addons.deckcraftFormat")
|
||||
: addon.id === "lightcraft"
|
||||
? t("addons.rawCopies")
|
||||
: addon.id === "soundcraft"
|
||||
? t("addons.soundcraftSessions")
|
||||
: "";
|
||||
}
|
||||
let timer: ReturnType<typeof setTimeout> | undefined,
|
||||
disposed = false;
|
||||
const busy = (addon: Addon) =>
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
<template>
|
||||
<div
|
||||
class="auto-open-backdrop"
|
||||
@click.self="$emit('close')"
|
||||
@keydown.esc.stop.prevent="$emit('close')"
|
||||
@keydown.tab="trapFocus"
|
||||
>
|
||||
<section
|
||||
ref="dialog"
|
||||
class="card auto-open-dialog"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="t('preferences.autoOpen')"
|
||||
tabindex="-1"
|
||||
>
|
||||
<div class="auto-open-header">
|
||||
<h2>{{ t("preferences.autoOpen") }}</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="action"
|
||||
:aria-label="t('buttons.close')"
|
||||
@click="$emit('close')"
|
||||
>
|
||||
<AppIcon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
<p class="field-hint">{{ t("preferences.autoOpenHint") }}</p>
|
||||
<input
|
||||
v-model="search"
|
||||
class="input"
|
||||
type="search"
|
||||
:placeholder="t('preferences.extensionSearch')"
|
||||
:aria-label="t('preferences.extensionSearch')"
|
||||
/>
|
||||
<div class="auto-open-list">
|
||||
<label
|
||||
v-for="extension in visible"
|
||||
:key="extension"
|
||||
class="auto-open-row"
|
||||
><strong>{{ extension }}</strong>
|
||||
<select
|
||||
class="input"
|
||||
:value="modelValue[extension] || ''"
|
||||
:aria-label="extension"
|
||||
@change="
|
||||
choose(extension, ($event.target as HTMLSelectElement).value)
|
||||
"
|
||||
>
|
||||
<option value="">{{ t("preferences.openDefault") }}</option>
|
||||
<option value="preview">{{ t("preferences.openPreview") }}</option>
|
||||
<option value="download">{{ t("buttons.download") }}</option>
|
||||
<option
|
||||
v-for="tool in tools(extension)"
|
||||
:key="tool.id"
|
||||
:value="tool.id"
|
||||
:disabled="!available(tool)"
|
||||
>
|
||||
{{ tool.name
|
||||
}}{{ available(tool) ? "" : " · " + t("addons.unavailable") }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<p v-if="!visible.length" class="field-hint">
|
||||
{{ t("files.noItems") }}
|
||||
</p>
|
||||
</div>
|
||||
<footer>
|
||||
<span class="field-hint">{{ t("preferences.autoOpenSaveHint") }}</span
|
||||
><button class="button" type="button" @click="$emit('close')">
|
||||
{{ t("buttons.ok") }}
|
||||
</button>
|
||||
</footer>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useAddonsStore, type Addon } from "@/stores/addons";
|
||||
import { knownFileExtensions } from "@/utils/file-icons";
|
||||
import { addonAccepts } from "@/utils/craft";
|
||||
const props = defineProps<{ modelValue: Record<string, string> }>();
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: Record<string, string>];
|
||||
close: [];
|
||||
}>();
|
||||
const { t } = useI18n(),
|
||||
addons = useAddonsStore(),
|
||||
search = ref(""),
|
||||
dialog = ref<HTMLElement>();
|
||||
const extensions = computed(() =>
|
||||
[
|
||||
...new Set([
|
||||
...knownFileExtensions,
|
||||
...addons.items.flatMap((tool) => tool.extensions || [tool.extension]),
|
||||
...Object.keys(props.modelValue),
|
||||
]),
|
||||
].sort()
|
||||
);
|
||||
const visible = computed(() =>
|
||||
extensions.value.filter((extension) =>
|
||||
extension.includes(search.value.trim().toLowerCase())
|
||||
)
|
||||
);
|
||||
const tools = (extension: string) =>
|
||||
addons.items.filter((tool) => addonAccepts(tool, "file" + extension));
|
||||
const available = (tool: Addon) =>
|
||||
tool.enabled && !!tool.build && !tool.compatibilityIssue;
|
||||
function choose(extension: string, handler: string) {
|
||||
const value = { ...props.modelValue };
|
||||
if (handler) value[extension] = handler;
|
||||
else delete value[extension];
|
||||
emit("update:modelValue", value);
|
||||
}
|
||||
const previous = document.activeElement as HTMLElement | null;
|
||||
function trapFocus(event: KeyboardEvent) {
|
||||
const elements = [
|
||||
...dialog.value!.querySelectorAll<HTMLElement>(
|
||||
"button:not(:disabled),input,select"
|
||||
),
|
||||
];
|
||||
const boundary = event.shiftKey ? elements[0] : elements.at(-1);
|
||||
if (
|
||||
document.activeElement === boundary ||
|
||||
document.activeElement === dialog.value
|
||||
) {
|
||||
event.preventDefault();
|
||||
(event.shiftKey ? elements.at(-1) : elements[0])?.focus();
|
||||
}
|
||||
}
|
||||
onMounted(() => {
|
||||
dialog.value?.querySelector("input")?.focus();
|
||||
addons.refresh().catch(() => {});
|
||||
});
|
||||
onBeforeUnmount(() => previous?.focus());
|
||||
</script>
|
||||
<style scoped>
|
||||
.auto-open-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 10020;
|
||||
background: #0008;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 16px;
|
||||
}
|
||||
.auto-open-dialog {
|
||||
width: min(760px, 100%);
|
||||
max-height: calc(100dvh - 32px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 20px;
|
||||
gap: 12px;
|
||||
margin: 0;
|
||||
}
|
||||
.auto-open-header,
|
||||
footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
h2,
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
.auto-open-dialog > .input {
|
||||
margin: 0;
|
||||
}
|
||||
.auto-open-list {
|
||||
overflow: auto;
|
||||
min-height: 150px;
|
||||
}
|
||||
.auto-open-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px solid var(--borderPrimary);
|
||||
}
|
||||
.auto-open-row strong {
|
||||
width: 100px;
|
||||
flex: none;
|
||||
}
|
||||
.auto-open-row select {
|
||||
margin: 0;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
footer {
|
||||
padding-top: 12px;
|
||||
}
|
||||
@media (max-width: 500px) {
|
||||
.auto-open-dialog {
|
||||
padding: 12px;
|
||||
}
|
||||
.auto-open-row strong {
|
||||
width: 70px;
|
||||
}
|
||||
footer {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,52 @@
|
||||
<template>
|
||||
<section class="card settings-section settings-wide">
|
||||
<h2><AppIcon name="video" />FFmpeg</h2>
|
||||
<p role="status">
|
||||
<strong>{{
|
||||
busy
|
||||
? t("files.loading")
|
||||
: status?.available
|
||||
? t("settings.ffmpegAvailable")
|
||||
: t("settings.ffmpegUnavailable")
|
||||
}}</strong>
|
||||
</p>
|
||||
<p v-if="status?.version" class="field-hint">{{ status.version }}</p>
|
||||
<p class="field-hint">{{ t("settings.ffmpegHint") }}</p>
|
||||
<p v-if="error" role="alert" class="document-error">{{ error }}</p>
|
||||
<button
|
||||
type="button"
|
||||
class="button button--flat"
|
||||
:disabled="busy"
|
||||
@click="refresh"
|
||||
>
|
||||
<AppIcon name="refresh" />{{ t("explorer.refresh") }}
|
||||
</button>
|
||||
</section>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onBeforeUnmount, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { fetchJSON } from "@/api/utils";
|
||||
const { t } = useI18n(),
|
||||
status = ref<{ available: boolean; version?: string }>(),
|
||||
busy = ref(false),
|
||||
error = ref("");
|
||||
const controller = new AbortController();
|
||||
async function refresh() {
|
||||
busy.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
status.value = await fetchJSON("/api/media/status", {
|
||||
signal: controller.signal,
|
||||
});
|
||||
} catch (failure) {
|
||||
if (!controller.signal.aborted)
|
||||
error.value =
|
||||
failure instanceof Error ? failure.message : String(failure);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
onMounted(refresh);
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
@@ -389,19 +389,77 @@
|
||||
padding: 14px;
|
||||
}
|
||||
}
|
||||
.addons-settings .addon-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr));
|
||||
gap: 16px;
|
||||
.addons-settings .addon-table {
|
||||
margin: 20px 0;
|
||||
}
|
||||
.addons-settings .addon-card {
|
||||
min-width: 0;
|
||||
padding: 20px;
|
||||
border: 1px solid var(--borderPrimary);
|
||||
border-radius: 14px;
|
||||
}
|
||||
.addons-settings .addon-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
min-width: 0;
|
||||
padding: 14px 20px;
|
||||
border-bottom: 1px solid var(--borderPrimary);
|
||||
}
|
||||
.addons-settings .addon-row:last-child {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.addon-row .addon-details {
|
||||
flex: 1;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
}
|
||||
.addon-row.is-incompatible {
|
||||
color: var(--textSecondary);
|
||||
background: var(--surfaceSecondary);
|
||||
}
|
||||
.addon-row.is-incompatible .addon-logo {
|
||||
filter: grayscale(1);
|
||||
opacity: 0.5;
|
||||
}
|
||||
.addon-logo {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
object-fit: contain;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.addon-note {
|
||||
position: relative;
|
||||
cursor: help;
|
||||
color: var(--blue);
|
||||
}
|
||||
.addon-note [role="tooltip"] {
|
||||
display: none;
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 130%;
|
||||
width: min(320px, 70vw);
|
||||
padding: 12px;
|
||||
border: 1px solid var(--borderPrimary);
|
||||
background: var(--surfacePrimary);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 20px #0004;
|
||||
z-index: 1;
|
||||
color: var(--textPrimary);
|
||||
font-size: 13px;
|
||||
}
|
||||
.addon-note:hover [role="tooltip"],
|
||||
.addon-note:focus [role="tooltip"] {
|
||||
display: block;
|
||||
}
|
||||
@media (max-width: 700px) {
|
||||
.addons-settings .addon-row {
|
||||
flex-wrap: wrap;
|
||||
padding: 12px;
|
||||
}
|
||||
.addon-row .addon-details {
|
||||
flex-basis: 75%;
|
||||
}
|
||||
.addons-settings .addon-row .addon-controls {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
.addon-details {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
@@ -433,7 +491,7 @@
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 14px;
|
||||
margin-top: 20px;
|
||||
margin-top: 0;
|
||||
}
|
||||
.addons-settings .addon-controls .settings-toggle {
|
||||
padding: 0;
|
||||
@@ -484,22 +542,6 @@
|
||||
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;
|
||||
}
|
||||
.craft-feedback {
|
||||
position: absolute;
|
||||
bottom: 16px;
|
||||
@@ -514,9 +556,6 @@
|
||||
box-shadow: 0 8px 32px #0003;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.addons-settings .addon-card {
|
||||
padding: 16px;
|
||||
}
|
||||
.addon-controls .button {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
@@ -72,6 +72,10 @@
|
||||
"connection": "The server can't be reached."
|
||||
},
|
||||
"files": {
|
||||
"mediaCodecError": "The browser cannot play this codec. Try server conversion.",
|
||||
"mediaConvert": "Play compatible stream",
|
||||
"mediaConverted": "Server conversion is active. Seeking is limited to buffered media.",
|
||||
"mediaUnavailable": "Conversion failed or FFmpeg is unavailable on the server. Download the original to play locally.",
|
||||
"editorUndo": "Undo",
|
||||
"editorRedo": "Redo",
|
||||
"editorFind": "Find",
|
||||
@@ -292,7 +296,10 @@
|
||||
"showPreviews": "Show previews",
|
||||
"downloadsTitle": "Downloads",
|
||||
"downloadArchiveFormat": "Archive format",
|
||||
"downloadArchiveHint": "Folders and multiple selected files download immediately using this format. A single file downloads without an archive."
|
||||
"downloadArchiveHint": "Folders and multiple selected files download immediately using this format. A single file downloads without an archive.",
|
||||
"ffmpegAvailable": "Available",
|
||||
"ffmpegUnavailable": "Unavailable",
|
||||
"ffmpegHint": "FFmpeg on the server converts audio and video codecs that the browser cannot play."
|
||||
},
|
||||
"sidebar": {
|
||||
"diskUsed": "{used} of {total} used",
|
||||
@@ -409,7 +416,8 @@
|
||||
"downloadFolderArchive": "Download folder archive",
|
||||
"account": "Account",
|
||||
"adminSettings": "Control panel",
|
||||
"usersHint": "Manage user scope, permissions and access rules"
|
||||
"usersHint": "Manage user scope, permissions and access rules",
|
||||
"createFile": "Create file"
|
||||
},
|
||||
"preferences": {
|
||||
"appearance": "Appearance",
|
||||
@@ -426,7 +434,13 @@
|
||||
"dicomQuarter": "Quarter resolution",
|
||||
"dicomMemory": "Voxel memory limit",
|
||||
"dicomOpacity": "Initial opacity",
|
||||
"dicomHint": "Automatic mode reduces large series while preserving all slices and physical proportions. The limit covers voxels; assembly and GPU rendering need additional memory."
|
||||
"dicomHint": "Automatic mode reduces large series while preserving all slices and physical proportions. The limit covers voxels; assembly and GPU rendering need additional memory.",
|
||||
"autoOpen": "Auto-open settings",
|
||||
"autoOpenHint": "Choose how each extension opens. Unavailable editors fall back to the built-in viewer. These preferences do not change access permissions.",
|
||||
"extensionSearch": "Search extensions…",
|
||||
"openDefault": "Default behavior",
|
||||
"openPreview": "Built-in viewer",
|
||||
"autoOpenSaveHint": "Save your profile settings to apply these changes."
|
||||
},
|
||||
"notifications": {
|
||||
"success": "Done",
|
||||
@@ -446,6 +460,9 @@
|
||||
"pdf": "PDF document"
|
||||
},
|
||||
"addons": {
|
||||
"about": "About",
|
||||
"overwrite": "Replace {name}? The existing server file will be overwritten.",
|
||||
"soundcraftSessions": "SoundCraft edits sessions (.scraftz). Use Import to add audio to the current session.",
|
||||
"deckcraftFormat": "Save uses the .deckcraft format. Use the editor’s export command for PPTX.",
|
||||
"rawCopies": "RAW originals stay unchanged. Exports are separate files; the library and adjustments live in this tab.",
|
||||
"popupBlocked": "Allow new tabs in your browser.",
|
||||
@@ -467,8 +484,8 @@
|
||||
"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.",
|
||||
"invalidName": "Enter a valid filename with a supported extension, without a path.",
|
||||
"tooLarge": "The file is too large. Editors support files up to 256 MiB. Reduce the file size or open it in a desktop application.",
|
||||
"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": {
|
||||
|
||||
@@ -72,6 +72,10 @@
|
||||
"connection": "Нет подключения к серверу."
|
||||
},
|
||||
"files": {
|
||||
"mediaCodecError": "Браузер не может воспроизвести этот кодек. Попробуйте преобразование на сервере.",
|
||||
"mediaConvert": "Воспроизвести совместимый поток",
|
||||
"mediaConverted": "Включено преобразование на сервере. Перемотка доступна в пределах загруженной части.",
|
||||
"mediaUnavailable": "Не удалось преобразовать файл или на сервере отсутствует FFmpeg. Скачайте оригинал для воспроизведения на компьютере.",
|
||||
"editorUndo": "Отменить",
|
||||
"editorRedo": "Повторить",
|
||||
"editorFind": "Найти",
|
||||
@@ -289,7 +293,10 @@
|
||||
"showPreviews": "Показ превью",
|
||||
"downloadsTitle": "Скачивание",
|
||||
"downloadArchiveFormat": "Формат архива",
|
||||
"downloadArchiveHint": "Папки и несколько выбранных файлов скачиваются сразу в этом формате. Отдельный файл скачивается без архива."
|
||||
"downloadArchiveHint": "Папки и несколько выбранных файлов скачиваются сразу в этом формате. Отдельный файл скачивается без архива.",
|
||||
"ffmpegAvailable": "Доступен",
|
||||
"ffmpegUnavailable": "Недоступен",
|
||||
"ffmpegHint": "FFmpeg на сервере преобразует аудио и видео с кодеками, которые не поддерживает браузер."
|
||||
},
|
||||
"sidebar": {
|
||||
"diskUsed": "Занято {used} из {total}",
|
||||
@@ -299,7 +306,7 @@
|
||||
"logout": "Выйти",
|
||||
"myFiles": "Файлы",
|
||||
"newFile": "Новый файл",
|
||||
"newFolder": "Новый каталог",
|
||||
"newFolder": "Создать папку",
|
||||
"preview": "Предпросмотр",
|
||||
"settings": "Настройки",
|
||||
"signup": "Зарегистрироваться",
|
||||
@@ -406,7 +413,8 @@
|
||||
"downloadFolderArchive": "Скачать папку архивом",
|
||||
"account": "Аккаунт",
|
||||
"adminSettings": "Панель управления",
|
||||
"usersHint": "Область доступа, разрешения и правила пользователей"
|
||||
"usersHint": "Область доступа, разрешения и правила пользователей",
|
||||
"createFile": "Создать файл"
|
||||
},
|
||||
"preferences": {
|
||||
"appearance": "Внешний вид",
|
||||
@@ -423,7 +431,13 @@
|
||||
"dicomQuarter": "Уменьшить разрешение в 4 раза",
|
||||
"dicomMemory": "Лимит памяти для вокселей",
|
||||
"dicomOpacity": "Начальная непрозрачность",
|
||||
"dicomHint": "Автоматический режим уменьшает большие серии, сохраняя все срезы и физические пропорции. Лимит относится к вокселям; сборка и видеокарта требуют дополнительной памяти."
|
||||
"dicomHint": "Автоматический режим уменьшает большие серии, сохраняя все срезы и физические пропорции. Лимит относится к вокселям; сборка и видеокарта требуют дополнительной памяти.",
|
||||
"autoOpen": "Настройки автооткрытия",
|
||||
"autoOpenHint": "Выберите способ открытия для каждого расширения. Если редактор недоступен, файл откроется во встроенном просмотре. Настройки не меняют права доступа.",
|
||||
"extensionSearch": "Поиск расширений…",
|
||||
"openDefault": "По умолчанию",
|
||||
"openPreview": "Встроенный просмотр",
|
||||
"autoOpenSaveHint": "Сохраните настройки профиля, чтобы применить изменения."
|
||||
},
|
||||
"notifications": {
|
||||
"success": "Готово",
|
||||
@@ -443,6 +457,9 @@
|
||||
"pdf": "Документ PDF"
|
||||
},
|
||||
"addons": {
|
||||
"about": "О приложении",
|
||||
"overwrite": "Заменить {name}? Существующий файл на сервере будет перезаписан.",
|
||||
"soundcraftSessions": "SoundCraft редактирует сессии (.scraftz). Добавляйте аудио через «Импорт» в текущую сессию.",
|
||||
"deckcraftFormat": "Сохранение — в формате .deckcraft. PPTX доступен через экспорт в редакторе.",
|
||||
"rawCopies": "RAW сохраняется без изменений. Экспорт — отдельным файлом; каталог и настройки обработки действуют в этой вкладке.",
|
||||
"popupBlocked": "Разрешите открытие новых вкладок в браузере.",
|
||||
@@ -464,8 +481,8 @@
|
||||
"leaveUnsaved": "Изменения ещё не сохранены на сервере. Покинуть редактор?",
|
||||
"conflict": "Файл изменился на сервере или имя уже занято. Сохраните под другим именем либо скачайте копию; исходный файл не перезаписан.",
|
||||
"saveFailed": "Не удалось сохранить на сервере.",
|
||||
"invalidName": "Укажите корректное имя с расширением .xlsx или .pdf, без пути.",
|
||||
"tooLarge": "Документы ограничены 64 МиБ.",
|
||||
"invalidName": "Укажите корректное имя с поддерживаемым расширением, без пути.",
|
||||
"tooLarge": "Файл слишком большой. Максимальный размер для редактора — 256 МиБ. Уменьшите размер файла или откройте его в приложении на компьютере.",
|
||||
"unavailable": "Редактор не установлен, отключён или нет разрешения на редактирование.",
|
||||
"startFailed": "Редактор не запустился. Проверьте поддержку WebGL2/WebGPU и установленную версию аддона.",
|
||||
"states": {
|
||||
|
||||
@@ -18,6 +18,7 @@ interface IUser {
|
||||
hidePreviews?: boolean;
|
||||
dicom3D?: Dicom3DSettings;
|
||||
singleClick: boolean;
|
||||
autoOpen?: Record<string, string>;
|
||||
redirectAfterCopyMove: boolean;
|
||||
dateFormat: boolean;
|
||||
viewMode: ViewModeType;
|
||||
|
||||
@@ -2,11 +2,39 @@ import { expect, it } from "vitest";
|
||||
import {
|
||||
addonAccepts,
|
||||
defaultCraftTool,
|
||||
fileOpenPreference,
|
||||
craftSaveExtension,
|
||||
craftLocation,
|
||||
craftMessage,
|
||||
safeCraftName,
|
||||
} from "../craft";
|
||||
it("honors extension preferences, including images, without opening unavailable editors", () => {
|
||||
const photo = {
|
||||
id: "photocraft",
|
||||
extension: ".png",
|
||||
extensions: [".png", ".jpg"],
|
||||
enabled: true,
|
||||
build: "installed",
|
||||
} as import("@/stores/addons").Addon;
|
||||
expect(
|
||||
defaultCraftTool([photo], "photo.PNG", "image", { ".png": "photocraft" })
|
||||
).toBe(photo);
|
||||
expect(
|
||||
defaultCraftTool([photo], "photo.png", "image", { ".png": "preview" })
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
defaultCraftTool([photo], "photo.png", "image", { ".png": "download" })
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
defaultCraftTool([{ ...photo, enabled: false }], "photo.png", "image", {
|
||||
".png": "photocraft",
|
||||
})
|
||||
).toBeUndefined();
|
||||
expect(fileOpenPreference({ ".mp3": "download" }, "song.MP3")).toBe(
|
||||
"download"
|
||||
);
|
||||
expect(fileOpenPreference({ ".mp3": "download" }, "folder")).toBeUndefined();
|
||||
});
|
||||
it("accepts messages only from the specific same-origin editor frame", () => {
|
||||
const frame = {} as Window,
|
||||
origin = "https://files.test";
|
||||
|
||||
@@ -117,8 +117,8 @@ it("rejects failed writes and bounds memory before accepting document data", asy
|
||||
await context.showSaveFilePicker({ suggestedName: "report.docx" })
|
||||
).createWritable();
|
||||
await expect(
|
||||
writer.write(new Uint8Array(64 * 1024 * 1024 + 1))
|
||||
).rejects.toThrow("64 MiB");
|
||||
writer.write(new Uint8Array(256 * 1024 * 1024 + 1))
|
||||
).rejects.toThrow("256 MiB");
|
||||
await writer.write(new Uint8Array([1]));
|
||||
const saved = writer.close();
|
||||
const rejected = expect(saved).rejects.toThrow("Server could not save");
|
||||
@@ -147,6 +147,29 @@ it("captures presentation saves but preserves native downloads for unrelated exp
|
||||
expect(nativeClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("supports seek, positional writes and truncate without corrupting the exported file", async () => {
|
||||
const { context, messages, receive } = bridge();
|
||||
const writer = await (
|
||||
await context.showSaveFilePicker({ suggestedName: "report.docx" })
|
||||
).createWritable();
|
||||
await writer.write(new Uint8Array([1, 2, 3, 4]));
|
||||
await writer.write({ type: "write", position: 1, data: new Uint8Array([9]) });
|
||||
await writer.truncate(3);
|
||||
await writer.seek(4);
|
||||
await writer.write(new Uint8Array([5]));
|
||||
const saving = writer.close();
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((message) => message.type === "wordcraft:save")).toBe(
|
||||
true
|
||||
)
|
||||
);
|
||||
const message = messages.find((message) => message.type === "wordcraft:save");
|
||||
expect([...new Uint8Array(message.bytes)]).toEqual([1, 9, 3, 0, 5]);
|
||||
expect(message.saveAs).toBe(true);
|
||||
receive({ type: "wordcraft:saved", requestId: message.requestId });
|
||||
await saving;
|
||||
});
|
||||
|
||||
it("adapts verified graphics, layout, RAW and audio builds without changing office defaults", () => {
|
||||
for (const [id, extension, output] of [
|
||||
["photocraft", ".png", ".pcraft"],
|
||||
|
||||
@@ -55,6 +55,7 @@ export function craftMessage(
|
||||
saveAs?: boolean;
|
||||
error?: string;
|
||||
intent?: string;
|
||||
accept?: string;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -73,7 +74,30 @@ export function craftSaveExtension(
|
||||
);
|
||||
}
|
||||
|
||||
export function defaultCraftTool(items: Addon[], name: string, type = "") {
|
||||
export function fileOpenPreference(
|
||||
preferences: Record<string, string> | undefined,
|
||||
name: string
|
||||
) {
|
||||
const dot = name.lastIndexOf(".");
|
||||
return dot >= 0 ? preferences?.[name.slice(dot).toLowerCase()] : undefined;
|
||||
}
|
||||
export function defaultCraftTool(
|
||||
items: Addon[],
|
||||
name: string,
|
||||
type = "",
|
||||
preferences?: Record<string, string>
|
||||
) {
|
||||
const preferred = fileOpenPreference(preferences, name);
|
||||
if (preferred === "preview" || preferred === "download") return undefined;
|
||||
if (preferred)
|
||||
return items.find(
|
||||
(item) =>
|
||||
item.id === preferred &&
|
||||
item.enabled &&
|
||||
!item.compatibilityIssue &&
|
||||
item.build &&
|
||||
addonAccepts(item, name)
|
||||
);
|
||||
const preview = previewKind(name, type);
|
||||
if (preview && preview !== "pdf") return undefined;
|
||||
return items.find(
|
||||
|
||||
@@ -61,6 +61,11 @@ const extensions: Partial<Record<FileIconKind, string>> = {
|
||||
text: "txt text log md markdown rst adoc nfo srt vtt ass sub tex bib",
|
||||
};
|
||||
const lookup = new Map<string, FileIconKind>();
|
||||
export const knownFileExtensions = [
|
||||
...new Set(Object.values(extensions).flatMap((names) => names.split(" "))),
|
||||
]
|
||||
.map((name) => "." + name)
|
||||
.sort();
|
||||
for (const [kind, names] of Object.entries(extensions))
|
||||
for (const name of names.split(" "))
|
||||
if (!lookup.has(name)) lookup.set(name, kind as FileIconKind);
|
||||
|
||||
@@ -42,11 +42,42 @@ export function previewKind(
|
||||
)
|
||||
return "image";
|
||||
if (
|
||||
["mp3", "wav", "ogg", "oga", "flac", "m4a", "aac", "opus"].includes(ext) ||
|
||||
[
|
||||
"mp3",
|
||||
"wav",
|
||||
"ogg",
|
||||
"oga",
|
||||
"flac",
|
||||
"m4a",
|
||||
"aac",
|
||||
"opus",
|
||||
"aif",
|
||||
"aiff",
|
||||
"wma",
|
||||
"ac3",
|
||||
"dts",
|
||||
].includes(ext) ||
|
||||
type === "audio"
|
||||
)
|
||||
return "audio";
|
||||
if (["mp4", "m4v", "webm", "ogv", "mov"].includes(ext) || type === "video")
|
||||
if (
|
||||
[
|
||||
"mp4",
|
||||
"m4v",
|
||||
"webm",
|
||||
"ogv",
|
||||
"mov",
|
||||
"mkv",
|
||||
"avi",
|
||||
"wmv",
|
||||
"mpg",
|
||||
"mpeg",
|
||||
"mts",
|
||||
"m2ts",
|
||||
"flv",
|
||||
].includes(ext) ||
|
||||
type === "video"
|
||||
)
|
||||
return "video";
|
||||
if (
|
||||
[
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
<template>
|
||||
<div class="craft-editor">
|
||||
<ServerFilePicker
|
||||
v-if="pickerRequest"
|
||||
v-if="pickerRequest || saveAs"
|
||||
:initial-path="
|
||||
currentPath.slice(0, currentPath.lastIndexOf('/') + 1) || '/'
|
||||
"
|
||||
:extensions="activeTool?.extensions || [activeTool?.extension || '']"
|
||||
:intent="pickerRequest.intent"
|
||||
:extensions="saveAs ? activeTool?.exports || [] : pickerExtensions"
|
||||
:intent="saveAs ? 'save' : pickerRequest!.intent"
|
||||
:suggested-name="newName"
|
||||
:external-error="error"
|
||||
@cancel="cancelPicker"
|
||||
@cancel="cancelDialog"
|
||||
@save="confirmSaveAs"
|
||||
@open="openServerDocument"
|
||||
@import="importServerFile"
|
||||
/>
|
||||
@@ -60,20 +62,6 @@
|
||||
>{{ 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>
|
||||
</div>
|
||||
<iframe
|
||||
v-if="frameURL"
|
||||
@@ -144,10 +132,42 @@ interface Save {
|
||||
create: boolean;
|
||||
revision: number;
|
||||
requestId?: string;
|
||||
tag?: string;
|
||||
}
|
||||
const pending = ref<Save>();
|
||||
const authExpired = ref(false);
|
||||
const pickerRequest = ref<{ requestId: string; intent: string }>();
|
||||
function readableError(failure: unknown) {
|
||||
if (failure instanceof StatusError && failure.status === 413)
|
||||
return t("addons.tooLarge");
|
||||
return failure instanceof Error ? failure.message : String(failure);
|
||||
}
|
||||
const pickerRequest = ref<{
|
||||
requestId: string;
|
||||
intent: string;
|
||||
accept: string;
|
||||
}>();
|
||||
const pickerExtensions = computed(() => {
|
||||
const extensions = pickerRequest.value?.accept
|
||||
.toLowerCase()
|
||||
.match(/\.[a-z0-9]+/g);
|
||||
return extensions?.length
|
||||
? [...new Set(extensions)]
|
||||
: pickerRequest.value?.intent === "open"
|
||||
? activeTool.value?.extensions || []
|
||||
: [];
|
||||
});
|
||||
function cancelDialog() {
|
||||
if (saveAs.value) {
|
||||
saveAs.value = false;
|
||||
if (pending.value?.requestId)
|
||||
frame.value?.contentWindow?.postMessage(
|
||||
{ type: id + ":save-error", requestId: pending.value.requestId },
|
||||
window.location.origin
|
||||
);
|
||||
return;
|
||||
}
|
||||
cancelPicker();
|
||||
}
|
||||
function cancelPicker() {
|
||||
if (!pickerRequest.value) return;
|
||||
frame.value?.contentWindow?.postMessage(
|
||||
@@ -167,7 +187,7 @@ function openServerDocument(item: ResourceItem) {
|
||||
!mayLeave()
|
||||
)
|
||||
return;
|
||||
if (item.size > 64 * 1024 * 1024) {
|
||||
if (item.size > 256 * 1024 * 1024) {
|
||||
error.value = t("addons.tooLarge");
|
||||
return;
|
||||
}
|
||||
@@ -186,11 +206,11 @@ async function importServerFile(item: ResourceItem) {
|
||||
const request = pickerRequest.value;
|
||||
if (!request) return;
|
||||
try {
|
||||
if (item.size > 64 * 1024 * 1024) throw new Error(t("addons.tooLarge"));
|
||||
if (item.size > 256 * 1024 * 1024) throw new Error(t("addons.tooLarge"));
|
||||
const bytes = await previewBuffer(
|
||||
getDownloadURL(item, true),
|
||||
controller.signal,
|
||||
64 * 1024 * 1024
|
||||
256 * 1024 * 1024
|
||||
);
|
||||
if (pickerRequest.value !== request || disposed) return;
|
||||
const mime =
|
||||
@@ -217,7 +237,7 @@ async function importServerFile(item: ResourceItem) {
|
||||
frameDirty.value = true;
|
||||
revision++;
|
||||
} catch (failure) {
|
||||
if (!disposed) error.value = String(failure);
|
||||
if (!disposed) error.value = readableError(failure);
|
||||
}
|
||||
}
|
||||
let activityDocument: Document | null = null,
|
||||
@@ -297,7 +317,7 @@ async function persist() {
|
||||
method: "PUT",
|
||||
headers: payload.create
|
||||
? { "If-None-Match": "*" }
|
||||
: { "If-Match": tag },
|
||||
: { "If-Match": payload.tag || tag },
|
||||
body: payload.bytes,
|
||||
signal: controller.signal,
|
||||
},
|
||||
@@ -338,7 +358,9 @@ async function persist() {
|
||||
failure instanceof StatusError &&
|
||||
[409, 412].includes(failure.status || 0)
|
||||
? t("addons.conflict")
|
||||
: t("addons.saveFailed") + " " + String(failure);
|
||||
: failure instanceof StatusError && failure.status === 413
|
||||
? t("addons.tooLarge")
|
||||
: t("addons.saveFailed") + " " + readableError(failure);
|
||||
}
|
||||
} finally {
|
||||
saving.value = false;
|
||||
@@ -346,23 +368,43 @@ async function persist() {
|
||||
queueMicrotask(persist);
|
||||
}
|
||||
}
|
||||
function confirmSaveAs() {
|
||||
async function confirmSaveAs(
|
||||
directory: string,
|
||||
filename: string,
|
||||
existing?: ResourceItem
|
||||
) {
|
||||
if (!pending.value) return;
|
||||
const ext =
|
||||
activeTool.value &&
|
||||
craftSaveExtension(activeTool.value, pending.value.name);
|
||||
if (!ext) return;
|
||||
const name = safeCraftName(newName.value, ext);
|
||||
const name = safeCraftName(filename, ext);
|
||||
if (!name) {
|
||||
error.value = t("addons.invalidName");
|
||||
return;
|
||||
}
|
||||
const payload = pending.value;
|
||||
let destinationTag: string | undefined;
|
||||
if (existing) {
|
||||
if (!window.confirm(t("addons.overwrite", { name }))) return;
|
||||
try {
|
||||
const response = await fetchURL(endpoint(existing.path), {
|
||||
signal: controller.signal,
|
||||
});
|
||||
destinationTag = response.headers.get("ETag") || undefined;
|
||||
await response.body?.cancel();
|
||||
if (!destinationTag || pending.value !== payload || disposed) return;
|
||||
} catch (failure) {
|
||||
error.value = readableError(failure);
|
||||
return;
|
||||
}
|
||||
}
|
||||
pending.value = {
|
||||
...pending.value,
|
||||
...payload,
|
||||
name,
|
||||
path:
|
||||
currentPath.value.slice(0, currentPath.value.lastIndexOf("/") + 1) + name,
|
||||
create: true,
|
||||
path: directory.replace(/\/$/, "") + "/" + name,
|
||||
create: !existing,
|
||||
tag: destinationTag,
|
||||
};
|
||||
saveAs.value = false;
|
||||
persist();
|
||||
@@ -396,6 +438,8 @@ function receive(event: MessageEvent) {
|
||||
pickerRequest.value = {
|
||||
requestId: message.requestId,
|
||||
intent: message.intent === "open" ? "open" : "choose",
|
||||
accept:
|
||||
typeof message.accept === "string" ? message.accept.slice(0, 2048) : "",
|
||||
};
|
||||
} else if (message.type === id + ":ready") {
|
||||
if (opened || !original) return;
|
||||
@@ -417,7 +461,7 @@ function receive(event: MessageEvent) {
|
||||
} else if (message.type === id + ":save") {
|
||||
if (
|
||||
!(message.bytes instanceof ArrayBuffer) ||
|
||||
message.bytes.byteLength > 64 * 1024 * 1024
|
||||
message.bytes.byteLength > 256 * 1024 * 1024
|
||||
) {
|
||||
error.value = t("addons.tooLarge");
|
||||
return;
|
||||
@@ -477,7 +521,7 @@ onMounted(async () => {
|
||||
});
|
||||
tag = response.headers.get("ETag") || "";
|
||||
if (!tag) throw new Error("Missing document version");
|
||||
if (Number(response.headers.get("Content-Length")) > 64 * 1024 * 1024) {
|
||||
if (Number(response.headers.get("Content-Length")) > 256 * 1024 * 1024) {
|
||||
await response.body?.cancel();
|
||||
throw new Error(t("addons.tooLarge"));
|
||||
}
|
||||
@@ -489,7 +533,7 @@ onMounted(async () => {
|
||||
const part = await reader.read();
|
||||
if (part.done) break;
|
||||
length += part.value.length;
|
||||
if (length > 64 * 1024 * 1024) {
|
||||
if (length > 256 * 1024 * 1024) {
|
||||
await reader.cancel();
|
||||
throw new Error(t("addons.tooLarge"));
|
||||
}
|
||||
@@ -511,17 +555,19 @@ onMounted(async () => {
|
||||
addon.build +
|
||||
"/index.html?host=parent" +
|
||||
(id === "lightcraft"
|
||||
? "&store=memory"
|
||||
? "&store=memory&workers=0"
|
||||
: id === "deckcraft"
|
||||
? "&blank"
|
||||
: "") +
|
||||
: id === "soundcraft"
|
||||
? "&empty"
|
||||
: "") +
|
||||
"&author=" +
|
||||
encodeURIComponent(auth.user.profileName || auth.user.username);
|
||||
startup = setTimeout(() => {
|
||||
error.value = t("addons.startFailed");
|
||||
}, 45000);
|
||||
} catch (failure) {
|
||||
if (!disposed) error.value = String(failure);
|
||||
if (!disposed) error.value = readableError(failure);
|
||||
}
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
|
||||
@@ -216,6 +216,12 @@
|
||||
/>
|
||||
<div class="context-menu-separator" v-if="fileStore.selectedCount" />
|
||||
<CreateMenu v-if="authStore.user?.perm.create" />
|
||||
<action
|
||||
v-if="authStore.user?.perm.create"
|
||||
icon="create_new_folder"
|
||||
:label="t('sidebar.newFolder')"
|
||||
show="newDir"
|
||||
/>
|
||||
<action
|
||||
v-if="headerButtons.upload"
|
||||
icon="upload"
|
||||
|
||||
@@ -119,22 +119,18 @@
|
||||
:src="previewUrl"
|
||||
@error="imageFailed = true"
|
||||
/>
|
||||
<audio
|
||||
v-else-if="fileStore.req?.type == 'audio'"
|
||||
ref="player"
|
||||
:src="previewUrl"
|
||||
controls
|
||||
:autoplay="autoPlay"
|
||||
@play="autoPlay = true"
|
||||
></audio>
|
||||
<VideoPlayer
|
||||
v-else-if="fileStore.req?.type == 'video'"
|
||||
<MediaPlayer
|
||||
v-else-if="
|
||||
fileStore.req?.type == 'audio' || fileStore.req?.type == 'video'
|
||||
"
|
||||
ref="player"
|
||||
:source="previewUrl"
|
||||
:audio="fileStore.req?.type == 'audio'"
|
||||
:subtitles="subtitles"
|
||||
:options="videoOptions"
|
||||
:autoplay="autoPlay"
|
||||
@play="autoPlay = true"
|
||||
>
|
||||
</VideoPlayer>
|
||||
</MediaPlayer>
|
||||
<div
|
||||
v-else-if="fileStore.req?.type == 'blob' || imageFailed"
|
||||
class="info"
|
||||
@@ -196,7 +192,7 @@ import { throttle } from "lodash-es";
|
||||
import HeaderBar from "@/components/header/HeaderBar.vue";
|
||||
import Action from "@/components/header/Action.vue";
|
||||
import ExtendedImage from "@/components/files/ExtendedImage.vue";
|
||||
import VideoPlayer from "@/components/files/VideoPlayer.vue";
|
||||
import MediaPlayer from "@/components/files/MediaPlayer.vue";
|
||||
import CsvViewer from "@/components/files/CsvViewer.vue";
|
||||
import ResourcePreview from "@/components/files/ResourcePreview.vue";
|
||||
import FileIcon from "@/components/files/FileIcon.vue";
|
||||
@@ -286,7 +282,7 @@ const nextRaw = ref<string>("");
|
||||
const csvContent = ref<ArrayBuffer | string>("");
|
||||
const csvError = ref<string>("");
|
||||
|
||||
const player = ref<HTMLVideoElement | HTMLAudioElement | null>(null);
|
||||
const player = ref<{ paused?: boolean; ended?: boolean } | null>(null);
|
||||
|
||||
const $showError = inject<IToastError>("$showError")!;
|
||||
|
||||
@@ -364,10 +360,6 @@ const subtitles = computed(() => {
|
||||
return [];
|
||||
});
|
||||
|
||||
const videoOptions = computed(() => {
|
||||
return { autoplay: autoPlay.value };
|
||||
});
|
||||
|
||||
watch(route, () => {
|
||||
updatePreview();
|
||||
toggleNavigation();
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
><AppIcon name="chevron_right" />
|
||||
</button>
|
||||
<Addons />
|
||||
<MediaStatus />
|
||||
<section class="card settings-section">
|
||||
<h2><AppIcon name="archive" />{{ t("settings.downloadsTitle") }}</h2>
|
||||
<label class="settings-field"
|
||||
@@ -133,6 +134,7 @@
|
||||
import { useRoute } from "vue-router";
|
||||
import { settings as api } from "@/api";
|
||||
import Addons from "@/components/settings/Addons.vue";
|
||||
import MediaStatus from "@/components/settings/MediaStatus.vue";
|
||||
import { StatusError } from "@/api/utils";
|
||||
import Rules from "@/components/settings/Rules.vue";
|
||||
import Themes from "@/components/settings/Themes.vue";
|
||||
|
||||
@@ -48,6 +48,13 @@
|
||||
><span>{{ t("settings.redirectAfterCopyMove") }}</span
|
||||
><input type="checkbox" v-model="redirectAfterCopyMove"
|
||||
/></label>
|
||||
<button
|
||||
type="button"
|
||||
class="button button--flat"
|
||||
@click="autoOpenVisible = true"
|
||||
>
|
||||
{{ t("preferences.autoOpen") }}
|
||||
</button>
|
||||
</section>
|
||||
<section v-if="DICOM_3D_ENABLED" class="card settings-section">
|
||||
<h2><AppIcon name="tune" />{{ t("preferences.dicom3D") }}</h2>
|
||||
@@ -99,6 +106,11 @@
|
||||
/></label>
|
||||
</section>
|
||||
</div>
|
||||
<AutoOpenSettings
|
||||
v-if="autoOpenVisible"
|
||||
v-model="autoOpen"
|
||||
@close="autoOpenVisible = false"
|
||||
/>
|
||||
<div class="settings-save">
|
||||
<button class="button" type="submit" :disabled="saving">
|
||||
{{ t("buttons.save") }}
|
||||
@@ -112,6 +124,7 @@ import { useLayoutStore } from "@/stores/layout";
|
||||
import { users as api } from "@/api";
|
||||
import Languages from "@/components/settings/Languages.vue";
|
||||
import AccountAvatar from "@/components/AccountAvatar.vue";
|
||||
import AutoOpenSettings from "@/components/settings/AutoOpenSettings.vue";
|
||||
import { baseURL, noAuth } from "@/utils/constants";
|
||||
import { getTheme, getMediaPreference, setTheme } from "@/utils/theme";
|
||||
import { dicomPreferences } from "@/utils/dicom-quality";
|
||||
@@ -136,6 +149,8 @@ const locale = ref<string>("");
|
||||
const selectedTheme = ref<UserTheme>(getTheme() || getMediaPreference());
|
||||
const saving = ref(false);
|
||||
const dicom3D = ref(dicomPreferences());
|
||||
const autoOpenVisible = ref(false),
|
||||
autoOpen = ref<Record<string, string>>({});
|
||||
|
||||
onMounted(async () => {
|
||||
layoutStore.loading = true;
|
||||
@@ -150,6 +165,7 @@ onMounted(async () => {
|
||||
redirectAfterCopyMove.value = authStore.user.redirectAfterCopyMove;
|
||||
dateFormat.value = authStore.user.dateFormat;
|
||||
dicom3D.value = dicomPreferences(authStore.user.dicom3D);
|
||||
autoOpen.value = { ...authStore.user.autoOpen };
|
||||
layoutStore.loading = false;
|
||||
|
||||
return true;
|
||||
@@ -173,6 +189,7 @@ const updateSettings = async (event: Event) => {
|
||||
redirectAfterCopyMove: redirectAfterCopyMove.value,
|
||||
dateFormat: dateFormat.value,
|
||||
dicom3D: { ...dicom3D.value },
|
||||
autoOpen: { ...autoOpen.value },
|
||||
};
|
||||
|
||||
await api.update(data, [
|
||||
@@ -183,6 +200,7 @@ const updateSettings = async (event: Event) => {
|
||||
"redirectAfterCopyMove",
|
||||
"dateFormat",
|
||||
"dicom3D",
|
||||
"autoOpen",
|
||||
]);
|
||||
authStore.updateUser(data);
|
||||
$showSuccess(t("settings.settingsUpdated"));
|
||||
|
||||
@@ -93,20 +93,26 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
if !ok {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
bridge := needsOfficeBridge(id) && name == "filebrowser-bridge.js"
|
||||
bridge := needsOfficeBridge(id, vars["build"]) && name == "filebrowser-bridge.js"
|
||||
pickerBridge := name == "filebrowser-picker.js"
|
||||
lookup := name
|
||||
if bridge || pickerBridge {
|
||||
lookup = "index.html"
|
||||
}
|
||||
file, err := manager.Open(id, vars["build"], lookup)
|
||||
// PhotoCraft's split WASM release keeps snippets at the bundle root,
|
||||
// while app/photocraft-web.js imports them relative to app/.
|
||||
if err != nil && id == "photocraft" && strings.HasPrefix(lookup, "app/snippets/") {
|
||||
lookup = strings.TrimPrefix(lookup, "app/")
|
||||
file, err = manager.Open(id, vars["build"], lookup)
|
||||
}
|
||||
if err != nil {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
defer file.Close()
|
||||
adaptIndex := name == "index.html" && r.URL.Query().Get("host") == "parent"
|
||||
if !bridge && !pickerBridge && !adaptIndex && acceptsAddonGzip(r.Header.Get("Accept-Encoding")) {
|
||||
if compressed, e := manager.Open(id, vars["build"], name+".gz"); e == nil {
|
||||
if compressed, e := manager.Open(id, vars["build"], lookup+".gz"); e == nil {
|
||||
file.Close()
|
||||
file = compressed
|
||||
defer compressed.Close()
|
||||
@@ -122,7 +128,7 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Cache-Control", "private, max-age=86400")
|
||||
// Only installed, checksum-verified vendor pages get WASM and framing permissions.
|
||||
w.Header().Set("Content-Security-Policy", `default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; worker-src 'self' blob:; media-src 'self' blob:; frame-src 'none'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'`)
|
||||
w.Header().Set("Content-Security-Policy", `default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' blob:; worker-src 'self' blob:; media-src 'self' blob:; frame-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'`)
|
||||
if pickerBridge {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.ServeContent(w, r, name, info.ModTime(), bytes.NewReader(craftPicker))
|
||||
@@ -149,7 +155,7 @@ func addonStaticHandler(manager *addons.Manager) handleFunc {
|
||||
return http.StatusUnprocessableEntity, nil
|
||||
}
|
||||
scripts := `<script src="./filebrowser-picker.js"></script>`
|
||||
if needsOfficeBridge(id) {
|
||||
if needsOfficeBridge(id, vars["build"]) {
|
||||
scripts += `<script src="./filebrowser-bridge.js"></script>`
|
||||
}
|
||||
content = bytes.Replace(content, marker, []byte(scripts+`</head>`), 1)
|
||||
|
||||
@@ -12,6 +12,7 @@ type userInfo struct {
|
||||
Locale string `json:"locale"`
|
||||
ViewMode users.ViewMode `json:"viewMode"`
|
||||
SingleClick bool `json:"singleClick"`
|
||||
AutoOpen map[string]string `json:"autoOpen"`
|
||||
RedirectAfterCopyMove bool `json:"redirectAfterCopyMove"`
|
||||
Perm users.Permissions `json:"perm"`
|
||||
Commands []string `json:"commands"`
|
||||
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
const maxCraftDocument = 64 << 20
|
||||
const maxCraftDocument = 256 << 20
|
||||
|
||||
// Normal uploads/moves take a shared lock; editor commit/read takes the exclusive
|
||||
// lock so the version check and replacement cannot race our own file API.
|
||||
@@ -33,8 +33,11 @@ func readCraftFile(d *data, name string) ([]byte, os.FileInfo, error) {
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() > maxCraftDocument {
|
||||
return nil, nil, errors.New("unsupported document size or type")
|
||||
if !info.Mode().IsRegular() {
|
||||
return nil, nil, os.ErrInvalid
|
||||
}
|
||||
if info.Size() > maxCraftDocument {
|
||||
return nil, nil, errCraftDocumentSize
|
||||
}
|
||||
f, err := d.user.Fs.Open(name)
|
||||
if err != nil {
|
||||
@@ -43,10 +46,13 @@ func readCraftFile(d *data, name string) ([]byte, os.FileInfo, error) {
|
||||
defer f.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(f, maxCraftDocument+1))
|
||||
if len(data) > maxCraftDocument {
|
||||
return nil, nil, errors.New("document exceeds 64 MiB")
|
||||
return nil, nil, errCraftDocumentSize
|
||||
}
|
||||
return data, info, err
|
||||
}
|
||||
|
||||
var errCraftDocumentSize = errors.New("file is too large: editors support files up to 256 MiB")
|
||||
|
||||
func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
|
||||
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
id := mux.Vars(r)["addon"]
|
||||
@@ -54,7 +60,8 @@ func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
|
||||
if !ok {
|
||||
return http.StatusNotFound, nil
|
||||
}
|
||||
if !addonEnabled(d, id) || manager.Status(id).Build == "" || !d.user.Perm.Download || !d.user.Perm.Modify {
|
||||
status := manager.Status(id)
|
||||
if !addonEnabled(d, id) || status.Build == "" || addons.CompatibilityIssue(id, status.Build) != "" || !d.user.Perm.Download || !d.user.Perm.Modify {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
requested := r.URL.Query().Get("path")
|
||||
@@ -62,7 +69,7 @@ func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
extension := strings.ToLower(path.Ext(requested))
|
||||
if (r.Method == "PUT" && !tool.CanSave(extension)) || (r.Method != "PUT" && !tool.CanOpen(extension)) {
|
||||
if (r.Method == "PUT" && !tool.CanSave(extension)) || (r.Method == "POST" && !tool.CanOpen(extension)) || (r.Method == "GET" && !tool.CanOpen(extension) && !tool.CanSave(extension)) {
|
||||
return http.StatusUnsupportedMediaType, nil
|
||||
}
|
||||
if !d.Check(requested) {
|
||||
@@ -79,6 +86,12 @@ func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
|
||||
data, _, err := readCraftFile(d, requested)
|
||||
craftMutationMu.Unlock()
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrInvalid) {
|
||||
return http.StatusBadRequest, err
|
||||
}
|
||||
if errors.Is(err, errCraftDocumentSize) {
|
||||
return http.StatusRequestEntityTooLarge, err
|
||||
}
|
||||
return errToStatus(err), err
|
||||
}
|
||||
if err = validateCraftDocument(extension, data); err != nil {
|
||||
@@ -117,14 +130,17 @@ func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
|
||||
defer d.user.Fs.Remove(tempName)
|
||||
n, err := io.Copy(temp, io.LimitReader(body, maxCraftDocument+1))
|
||||
if err == nil && n > maxCraftDocument {
|
||||
err = errors.New("document exceeds 64 MiB")
|
||||
err = errCraftDocumentSize
|
||||
}
|
||||
if err == nil {
|
||||
err = temp.Sync()
|
||||
}
|
||||
if err != nil {
|
||||
temp.Close()
|
||||
return http.StatusRequestEntityTooLarge, err
|
||||
if errors.Is(err, errCraftDocumentSize) {
|
||||
return http.StatusRequestEntityTooLarge, err
|
||||
}
|
||||
return errToStatus(err), err
|
||||
}
|
||||
if _, err = temp.Seek(0, io.SeekStart); err != nil {
|
||||
temp.Close()
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
package fbhttp
|
||||
|
||||
import _ "embed"
|
||||
import "github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
import (
|
||||
_ "embed"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
)
|
||||
|
||||
//go:embed craft_bridge.js
|
||||
var officeBridge []byte
|
||||
@@ -18,7 +23,19 @@ func deckcraftNeedsCompat(id, build string) bool {
|
||||
return id == "deckcraft" && build == "v0.9.0-38076027b9c1"
|
||||
}
|
||||
|
||||
func needsOfficeBridge(id string) bool {
|
||||
func needsOfficeBridge(id string, build ...string) bool {
|
||||
// WordCraft 0.14 added the official parent protocol. Injecting the drop
|
||||
// adapter too announces readiness before Rust is listening and loses the file.
|
||||
if id == "wordcraft" && len(build) > 0 {
|
||||
parts := strings.Split(strings.TrimPrefix(build[0], "v"), ".")
|
||||
if len(parts) >= 2 {
|
||||
major, _ := strconv.Atoi(parts[0])
|
||||
minor, _ := strconv.Atoi(parts[1])
|
||||
if major > 0 || minor >= 14 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
tool, ok := addons.Find(id)
|
||||
return ok && tool.Bridge == "drop"
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
if (!config || config.id !== id || parent === window || new URLSearchParams(location.search).get("host") !== "parent") return;
|
||||
const accepts = (name, list) => typeof name === "string" && list.some(extension => name.toLowerCase().endsWith(extension));
|
||||
const origin = location.origin;
|
||||
const limit = 64 * 1024 * 1024;
|
||||
const limit = 256 * 1024 * 1024;
|
||||
const jobs = new Map();
|
||||
const blobs = new Map();
|
||||
let opened = false, dirty = false, revision = 0, sequence = 0;
|
||||
@@ -19,8 +19,8 @@
|
||||
const createURL = URL.createObjectURL.bind(URL), revokeURL = URL.revokeObjectURL.bind(URL);
|
||||
URL.createObjectURL = blob => { const url = createURL(blob); blobs.set(url, blob); return url; };
|
||||
URL.revokeObjectURL = url => { blobs.delete(url); revokeURL(url); };
|
||||
async function save(name, blob) {
|
||||
if (blob.size > limit) throw new Error("Document exceeds 64 MiB");
|
||||
async function save(name, blob, saveAs = false) {
|
||||
if (blob.size > limit) throw new Error("Document exceeds 256 MiB");
|
||||
// Bound in-flight copies even if the user repeatedly clicks Save.
|
||||
if (jobs.size >= 2) throw new Error("A save is already pending");
|
||||
const requestId = String(++sequence), savedRevision = revision;
|
||||
@@ -29,7 +29,7 @@
|
||||
return new Promise((resolve, reject) => {
|
||||
jobs.set(requestId, { resolve, reject, revision: savedRevision });
|
||||
blob.arrayBuffer().then(bytes => {
|
||||
send("save", { name, bytes, requestId }, [bytes]);
|
||||
send("save", { name, bytes, requestId, saveAs }, [bytes]);
|
||||
}).catch(error => { jobs.delete(requestId); reject(error); });
|
||||
});
|
||||
}
|
||||
@@ -51,17 +51,36 @@
|
||||
}
|
||||
return {
|
||||
kind: "file", name,
|
||||
queryPermission: async () => "granted",
|
||||
requestPermission: async () => "granted",
|
||||
async createWritable() {
|
||||
let chunks = [], size = 0;
|
||||
let content = new Blob(), position = 0;
|
||||
const offset = value => {
|
||||
if (!Number.isSafeInteger(value) || value < 0 || value > limit) throw new RangeError("Document exceeds 256 MiB or invalid position");
|
||||
return value;
|
||||
};
|
||||
const seek = async value => { position = offset(value); };
|
||||
const truncate = async value => {
|
||||
const size = offset(value);
|
||||
content = size <= content.size ? content.slice(0, size) : new Blob([content, new Uint8Array(size - content.size)]);
|
||||
position = Math.min(position, size);
|
||||
};
|
||||
return {
|
||||
async write(data) {
|
||||
// This build writes sequential Uint8Array chunks, never random-access data.
|
||||
if (data && typeof data === "object" && ["write", "seek", "truncate"].includes(data.type)) {
|
||||
if (data.type === "seek") return seek(data.position);
|
||||
if (data.type === "truncate") return truncate(data.size);
|
||||
if (data.position !== undefined) await seek(data.position);
|
||||
data = data.data;
|
||||
}
|
||||
const chunk = new Blob([data]);
|
||||
if (size + chunk.size > limit) throw new Error("Document exceeds 64 MiB");
|
||||
size += chunk.size; chunks.push(chunk);
|
||||
if (position + chunk.size > limit) throw new Error("Document exceeds 256 MiB");
|
||||
content = new Blob([content.slice(0, position), ...(position > content.size ? [new Uint8Array(position - content.size)] : []), chunk, content.slice(position + chunk.size)]);
|
||||
position += chunk.size;
|
||||
},
|
||||
async close() { const blob = new Blob(chunks); chunks = []; await save(name, blob); },
|
||||
async abort() { chunks = []; }
|
||||
seek, truncate,
|
||||
async close() { const blob = content; content = new Blob(); await save(name, blob, true); },
|
||||
async abort() { content = new Blob(); }
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -99,19 +118,21 @@
|
||||
window.addEventListener("pointerdown", event => { if (opened && event.isTrusted) markDirty(); }, true);
|
||||
window.addEventListener("beforeunload", event => { if (dirty || jobs.size) event.preventDefault(); });
|
||||
let announced = false;
|
||||
let domReady = document.readyState !== "loading";
|
||||
const reportFailure = error => send("failed", { error: String(error?.message || error || "Editor failed to start") });
|
||||
window.addEventListener("error", event => { if (!announced) reportFailure(event.error || event.message); });
|
||||
window.addEventListener("unhandledrejection", event => { if (!announced) reportFailure(event.reason); });
|
||||
function ready() {
|
||||
if (announced) return;
|
||||
if (announced || !domReady) return;
|
||||
const loading = document.getElementById(id + "_loading");
|
||||
if (loading) {
|
||||
if (loading && loading.textContent.trim() && !loading.hidden && loading.style.display !== "none" && (!window.getComputedStyle || getComputedStyle(loading).display !== "none")) {
|
||||
if (/failed to start/i.test(loading.textContent || "")) { send("failed", { error: loading.textContent }); observer.disconnect(); }
|
||||
return;
|
||||
}
|
||||
if (document.getElementById(id + "_canvas")) { announced = true; observer.disconnect(); send("ready"); }
|
||||
}
|
||||
const observer = new MutationObserver(ready);
|
||||
observer.observe(document.documentElement, { childList: true, subtree: true, characterData: true });
|
||||
window.addEventListener("DOMContentLoaded", () => { domReady = true; ready(); }, { once: true });
|
||||
observer.observe(document.documentElement, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ["style", "class", "hidden"] });
|
||||
ready();
|
||||
})();
|
||||
@@ -16,7 +16,7 @@
|
||||
const message = event.data, job = jobs.get(message.requestId); if (!job) return;
|
||||
jobs.delete(message.requestId);
|
||||
if (!Array.isArray(message.files)) { job.reject(new DOMException("Selection cancelled", "AbortError")); return; }
|
||||
const files = message.files.filter(f => typeof f.name === "string" && f.bytes instanceof ArrayBuffer && f.bytes.byteLength <= 64 * 1024 * 1024)
|
||||
const files = message.files.filter(f => typeof f.name === "string" && f.bytes instanceof ArrayBuffer && f.bytes.byteLength <= 256 * 1024 * 1024)
|
||||
.map(f => new File([f.bytes], f.name, { type: typeof f.mime === "string" ? f.mime : "" }));
|
||||
if (!files.length) job.reject(new DOMException("No file selected", "AbortError")); else job.resolve(files);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func TestLargePSDAndOversizeResponse(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
manager := installedTestManager(t)
|
||||
key := []byte("large-psd-test")
|
||||
perm := users.Permissions{Download: true, Modify: true}
|
||||
store := scopedUserStorage(t, root, perm, key)
|
||||
handler := handle(craftDocumentHandler(manager, nil), "", store, &settings.Server{})
|
||||
for _, size := range []int64{149355372, maxCraftDocument + 1} {
|
||||
file, err := os.Create(filepath.Join(root, "large.psd"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
header := make([]byte, 26)
|
||||
copy(header, "8BPS")
|
||||
binary.BigEndian.PutUint16(header[4:6], 1)
|
||||
binary.BigEndian.PutUint32(header[14:18], 2528)
|
||||
binary.BigEndian.PutUint32(header[18:22], 1696)
|
||||
file.Write(header)
|
||||
file.Truncate(size)
|
||||
file.Close()
|
||||
r := httptest.NewRequest("GET", "/api/craft/photocraft/document?path="+url.QueryEscape("/large.psd"), nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"addon": "photocraft"})
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, authorizeTestRequest(r, signToken(t, perm, key)))
|
||||
if size <= maxCraftDocument {
|
||||
if rec.Code != 200 || int64(rec.Body.Len()) != size || rec.Header().Get("ETag") == "" {
|
||||
t.Fatalf("large PSD: status %d, size %d", rec.Code, rec.Body.Len())
|
||||
}
|
||||
} else if rec.Code != 413 {
|
||||
t.Fatalf("oversize must be 413, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPhotoCraftSplitModuleAndPrintPolicy(t *testing.T) {
|
||||
manager := installedTestManager(t)
|
||||
key := []byte("split-module-test")
|
||||
perm := users.Permissions{Download: true, Modify: true}
|
||||
store := scopedUserStorage(t, t.TempDir(), perm, key)
|
||||
dir := filepath.Join(manager.Root, "photocraft", "versions", "test-123", "snippets", "eframe-test")
|
||||
os.MkdirAll(dir, 0700)
|
||||
os.WriteFile(filepath.Join(dir, "inline0.js"), []byte("export const ready = true;"), 0600)
|
||||
handler := handle(addonStaticHandler(manager), "", store, &settings.Server{})
|
||||
r := httptest.NewRequest("GET", "/addons/photocraft/test-123/app/snippets/eframe-test/inline0.js", nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"addon": "photocraft", "build": "test-123", "asset": "app/snippets/eframe-test/inline0.js"})
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, authorizeTestRequest(r, signToken(t, perm, key)))
|
||||
if rec.Code != 200 || !bytes.Contains(rec.Body.Bytes(), []byte("export const ready")) {
|
||||
t.Fatalf("split module: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if !strings.Contains(rec.Header().Get("Content-Security-Policy"), "frame-src 'self' blob:") {
|
||||
t.Fatal("PDF print iframe blocked")
|
||||
}
|
||||
if needsOfficeBridge("wordcraft", "v0.14.0-afbb7fb0d7c0") {
|
||||
t.Fatal("native WordCraft must not receive duplicate drop bridge")
|
||||
}
|
||||
if !needsOfficeBridge("wordcraft", "v0.9.0-710d2f4dd95a") {
|
||||
t.Fatal("legacy WordCraft still needs adapter")
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,8 @@ func NewHandler(
|
||||
r.Handle("/addons/{addon}/{build}/{asset:.*}", monkey(addonStaticHandler(addonManager), "")).Methods("GET", "HEAD")
|
||||
|
||||
api.PathPrefix("/raw").Handler(monkey(rawHandler, "/api/raw")).Methods("GET")
|
||||
api.Handle("/media/play", monkey(mediaHandler, "")).Methods("GET")
|
||||
api.Handle("/media/status", monkey(mediaStatusHandler, "")).Methods("GET")
|
||||
api.PathPrefix("/preview/{size}/{path:.*}").
|
||||
Handler(monkey(previewHandler(imgSvc, fileCache, server.EnableThumbnails, server.ResizePreview), "/api/preview")).Methods("GET")
|
||||
api.PathPrefix("/search").Handler(monkey(searchHandler, "/api/search")).Methods("GET")
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var mediaStreams = make(chan struct{}, 2)
|
||||
|
||||
var mediaStatusHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
status := struct {
|
||||
Available bool `json:"available"`
|
||||
Version string `json:"version,omitempty"`
|
||||
}{}
|
||||
binary, err := exec.LookPath("ffmpeg")
|
||||
if err == nil {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
output, runErr := exec.CommandContext(ctx, binary, "-version").Output()
|
||||
if runErr == nil && strings.HasPrefix(string(output), "ffmpeg version ") {
|
||||
status.Available = true
|
||||
status.Version = strings.SplitN(string(output), "\n", 2)[0]
|
||||
}
|
||||
}
|
||||
return renderJSON(w, r, status)
|
||||
})
|
||||
|
||||
// The browser uses the original file first. This optional fallback converts
|
||||
// codecs the browser cannot decode, without changing or copying the original.
|
||||
var mediaHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
if !d.user.Perm.Download {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
name := r.URL.Query().Get("path")
|
||||
if name == "" || !strings.HasPrefix(name, "/") || path.Clean(name) != name || strings.ContainsAny(name, "\\\x00") {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
if !d.Check(name) {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
ext := strings.ToLower(path.Ext(name))
|
||||
if !strings.Contains("|.mp4|.m4v|.mkv|.webm|.mov|.avi|.wmv|.mpg|.mpeg|.ts|.mts|.m2ts|.flv|.ogv|.mp3|.wav|.ogg|.oga|.flac|.m4a|.aac|.opus|.aif|.aiff|.wma|.ac3|.dts|", "|"+ext+"|") {
|
||||
return http.StatusUnsupportedMediaType, nil
|
||||
}
|
||||
input, err := d.user.Fs.Open(name)
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
defer input.Close()
|
||||
info, err := input.Stat()
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
binary, err := exec.LookPath("ffmpeg")
|
||||
if err != nil {
|
||||
return http.StatusServiceUnavailable, errors.New("install FFmpeg on the server to play this codec")
|
||||
}
|
||||
select {
|
||||
case mediaStreams <- struct{}{}:
|
||||
defer func() { <-mediaStreams }()
|
||||
default:
|
||||
return http.StatusTooManyRequests, nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Hour)
|
||||
defer cancel()
|
||||
// Give FFmpeg seekable HTTP access to this already authorized, open handle.
|
||||
// No filesystem path, credentials or caller-controlled URL enters its args.
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
secret := make([]byte, 32)
|
||||
if _, err = rand.Read(secret); err != nil {
|
||||
listener.Close()
|
||||
return 500, err
|
||||
}
|
||||
token := "/" + hex.EncodeToString(secret)
|
||||
var readMu sync.Mutex
|
||||
relay := &http.Server{ReadHeaderTimeout: 5 * time.Second, Handler: http.HandlerFunc(func(out http.ResponseWriter, request *http.Request) {
|
||||
if request.URL.Path != token || (request.Method != "GET" && request.Method != "HEAD") {
|
||||
http.NotFound(out, request)
|
||||
return
|
||||
}
|
||||
// ServeContent seeks the shared handle; FFmpeg issues sequential range requests.
|
||||
readMu.Lock()
|
||||
defer readMu.Unlock()
|
||||
http.ServeContent(out, request, info.Name(), info.ModTime(), input)
|
||||
})}
|
||||
go relay.Serve(listener) //nolint:errcheck
|
||||
defer relay.Close()
|
||||
args := []string{"-nostdin", "-hide_banner", "-loglevel", "error", "-protocol_whitelist", "http,tcp", "-format_whitelist", "mov,matroska,webm,avi,asf,mpeg,mpegts,flv,ogg,wav,mp3,flac,aac,aiff,ac3,eac3,dts", "-threads", "2", "-i", "http://" + listener.Addr().String() + token}
|
||||
if r.URL.Query().Get("audio") == "true" {
|
||||
args = append(args, "-map", "0:a:0", "-vn", "-c:a", "libmp3lame", "-b:a", "192k", "-f", "mp3", "pipe:1")
|
||||
w.Header().Set("Content-Type", "audio/mpeg")
|
||||
} else {
|
||||
args = append(args, "-map", "0:v:0", "-map", "0:a:0?", "-c:v", "libx264", "-threads", "2", "-preset", "veryfast", "-crf", "23", "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2", "-pix_fmt", "yuv420p", "-c:a", "aac", "-movflags", "frag_keyframe+empty_moov+default_base_moof", "-f", "mp4", "pipe:1")
|
||||
w.Header().Set("Content-Type", "video/mp4")
|
||||
}
|
||||
command := exec.CommandContext(ctx, binary, args...)
|
||||
stream, err := command.StdoutPipe()
|
||||
if err != nil {
|
||||
return 500, err
|
||||
}
|
||||
if err = command.Start(); err != nil {
|
||||
return http.StatusServiceUnavailable, err
|
||||
}
|
||||
defer command.Wait() //nolint:errcheck
|
||||
// Do not report success when FFmpeg rejects the container or codec.
|
||||
first := make([]byte, 32*1024)
|
||||
n, err := stream.Read(first)
|
||||
if n == 0 {
|
||||
return http.StatusUnsupportedMediaType, errors.New("FFmpeg could not decode this media file")
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
if _, err = w.Write(first[:n]); err == nil {
|
||||
_, err = io.Copy(w, stream)
|
||||
}
|
||||
if err != nil {
|
||||
cancel()
|
||||
}
|
||||
return 0, err
|
||||
})
|
||||
@@ -0,0 +1,116 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/settings"
|
||||
"github.com/filebrowser/filebrowser/v2/users"
|
||||
)
|
||||
|
||||
func TestMediaStatusIsAdminOnlyAndChecksExecutable(t *testing.T) {
|
||||
perm := users.Permissions{Admin: true}
|
||||
key := []byte("media-status-test")
|
||||
store := scopedUserStorage(t, t.TempDir(), perm, key)
|
||||
handler := handle(mediaStatusHandler, "", store, &settings.Server{})
|
||||
request := func(admin bool) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("GET", "/api/media/status", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, authorizeTestRequest(r, signToken(t, users.Permissions{Admin: admin}, key)))
|
||||
return rec
|
||||
}
|
||||
if rec := request(false); rec.Code != 403 {
|
||||
t.Fatalf("nonadmin: %d", rec.Code)
|
||||
}
|
||||
_, ffmpegErr := exec.LookPath("ffmpeg")
|
||||
rec := request(true)
|
||||
var status struct {
|
||||
Available bool `json:"available"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &status) != nil {
|
||||
t.Fatalf("status: %d", rec.Code)
|
||||
}
|
||||
if ffmpegErr == nil && (!status.Available || status.Version == "") {
|
||||
t.Fatal("installed FFmpeg was not detected")
|
||||
}
|
||||
t.Setenv("PATH", t.TempDir())
|
||||
rec = request(true)
|
||||
if json.Unmarshal(rec.Body.Bytes(), &status) != nil || status.Available {
|
||||
t.Fatal("missing FFmpeg reported as available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaPermissionsAndConversion(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
key := []byte("media-test")
|
||||
perm := users.Permissions{Download: true}
|
||||
store := scopedUserStorage(t, root, perm, key)
|
||||
handler := handle(mediaHandler, "", store, &settings.Server{})
|
||||
request := func(target string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("GET", target, nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, authorizeTestRequest(r, signToken(t, perm, key)))
|
||||
return rec
|
||||
}
|
||||
for target, status := range map[string]int{
|
||||
"/api/media/play?path=/../private.wav": 400,
|
||||
"/api/media/play?path=/playlist.m3u": 415,
|
||||
"/api/media/play?path=https://example.com/test.mp3": 400,
|
||||
"/api/media/play?path=/missing.wav": 404,
|
||||
} {
|
||||
if rec := request(target); rec.Code != status {
|
||||
t.Fatalf("%s: want %d, got %d", target, status, rec.Code)
|
||||
}
|
||||
}
|
||||
wave := make([]byte, 44+9600)
|
||||
copy(wave, "RIFF")
|
||||
binary.LittleEndian.PutUint32(wave[4:], uint32(len(wave)-8))
|
||||
copy(wave[8:], "WAVEfmt ")
|
||||
binary.LittleEndian.PutUint32(wave[16:], 16)
|
||||
binary.LittleEndian.PutUint16(wave[20:], 1)
|
||||
binary.LittleEndian.PutUint16(wave[22:], 1)
|
||||
binary.LittleEndian.PutUint32(wave[24:], 48000)
|
||||
binary.LittleEndian.PutUint32(wave[28:], 96000)
|
||||
binary.LittleEndian.PutUint16(wave[32:], 2)
|
||||
binary.LittleEndian.PutUint16(wave[34:], 16)
|
||||
copy(wave[36:], "data")
|
||||
binary.LittleEndian.PutUint32(wave[40:], 9600)
|
||||
os.WriteFile(filepath.Join(root, "audio.wav"), wave, 0600)
|
||||
user, _ := store.Users.Get("", false, uint(1))
|
||||
user.Perm.Download = false
|
||||
store.Users.Save(user)
|
||||
if rec := request("/api/media/play?path=/audio.wav&audio=true"); rec.Code != 403 {
|
||||
t.Fatalf("download denied: %d", rec.Code)
|
||||
}
|
||||
user.Perm.Download = true
|
||||
store.Users.Save(user)
|
||||
if _, err := exec.LookPath("ffmpeg"); err != nil {
|
||||
if rec := request("/api/media/play?path=/audio.wav&audio=true"); rec.Code != 503 {
|
||||
t.Fatalf("missing FFmpeg: %d", rec.Code)
|
||||
}
|
||||
return
|
||||
}
|
||||
rec := request("/api/media/play?path=/audio.wav&audio=true")
|
||||
if rec.Code != 200 || rec.Body.Len() < 100 || rec.Header().Get("Content-Type") != "audio/mpeg" {
|
||||
t.Fatalf("audio transcode: %d, %d bytes, %s", rec.Code, rec.Body.Len(), rec.Body.String())
|
||||
}
|
||||
original, _ := os.ReadFile(filepath.Join(root, "audio.wav"))
|
||||
if !bytes.Equal(original, wave) {
|
||||
t.Fatal("original changed")
|
||||
}
|
||||
video := filepath.Join(root, "video.avi")
|
||||
if output, err := exec.Command("ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=size=64x64:rate=10:color=blue", "-t", "0.2", "-c:v", "mpeg4", video).CombinedOutput(); err != nil {
|
||||
t.Fatalf("fixture: %v %s", err, output)
|
||||
}
|
||||
rec = request("/api/media/play?path=/video.avi")
|
||||
if rec.Code != 200 || !bytes.Contains(rec.Body.Bytes(), []byte("ftyp")) || rec.Header().Get("Content-Type") != "video/mp4" {
|
||||
t.Fatalf("video transcode: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -225,5 +225,5 @@ func applySSOIdentity(u *users.User, i sessionIdentity) {
|
||||
u.DisplayName = i.Name
|
||||
}
|
||||
func ssoUserInfo(u *users.User) userInfo {
|
||||
return userInfo{ID: u.ID, Username: u.DisplayName, ProfileName: u.ProfileName, Email: u.Email, Locale: u.Locale, ViewMode: u.ViewMode, SingleClick: u.SingleClick, RedirectAfterCopyMove: u.RedirectAfterCopyMove, Perm: u.Perm, Commands: []string{}, LockPassword: true, HideDotfiles: u.HideDotfiles, HidePreviews: u.HidePreviews, Dicom3D: u.Dicom3D.Normalized(), DateFormat: u.DateFormat, AceEditorTheme: u.AceEditorTheme}
|
||||
return userInfo{ID: u.ID, Username: u.DisplayName, ProfileName: u.ProfileName, Email: u.Email, Locale: u.Locale, ViewMode: u.ViewMode, SingleClick: u.SingleClick, AutoOpen: u.AutoOpen, RedirectAfterCopyMove: u.RedirectAfterCopyMove, Perm: u.Perm, Commands: []string{}, LockPassword: true, HideDotfiles: u.HideDotfiles, HidePreviews: u.HidePreviews, Dicom3D: u.Dicom3D.Normalized(), DateFormat: u.DateFormat, AceEditorTheme: u.AceEditorTheme}
|
||||
}
|
||||
@@ -130,7 +130,7 @@ var userPutHandler = withSelfOrAdmin(func(w http.ResponseWriter, r *http.Request
|
||||
if req.Data == nil || req.Data.ID != d.raw.(uint) || len(req.Which) == 0 || req.Data.Password != "" {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
allowed := map[string]string{"scope": "Scope", "perm": "Perm", "rules": "Rules", "locale": "Locale", "viewmode": "ViewMode", "singleclick": "SingleClick", "redirectaftercopymove": "RedirectAfterCopyMove", "hidedotfiles": "HideDotfiles", "hidepreviews": "HidePreviews", "dicom3d": "Dicom3D", "dateformat": "DateFormat", "aceeditortheme": "AceEditorTheme", "sorting": "Sorting"}
|
||||
allowed := map[string]string{"autoopen": "AutoOpen", "scope": "Scope", "perm": "Perm", "rules": "Rules", "locale": "Locale", "viewmode": "ViewMode", "singleclick": "SingleClick", "redirectaftercopymove": "RedirectAfterCopyMove", "hidedotfiles": "HideDotfiles", "hidepreviews": "HidePreviews", "dicom3d": "Dicom3D", "dateformat": "DateFormat", "aceeditortheme": "AceEditorTheme", "sorting": "Sorting"}
|
||||
for i, field := range req.Which {
|
||||
canonical, ok := allowed[strings.ToLower(field)]
|
||||
if !ok {
|
||||
|
||||
@@ -27,7 +27,7 @@ var Catalog = []Tool{
|
||||
tool("lightcraft", "LightCraft", ".dng", ".dng .cr2 .cr3 .nef .nrw .arw .pef .orf .rw2 .raf .jpg .jpeg .png .tif .tiff", ".jpg .jpeg .png .tif .tiff", "image", "drop"),
|
||||
tool("designcraft", "DesignCraft", ".designcraft", ".designcraft .idml", ".designcraft .idml .pdf .png .jpg .jpeg", "file", "drop"),
|
||||
tool("figcraft", "FigCraft", ".figcraft", ".figcraft", ".figcraft .svg .png .jpg .jpeg .pdf", "palette", "drop"),
|
||||
tool("soundcraft", "SoundCraft", ".scraftz", ".scraftz .wav .flac .mp3 .ogg .aif .aiff .m4a .mid .midi", ".scraftz .wav .flac .mp3 .ogg .aif .aiff .m4a .mid .midi", "music", "drop"),
|
||||
tool("soundcraft", "SoundCraft", ".scraftz", ".scraftz", ".scraftz .wav .flac .mp3 .ogg .aif .aiff .m4a .mid .midi", "music", "drop"),
|
||||
tool("cadcraft", "CADCraft", ".dxf", ".dxf .dwg", ".dxf .pdf .svg .png", "table", "native"),
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ func containsExtension(list []string, extension string) bool {
|
||||
}
|
||||
|
||||
// Known web builds that could not complete server file round trips.
|
||||
// Keep installation available so users can update them when upstream fixes land.
|
||||
// The installer rejects these exact builds; newer fixed releases remain eligible.
|
||||
func CompatibilityIssue(id, build string) string {
|
||||
if id == "soundcraft" && build == "v0.11.0-ca335c74d511" {
|
||||
return "demoOnly"
|
||||
|
||||
@@ -201,6 +201,9 @@ func (m *Manager) install(ctx context.Context, id string) error {
|
||||
return errors.New("unexpected release download URL")
|
||||
}
|
||||
build := rel.Tag + "-" + digest[:12]
|
||||
if issue := CompatibilityIssue(id, build); issue != "" {
|
||||
return fmt.Errorf("incompatible web release: %s", issue)
|
||||
}
|
||||
if m.manifest(id).Build == build {
|
||||
return precompress(filepath.Join(m.Root, id, "versions", build))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/filebrowser/filebrowser/v2/internal/addons"
|
||||
)
|
||||
|
||||
var autoOpenExtension = regexp.MustCompile(`^\.[a-z0-9][a-z0-9+-]{0,15}$`)
|
||||
|
||||
// Preferences select an opener; they never grant access to an addon or file.
|
||||
func normalizeAutoOpen(values map[string]string) (map[string]string, bool) {
|
||||
if len(values) > 512 {
|
||||
return nil, false
|
||||
}
|
||||
result := make(map[string]string, len(values))
|
||||
for extension, handler := range values {
|
||||
extension = strings.ToLower(strings.TrimSpace(extension))
|
||||
if !autoOpenExtension.MatchString(extension) {
|
||||
return nil, false
|
||||
}
|
||||
if _, exists := result[extension]; exists {
|
||||
return nil, false
|
||||
}
|
||||
if handler != "preview" && handler != "download" {
|
||||
tool, ok := addons.Find(handler)
|
||||
if !ok || !tool.CanOpen(extension) {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
result[extension] = handler
|
||||
}
|
||||
return result, true
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package users
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAutoOpenPreferences(t *testing.T) {
|
||||
valid, ok := normalizeAutoOpen(map[string]string{".JPG": "photocraft", ".txt": "preview", ".mp3": "download"})
|
||||
if !ok || valid[".jpg"] != "photocraft" {
|
||||
t.Fatal("valid mappings rejected")
|
||||
}
|
||||
for _, values := range []map[string]string{
|
||||
{"jpg": "photocraft"}, {"../secret": "download"}, {".jpg": "https://example.com"}, {".mp3": "soundcraft"}, {".jpg": "wordcraft"},
|
||||
} {
|
||||
if _, ok := normalizeAutoOpen(values); ok {
|
||||
t.Fatalf("invalid mapping accepted: %v", values)
|
||||
}
|
||||
}
|
||||
if _, ok := normalizeAutoOpen(nil); !ok {
|
||||
t.Fatal("legacy users must retain default opening behavior")
|
||||
}
|
||||
}
|
||||
@@ -19,28 +19,29 @@ const (
|
||||
|
||||
// User describes a user.
|
||||
type User struct {
|
||||
ID uint `storm:"id,increment" json:"id"`
|
||||
Username string `storm:"unique" json:"username"`
|
||||
DisplayName string `json:"displayName,omitempty"`
|
||||
ProfileName string `json:"profileName,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Password string `json:"password"`
|
||||
Scope string `json:"scope"`
|
||||
Locale string `json:"locale"`
|
||||
LockPassword bool `json:"lockPassword"`
|
||||
ViewMode ViewMode `json:"viewMode"`
|
||||
SingleClick bool `json:"singleClick"`
|
||||
RedirectAfterCopyMove bool `json:"redirectAfterCopyMove"`
|
||||
Perm Permissions `json:"perm"`
|
||||
Commands []string `json:"commands"`
|
||||
Sorting files.Sorting `json:"sorting"`
|
||||
Fs afero.Fs `json:"-" yaml:"-"`
|
||||
Rules []rules.Rule `json:"rules"`
|
||||
HideDotfiles bool `json:"hideDotfiles"`
|
||||
HidePreviews bool `json:"hidePreviews"`
|
||||
Dicom3D Dicom3DSettings `json:"dicom3D"`
|
||||
DateFormat bool `json:"dateFormat"`
|
||||
AceEditorTheme string `json:"aceEditorTheme"`
|
||||
ID uint `storm:"id,increment" json:"id"`
|
||||
Username string `storm:"unique" json:"username"`
|
||||
DisplayName string `json:"displayName,omitempty"`
|
||||
ProfileName string `json:"profileName,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Password string `json:"password"`
|
||||
Scope string `json:"scope"`
|
||||
Locale string `json:"locale"`
|
||||
LockPassword bool `json:"lockPassword"`
|
||||
ViewMode ViewMode `json:"viewMode"`
|
||||
SingleClick bool `json:"singleClick"`
|
||||
AutoOpen map[string]string `json:"autoOpen"`
|
||||
RedirectAfterCopyMove bool `json:"redirectAfterCopyMove"`
|
||||
Perm Permissions `json:"perm"`
|
||||
Commands []string `json:"commands"`
|
||||
Sorting files.Sorting `json:"sorting"`
|
||||
Fs afero.Fs `json:"-" yaml:"-"`
|
||||
Rules []rules.Rule `json:"rules"`
|
||||
HideDotfiles bool `json:"hideDotfiles"`
|
||||
HidePreviews bool `json:"hidePreviews"`
|
||||
Dicom3D Dicom3DSettings `json:"dicom3D"`
|
||||
DateFormat bool `json:"dateFormat"`
|
||||
AceEditorTheme string `json:"aceEditorTheme"`
|
||||
}
|
||||
|
||||
// GetRules implements rules.Provider.
|
||||
@@ -57,6 +58,7 @@ var checkableFields = []string{
|
||||
"Sorting",
|
||||
"Rules",
|
||||
"Dicom3D",
|
||||
"AutoOpen",
|
||||
}
|
||||
|
||||
// Clean cleans up a user and verifies if all its fields
|
||||
@@ -68,6 +70,12 @@ func (u *User) Clean(baseScope string, followExternalSymlinks bool, fields ...st
|
||||
|
||||
for _, field := range fields {
|
||||
switch field {
|
||||
case "AutoOpen":
|
||||
var valid bool
|
||||
u.AutoOpen, valid = normalizeAutoOpen(u.AutoOpen)
|
||||
if !valid {
|
||||
return fberrors.ErrInvalidRequestParams
|
||||
}
|
||||
case "Dicom3D":
|
||||
if !u.Dicom3D.Valid() {
|
||||
return fberrors.ErrInvalidRequestParams
|
||||
|
||||