Add profile 3D preferences and adapt DICOM preview resolution to memory budget

This commit is contained in:
SantaSpeen committed 2026-10-22 22:29:28 +03:00
1 parent 705762d57c
commit 7fd7ae6733
22 files changed
+500 -68

No files matched your search

+2
View File
@@ -18,6 +18,8 @@
Объёмный режим включает вращение и масштабирование 3D, аксиальную/сагиттальную/корональную реконструкцию, прокрутку срезов, перемещение, яркость/контрастность и непрозрачность. Нужен WebGL2. На неподходящем устройстве сохраняется 2D.
В настройках профиля есть раздел **DICOM — 3D-просмотр**: качество (автоматическое, исходное, половинное, четверть), лимит памяти вокселей 128–1536 МиБ и начальная непрозрачность. Настройки хранятся в аккаунте. По умолчанию автоматический режим подбирает разрешение под 1536 МиБ: большие срезы уменьшаются билинейной интерполяцией с сохранением поля обзора, координат пациента и физического масштаба; все срезы сохраняются. В просмотрщике показывается уменьшенное разрешение. Исходные DICOM-файлы не изменяются. При выборе исходного или фиксированного качества превышение персонального лимита по-прежнему останавливает просмотр.
Ограничения: до 2048 файлов, 64 МиБ на исходный файл, 1,5 ГиБ суммарной загрузки и 1,5 ГиБ Float32-вокселей. Это лимит массива объёма, а не всей памяти браузера: сборка и GPU требуют дополнительной памяти. Файлы читаются последовательно только после нажатия кнопки, загрузку можно отменить. При закрытии удаляются движок, GPU-ресурсы и принадлежащие просмотру записи кеша.
При запуске 3D в консоль браузера выводятся сообщения `[DICOM 3D]`: число файлов, общий и максимальный исходный размер, а после декодирования первого среза — размеры сетки и оценка Float32-объёма. При превышении лимита выводятся конкретная причина, фактическое значение и порог. Размеры указаны в байтах и ГиБ; пути, токены и медицинские теги не логируются.
+46
View File
@@ -59,6 +59,23 @@ const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
res.end(JSON.stringify(data));
};
if (u.pathname === "/api/session") return json(user);
if (u.pathname === "/api/users/1" && req.method === "PUT") {
let body = "";
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", () => {
const update = JSON.parse(body);
if (!update.which.includes("dicom3D")) {
res.writeHead(400);
res.end();
return;
}
Object.assign(user, update.data);
json({});
});
return;
}
if (u.pathname === "/api/addons") return json([]);
if (u.pathname.startsWith("/api/resources"))
return json(
@@ -106,6 +123,30 @@ const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
});
await route.fulfill({ response });
});
await page.goto(base + "/settings/profile");
await page.getByLabel("3D preview quality").selectOption("half");
await page.getByLabel("Voxel memory limit").selectOption("512");
await page.getByLabel("Initial opacity").fill("50");
await Promise.all([
page.waitForResponse(
(r) => r.url().endsWith("/api/users/1") && r.status() === 200
),
page.getByRole("button", { name: "Save", exact: true }).click(),
]);
await page.reload();
await page.getByLabel("3D preview quality").waitFor();
if (
(await page.getByLabel("3D preview quality").inputValue()) !== "half" ||
(await page.getByLabel("Voxel memory limit").inputValue()) !== "512"
)
throw new Error("3D profile settings were not restored");
await page.getByLabel("3D preview quality").selectOption("auto");
await Promise.all([
page.waitForResponse(
(r) => r.url().endsWith("/api/users/1") && r.status() === 200
),
page.getByRole("button", { name: "Save", exact: true }).click(),
]);
await page.goto(base + "/files/series/scan_1.dcm");
await page.waitForFunction(
() =>
@@ -120,6 +161,11 @@ const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
await page
.locator(".dicom-volume-stage canvas")
.waitFor({ timeout: 20000 });
if (
(await page.locator('.dicom-volume input[type="range"]').inputValue()) !==
"0.5"
)
throw new Error("Viewer ignored profile opacity");
for (const label of ["Axial", "Sagittal", "Coronal", "3D"]) {
await page.getByRole("button", { name: label, exact: true }).click();
await page.waitForTimeout(150);
@@ -74,6 +74,7 @@ import {
watch,
} from "vue";
import { useI18n } from "vue-i18n";
import { useAuthStore } from "@/stores/auth";
import DicomWorker from "@/utils/dicom.worker?worker";
import { readDicomFile } from "@/utils/dicom-file";
import { findDicomSeries } from "@/utils/dicom-context";
@@ -88,6 +89,7 @@ const DicomVolumeViewer = defineAsyncComponent({
});
const props = defineProps<{ source: string; resource?: Resource }>();
const { t } = useI18n();
const auth = useAuthStore();
const series = shallowRef<DicomSource[]>([]),
volume = shallowRef<DicomVolume>();
const volumeLoading = ref(false),
@@ -124,7 +126,8 @@ async function openVolume() {
request.signal,
(count) => {
loaded.value = count;
}
},
auth.user?.dicom3D
);
if (!request.signal.aborted) volume.value = result;
} catch (e) {
@@ -37,6 +37,17 @@
</div>
<p class="dicom-volume-hint">
{{ t(mode === "3d" ? "documents.volumeHint" : "documents.sliceHint") }}
<span v-if="volume.sampling && volume.sampling.factor > 1">
·
{{
t("documents.reduced3d", {
factor: volume.sampling.factor,
width: volume.dimensions[0],
height: volume.dimensions[1],
slices: volume.dimensions[2],
})
}}</span
>
</p>
<div
ref="element"
@@ -64,7 +75,7 @@ type Mode = (typeof views)[number];
const mode = ref<Mode>("3d"),
center = ref(props.volume.first.center),
width = ref(props.volume.first.width),
opacity = ref(0.3);
opacity = ref(props.volume.opacity ?? 0.3);
const id = `fs-dicom-${crypto.getRandomValues(new Uint32Array(2)).join("-")}`;
const viewportID = `${id}-viewport`;
let engine: InstanceType<typeof core.RenderingEngine> | undefined;
@@ -154,7 +165,7 @@ async function switchView(value: Mode) {
function reset() {
center.value = props.volume.first.center;
width.value = props.volume.first.width;
opacity.value = 0.3;
opacity.value = props.volume.opacity ?? 0.3;
viewport()?.resetCamera();
schedule();
}
+13 -3
View File
@@ -365,7 +365,7 @@
"open3d": "Open as 3D",
"back2d": "Back to 2D",
"loading3d": "Loading series: {count} / {total}",
"volumeLimit": "This series exceeds the safe 3D preview limit (1.5 GiB of decoded voxels, 2048 files). Use 2D preview.",
"volumeLimit": "3D preview limit exceeded. See the browser console for the size and limiting condition.",
"volumeInvalid": "Cannot build a volume: the slices must belong to one study and series, have matching geometry and uniform spacing. 2D preview remains available.",
"volumeUnavailable": "3D preview is unavailable on this device. WebGL2 with volume rendering support is required.",
"axial": "Axial",
@@ -373,7 +373,8 @@
"coronal": "Coronal",
"opacity": "Opacity",
"volumeHint": "Drag to rotate · Scroll to zoom",
"sliceHint": "Scroll to change slice · Drag to pan · Ctrl + scroll to zoom"
"sliceHint": "Scroll to change slice · Drag to pan · Ctrl + scroll to zoom",
"reduced3d": "Reduced 3D preview: {width} × {height} × {slices}"
},
"fileInfo": {
"dicom": "DICOM metadata",
@@ -409,7 +410,16 @@
"regional": "Language and dates",
"publicPages": "Public pages",
"homeFolders": "Home folders",
"manage": "Manage"
"manage": "Manage",
"dicom3D": "DICOM — 3D preview",
"dicomQuality": "3D preview quality",
"dicomAuto": "Automatic — fit memory limit",
"dicomOriginal": "Original resolution",
"dicomHalf": "Half resolution",
"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."
},
"notifications": {
"success": "Done",
+13 -3
View File
@@ -362,7 +362,7 @@
"open3d": "Открыть как 3D",
"back2d": "Вернуться к 2D",
"loading3d": "Загрузка серии: {count} / {total}",
"volumeLimit": "Серия превышает безопасный лимит 3D-просмотра (1,5 ГиБ декодированных вокселей, 2048 файлов). Используйте 2D.",
"volumeLimit": "Превышен лимит 3D-просмотра. Размер и причина ограничения указаны в консоли браузера.",
"volumeInvalid": "Не удалось построить объём: нужны срезы одного исследования и серии, с одинаковой геометрией и равномерным шагом. Просмотр в 2D доступен.",
"volumeUnavailable": "3D-просмотр недоступен на этом устройстве. Нужна поддержка WebGL2 и объёмного рендеринга.",
"axial": "Аксиально",
@@ -370,7 +370,8 @@
"coronal": "Коронально",
"opacity": "Непрозрачность",
"volumeHint": "Перетаскивание — вращение · Колесо — масштаб",
"sliceHint": "Колесо — смена среза · Перетаскивание — перемещение · Ctrl + колесо — масштаб"
"sliceHint": "Колесо — смена среза · Перетаскивание — перемещение · Ctrl + колесо — масштаб",
"reduced3d": "Уменьшенное 3D-превью: {width} × {height} × {slices}"
},
"fileInfo": {
"dicom": "Метаданные DICOM",
@@ -406,7 +407,16 @@
"regional": "Язык и даты",
"publicPages": "Публичные страницы",
"homeFolders": "Личные папки",
"manage": "Управление"
"manage": "Управление",
"dicom3D": "DICOM — 3D-просмотр",
"dicomQuality": "Качество 3D-превью",
"dicomAuto": "Автоматически — под лимит памяти",
"dicomOriginal": "Исходное разрешение",
"dicomHalf": "Уменьшить разрешение в 2 раза",
"dicomQuarter": "Уменьшить разрешение в 4 раза",
"dicomMemory": "Лимит памяти для вокселей",
"dicomOpacity": "Начальная непрозрачность",
"dicomHint": "Автоматический режим уменьшает большие серии, сохраняя все срезы и физические пропорции. Лимит относится к вокселям; сборка и видеокарта требуют дополнительной памяти."
},
"notifications": {
"success": "Готово",
+7
View File
@@ -14,6 +14,7 @@ interface IUser {
lockPassword: boolean;
hideDotfiles: boolean;
hidePreviews?: boolean;
dicom3D?: Dicom3DSettings;
singleClick: boolean;
redirectAfterCopyMove: boolean;
dateFormat: boolean;
@@ -22,6 +23,12 @@ interface IUser {
aceEditorTheme: string;
}
interface Dicom3DSettings {
memoryMiB: number;
quality: "auto" | "original" | "half" | "quarter";
opacity: number;
}
type ViewModeType = "list" | "mosaic" | "mosaic gallery";
interface IUserForm {
@@ -0,0 +1,67 @@
import { expect, it } from "vitest";
import {
dicomPreferences,
volumeSampling,
resampleSlice,
} from "../dicom-quality";
import { assembleVolume, type DicomSlice } from "../dicom-series";
it("fits a 768-slice volume into the profile memory budget", () => {
const plan = volumeSampling(1024, 1024, 768);
expect(plan.factor).toBe(2);
expect(plan.bytes).toBe(768 * 512 * 512 * 4);
expect(plan.bytes).toBeLessThanOrEqual(plan.limit);
expect(volumeSampling(1024, 1024, 768, { memoryMiB: 128 }).factor).toBe(5);
expect(() =>
volumeSampling(1024, 1024, 768, { quality: "original" })
).toThrow("DICOM_VOLUME_LIMIT");
});
it("handles odd dimensions, rounding and explicit quality modes", () => {
const plan = volumeSampling(1025, 1025, 768);
expect(plan.bytes).toBeLessThanOrEqual(plan.limit);
expect(volumeSampling(1024, 1024, 768, { quality: "quarter" }).cols).toBe(
256
);
expect(dicomPreferences({ memoryMiB: Infinity, opacity: -10 })).toEqual({
memoryMiB: 1536,
quality: "auto",
opacity: 30,
});
});
it("preserves patient-space extent, positions, signed intensities and source pixels", () => {
const original: DicomSlice = {
study: "study",
series: "series",
reference: "frame",
instance: "one",
modality: "CT",
rows: 4,
cols: 4,
orientation: [1, 0, 0, 0, 1, 0],
position: [10, 20, 30],
spacing: [0.5, 0.75],
pixels: Float32Array.from({ length: 16 }, (_, i) => i - 8),
center: 0,
width: 20,
};
const plan = {
rows: 2,
cols: 2,
factor: 2,
bytes: 32,
limit: 100,
originalDimensions: [4, 4, 2] as [number, number, number],
};
const reduced = resampleSlice(original, plan);
expect(Array.from(reduced.pixels)).toEqual([-8, -5, 4, 7]);
expect(reduced.spacing).toEqual([1.5, 2.25]);
expect(reduced.position).toEqual(original.position);
expect(reduced.orientation).toEqual(original.orientation);
expect(original.pixels.length).toBe(16);
expect(original.spacing).toEqual([0.5, 0.75]);
const volume = assembleVolume([
reduced,
{ ...reduced, instance: "two", position: [10, 20, 31] },
]);
expect(volume.spacing).toEqual([2.25, 1.5, 1]);
expect(volume.origin).toEqual([10, 20, 30]);
});
+8 -4
View File
@@ -7,7 +7,10 @@ import {
const size = (bytes: number) =>
`${(bytes / 1024 ** 3).toFixed(3)} GiB (${bytes.toLocaleString("en-US")} bytes)`;
export function logDicomSeries(sources: DicomSource[]) {
export function logDicomSeries(
sources: DicomSource[],
decodedLimit = MAX_VOLUME_BYTES
) {
const sourceBytes = sources.reduce((total, file) => total + file.size, 0);
const largestFileBytes = sources.reduce(
(largest, file) => Math.max(largest, file.size),
@@ -21,7 +24,7 @@ export function logDicomSeries(sources: DicomSource[]) {
largestFileBytes,
largestFileSize: size(largestFileBytes),
sourceLimit: size(MAX_VOLUME_BYTES),
decodedVolumeLimit: size(MAX_VOLUME_BYTES),
decodedVolumeLimit: size(decodedLimit),
perFileLimit: "64 MiB",
fileCountLimit: MAX_SERIES_FILES,
});
@@ -31,7 +34,8 @@ export function logDicomSeries(sources: DicomSource[]) {
export function logDicomVolumeEstimate(
rows: number,
cols: number,
count: number
count: number,
decodedLimit = MAX_VOLUME_BYTES
) {
const decodedBytes = rows * cols * count * Float32Array.BYTES_PER_ELEMENT;
console.info("[DICOM 3D] Decoded volume estimate", {
@@ -39,7 +43,7 @@ export function logDicomVolumeEstimate(
bytesPerVoxel: Float32Array.BYTES_PER_ELEMENT,
decodedBytes,
decodedSize: size(decodedBytes),
decodedVolumeLimit: size(MAX_VOLUME_BYTES),
decodedVolumeLimit: size(decodedLimit),
});
return decodedBytes;
}
+101
View File
@@ -0,0 +1,101 @@
import { MAX_VOLUME_BYTES, type DicomSlice } from "./dicom-series";
export function dicomPreferences(
value?: Partial<Dicom3DSettings>
): Dicom3DSettings {
return {
memoryMiB:
Number.isInteger(value?.memoryMiB) &&
value!.memoryMiB! >= 128 &&
value!.memoryMiB! <= 1536
? value!.memoryMiB!
: 1536,
quality: ["auto", "original", "half", "quarter"].includes(
value?.quality || ""
)
? value!.quality!
: "auto",
opacity:
Number.isInteger(value?.opacity) &&
value!.opacity! >= 5 &&
value!.opacity! <= 100
? value!.opacity!
: 30,
};
}
export function volumeSampling(
rows: number,
cols: number,
count: number,
preferences?: Partial<Dicom3DSettings>
) {
const settings = dicomPreferences(preferences);
const limit = Math.min(MAX_VOLUME_BYTES, settings.memoryMiB * 1024 * 1024);
let factor =
settings.quality === "half" ? 2 : settings.quality === "quarter" ? 4 : 1;
const dimensions = () => ({
rows: Math.max(2, Math.ceil(rows / factor)),
cols: Math.max(2, Math.ceil(cols / factor)),
});
const bytes = () => dimensions().rows * dimensions().cols * count * 4;
if (settings.quality === "auto") {
factor = Math.max(
1,
Math.ceil(Math.sqrt((rows * cols * count * 4) / limit))
);
while (bytes() > limit && factor < Math.max(rows, cols)) factor++;
}
if (
rows < 2 ||
cols < 2 ||
![rows, cols, count].every((n) => Number.isSafeInteger(n) && n > 0)
)
throw new Error("DICOM_GEOMETRY");
if (bytes() > limit) throw new Error("DICOM_VOLUME_LIMIT");
return {
...dimensions(),
factor,
bytes: bytes(),
limit,
originalDimensions: [cols, rows, count] as [number, number, number],
};
}
// Bilinear resampling keeps the full field of view and its physical spacing.
// Every slice keeps its original patient position and orientation.
export function resampleSlice(
slice: DicomSlice,
target: ReturnType<typeof volumeSampling>
): DicomSlice {
if (target.rows === slice.rows && target.cols === slice.cols) return slice;
const dx = (slice.cols - 1) / (target.cols - 1),
dy = (slice.rows - 1) / (target.rows - 1);
const pixels = new Float32Array(target.rows * target.cols);
for (let y = 0; y < target.rows; y++) {
const sy = y * dy,
y0 = Math.floor(sy),
y1 = Math.min(slice.rows - 1, y0 + 1),
fy = sy - y0;
for (let x = 0; x < target.cols; x++) {
const sx = x * dx,
x0 = Math.floor(sx),
x1 = Math.min(slice.cols - 1, x0 + 1),
fx = sx - x0;
const a =
slice.pixels[y0 * slice.cols + x0] * (1 - fx) +
slice.pixels[y0 * slice.cols + x1] * fx;
const b =
slice.pixels[y1 * slice.cols + x0] * (1 - fx) +
slice.pixels[y1 * slice.cols + x1] * fx;
pixels[y * target.cols + x] = a * (1 - fy) + b * fy;
}
}
return {
...slice,
rows: target.rows,
cols: target.cols,
pixels,
spacing: [slice.spacing[0] * dy, slice.spacing[1] * dx],
};
}
+4 -1
View File
@@ -152,4 +152,7 @@ export function assembleVolume(slices: DicomSlice[]) {
first,
};
}
export type DicomVolume = ReturnType<typeof assembleVolume>;
export type DicomVolume = ReturnType<typeof assembleVolume> & {
sampling?: { factor: number; originalDimensions: [number, number, number] };
opacity?: number;
};
+44 -12
View File
@@ -1,5 +1,10 @@
import DicomWorker from "./dicom.worker?worker";
import { readDicomFile } from "./dicom-file";
import {
dicomPreferences,
volumeSampling,
resampleSlice,
} from "./dicom-quality";
import {
logDicomSeries,
logDicomVolumeEstimate,
@@ -17,9 +22,15 @@ import {
export async function loadDicomVolume(
sources: DicomSource[],
signal: AbortSignal,
progress: (loaded: number) => void
progress: (loaded: number) => void,
preferences?: Partial<Dicom3DSettings>
) {
const { sourceBytes, largestFileBytes } = logDicomSeries(sources);
const settings = dicomPreferences(preferences);
const memoryLimit = settings.memoryMiB * 1024 * 1024;
const { sourceBytes, largestFileBytes } = logDicomSeries(
sources,
memoryLimit
);
if (sources.length < 2 || sources.length > MAX_SERIES_FILES)
dicomLimitExceeded("file count", sources.length, MAX_SERIES_FILES);
if (largestFileBytes > 64 * 1024 * 1024)
@@ -36,6 +47,8 @@ export async function loadDicomVolume(
);
const worker = new DicomWorker();
const slices: DicomSlice[] = [];
let originalFirst: DicomSlice | undefined;
let sampling: ReturnType<typeof volumeSampling> | undefined;
let bytes = 0;
try {
for (const source of sources) {
@@ -78,16 +91,31 @@ export async function loadDicomVolume(
buffer,
]);
});
checkSlice(slice, slices[0] || slice);
if (slices.length === 0)
logDicomVolumeEstimate(slice.rows, slice.cols, sources.length);
if (slice.pixels.byteLength * sources.length > MAX_VOLUME_BYTES)
dicomLimitExceeded(
"decoded Float32 voxel bytes",
slice.pixels.byteLength * sources.length,
MAX_VOLUME_BYTES
checkSlice(slice, originalFirst || slice);
if (!originalFirst) {
originalFirst = slice;
logDicomVolumeEstimate(
slice.rows,
slice.cols,
sources.length,
memoryLimit
);
slices.push(slice);
sampling = volumeSampling(
slice.rows,
slice.cols,
sources.length,
settings
);
console.info("[DICOM 3D] Preview resolution", {
quality: settings.quality,
factor: sampling.factor,
originalDimensions: sampling.originalDimensions,
previewDimensions: [sampling.cols, sampling.rows, sources.length],
decodedBytes: sampling.bytes,
memoryLimitBytes: sampling.limit,
});
}
slices.push(resampleSlice(slice, sampling!));
progress(slices.length);
}
if (signal.aborted) throw new DOMException("Aborted", "AbortError");
@@ -95,7 +123,11 @@ export async function loadDicomVolume(
fileCount: slices.length,
downloadedBytes: bytes,
});
return assembleVolume(slices);
return {
...assembleVolume(slices),
sampling,
opacity: settings.opacity / 100,
};
} catch (error) {
if (!signal.aborted)
console.warn("[DICOM 3D] Loading stopped", {
+44 -1
View File
@@ -46,7 +46,45 @@
><input type="checkbox" v-model="redirectAfterCopyMove"
/></label>
</section>
<section class="card settings-section settings-wide">
<section class="card settings-section">
<h2><AppIcon name="tune" />{{ t("preferences.dicom3D") }}</h2>
<label class="settings-field"
>{{ t("preferences.dicomQuality") }}
<select v-model="dicom3D.quality" class="input">
<option value="auto">{{ t("preferences.dicomAuto") }}</option>
<option value="original">
{{ t("preferences.dicomOriginal") }}
</option>
<option value="half">{{ t("preferences.dicomHalf") }}</option>
<option value="quarter">{{ t("preferences.dicomQuarter") }}</option>
</select>
</label>
<label class="settings-field"
>{{ t("preferences.dicomMemory") }}
<select v-model.number="dicom3D.memoryMiB" class="input">
<option
v-for="memory in [128, 256, 512, 1024, 1536]"
:key="memory"
:value="memory"
>
{{ memory }} MiB
</option>
</select>
</label>
<label class="settings-field"
>{{ t("preferences.dicomOpacity") }} ({{ dicom3D.opacity }}%)
<input
v-model.number="dicom3D.opacity"
class="input"
type="range"
min="5"
max="100"
step="5"
/>
</label>
<p class="settings-hint">{{ t("preferences.dicomHint") }}</p>
</section>
<section class="card settings-section">
<h2><AppIcon name="language" />{{ t("preferences.regional") }}</h2>
<label class="settings-field"
>{{ t("settings.language")
@@ -73,6 +111,7 @@ import Languages from "@/components/settings/Languages.vue";
import AccountAvatar from "@/components/AccountAvatar.vue";
import { baseURL } from "@/utils/constants";
import { getTheme, setTheme } from "@/utils/theme";
import { dicomPreferences } from "@/utils/dicom-quality";
import { inject, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
@@ -91,6 +130,7 @@ const dateFormat = ref<boolean>(false);
const locale = ref<string>("");
const selectedTheme = ref<UserTheme>(getTheme());
const saving = ref(false);
const dicom3D = ref(dicomPreferences());
onMounted(async () => {
layoutStore.loading = true;
@@ -104,6 +144,7 @@ onMounted(async () => {
singleClick.value = authStore.user.singleClick;
redirectAfterCopyMove.value = authStore.user.redirectAfterCopyMove;
dateFormat.value = authStore.user.dateFormat;
dicom3D.value = dicomPreferences(authStore.user.dicom3D);
layoutStore.loading = false;
return true;
@@ -126,6 +167,7 @@ const updateSettings = async (event: Event) => {
singleClick: singleClick.value,
redirectAfterCopyMove: redirectAfterCopyMove.value,
dateFormat: dateFormat.value,
dicom3D: { ...dicom3D.value },
};
await api.update(data, [
@@ -135,6 +177,7 @@ const updateSettings = async (event: Event) => {
"singleClick",
"redirectAfterCopyMove",
"dateFormat",
"dicom3D",
]);
authStore.updateUser(data);
$showSuccess(t("settings.settingsUpdated"));
+17 -16
View File
@@ -6,22 +6,23 @@ import (
)
type userInfo struct {
ID uint `json:"id"`
Locale string `json:"locale"`
ViewMode users.ViewMode `json:"viewMode"`
SingleClick bool `json:"singleClick"`
RedirectAfterCopyMove bool `json:"redirectAfterCopyMove"`
Perm users.Permissions `json:"perm"`
Commands []string `json:"commands"`
LockPassword bool `json:"lockPassword"`
HideDotfiles bool `json:"hideDotfiles"`
HidePreviews bool `json:"hidePreviews"`
DateFormat bool `json:"dateFormat"`
Username string `json:"username"`
ProfileName string `json:"profileName,omitempty"`
Email string `json:"email,omitempty"`
Picture string `json:"picture,omitempty"`
AceEditorTheme string `json:"aceEditorTheme"`
ID uint `json:"id"`
Locale string `json:"locale"`
ViewMode users.ViewMode `json:"viewMode"`
SingleClick bool `json:"singleClick"`
RedirectAfterCopyMove bool `json:"redirectAfterCopyMove"`
Perm users.Permissions `json:"perm"`
Commands []string `json:"commands"`
LockPassword bool `json:"lockPassword"`
HideDotfiles bool `json:"hideDotfiles"`
HidePreviews bool `json:"hidePreviews"`
Dicom3D users.Dicom3DSettings `json:"dicom3D"`
DateFormat bool `json:"dateFormat"`
Username string `json:"username"`
ProfileName string `json:"profileName,omitempty"`
Email string `json:"email,omitempty"`
Picture string `json:"picture,omitempty"`
AceEditorTheme string `json:"aceEditorTheme"`
}
func withUser(fn handleFunc) handleFunc {
+1 -1
View File
@@ -462,5 +462,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, 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, 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}
}
+34
View File
@@ -12,6 +12,40 @@ import (
"github.com/gorilla/mux"
)
func TestDicom3DPreferencesAreSelfEditableAndValidated(t *testing.T) {
st := scopedUserStorage(t, t.TempDir(), users.Permissions{}, []byte("key"))
for _, test := range []struct {
body string
status int
}{
{`{"what":"user","which":["dicom3D"],"data":{"id":1,"dicom3D":{"memoryMiB":512,"quality":"auto","opacity":50}}}`, 200},
{`{"what":"user","which":["dicom3D"],"data":{"id":1,"dicom3D":{"memoryMiB":2048,"quality":"auto","opacity":50}}}`, 400},
{`{"what":"user","which":["dicom3D"],"data":{"id":1,"dicom3D":{"quality":"invalid"}}}`, 400},
} {
r := mux.SetURLVars(httptest.NewRequest("PUT", "/users/1", strings.NewReader(test.body)), map[string]string{"id": "1"})
r = authorizeTestRequest(r, testSession(1, "u", false))
w := httptest.NewRecorder()
handle(userPutHandler, "", st, &settings.Server{}).ServeHTTP(w, r)
if w.Code != test.status {
t.Fatalf("status %d, want %d: %s", w.Code, test.status, w.Body.String())
}
}
u, err := st.Users.Get("", false, uint(1))
if err != nil {
t.Fatal(err)
}
if u.Dicom3D.MemoryMiB != 512 || u.Dicom3D.Opacity != 50 || u.Dicom3D.Quality != "auto" {
t.Fatalf("settings not persisted: %+v", u.Dicom3D)
}
if u.Perm.Admin {
t.Fatal("preferences changed permissions")
}
// Check the same profile representation returned on subsequent SSO sessions.
if ssoUserInfo(u).Dicom3D != u.Dicom3D {
t.Fatal("session profile lost preferences")
}
}
func TestLocalAdminCannotOverrideSSORole(t *testing.T) {
st := scopedUserStorage(t, t.TempDir(), users.Permissions{Admin: true}, []byte("key"))
r := authorizeTestRequest(httptest.NewRequest("GET", "/", nil), testSession(1, "u", false))
+1 -1
View File
@@ -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", "dateformat": "DateFormat", "aceeditortheme": "AceEditorTheme", "sorting": "Sorting"}
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"}
for i, field := range req.Which {
canonical, ok := allowed[strings.ToLower(field)]
if !ok {
+1 -1
View File
@@ -1,4 +1,4 @@
param([string]$Version = '3.0.0-sso.28')
param([string]$Version = '3.0.0-sso.29')
$ErrorActionPreference = 'Stop'
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Push-Location $repo
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
VERSION="${VERSION:-3.0.0-sso.28}"
VERSION="${VERSION:-3.0.0-sso.29}"
COMMIT=$(git rev-parse --short HEAD)
(cd frontend && pnpm install --frozen-lockfile && pnpm run build)
mkdir -p build/release/linux-amd64
+26
View File
@@ -0,0 +1,26 @@
package users
type Dicom3DSettings struct {
MemoryMiB int `json:"memoryMiB"`
Quality string `json:"quality"`
Opacity int `json:"opacity"`
}
func (s Dicom3DSettings) Normalized() Dicom3DSettings {
if s.MemoryMiB == 0 {
s.MemoryMiB = 1536
}
if s.Quality == "" {
s.Quality = "auto"
}
if s.Opacity == 0 {
s.Opacity = 30
}
return s
}
func (s Dicom3DSettings) Valid() bool {
s = s.Normalized()
return s.MemoryMiB >= 128 && s.MemoryMiB <= 1536 && s.Opacity >= 5 && s.Opacity <= 100 &&
(s.Quality == "auto" || s.Quality == "original" || s.Quality == "half" || s.Quality == "quarter")
}
+25
View File
@@ -0,0 +1,25 @@
package users
import "testing"
func TestDicom3DSettings(t *testing.T) {
defaults := (Dicom3DSettings{}).Normalized()
if defaults.MemoryMiB != 1536 || defaults.Quality != "auto" || defaults.Opacity != 30 || !defaults.Valid() {
t.Fatal(defaults)
}
for _, bad := range []Dicom3DSettings{{MemoryMiB: 1537}, {MemoryMiB: -1}, {MemoryMiB: 127}, {Quality: "invalid"}, {Opacity: 101}, {Opacity: -1}} {
if bad.Valid() {
t.Fatalf("accepted invalid preferences: %+v", bad)
}
u := User{Dicom3D: bad}
if u.Clean("", false, "Dicom3D") == nil {
t.Fatalf("saved invalid preferences: %+v", bad)
}
}
for _, quality := range []string{"auto", "original", "half", "quarter"} {
u := User{Dicom3D: Dicom3DSettings{MemoryMiB: 512, Quality: quality, Opacity: 50}}
if err := u.Clean("", false, "Dicom3D"); err != nil {
t.Fatal(err)
}
}
}
+28 -21
View File
@@ -19,27 +19,28 @@ 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"`
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"`
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.
@@ -55,6 +56,7 @@ var checkableFields = []string{
"Commands",
"Sorting",
"Rules",
"Dicom3D",
}
// Clean cleans up a user and verifies if all its fields
@@ -66,6 +68,11 @@ func (u *User) Clean(baseScope string, followExternalSymlinks bool, fields ...st
for _, field := range fields {
switch field {
case "Dicom3D":
if !u.Dicom3D.Valid() {
return fberrors.ErrInvalidRequestParams
}
u.Dicom3D = u.Dicom3D.Normalized()
case "Username":
if u.Username == "" {
return fberrors.ErrEmptyUsername