mirror of
https://github.com/gtsteffaniak/filebrowser.git
synced 2026-11-24 15:43:41 -05:00
Fix asset loading 3d models (#3423)
This commit is contained in:
1 parent
cfe9ad992e
commit
2800be47dc
3 files changed
+279
-169
No files matched your search
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Pure helpers for resolving external asset references (textures, .mtl files,
|
||||
* glTF buffers/images) emitted by 3D loaders into FileBrowser file paths.
|
||||
* Kept free of store/DOM imports so they can be unit tested directly.
|
||||
*/
|
||||
|
||||
const EXTERNAL_URL_RE = /^https?:\/\//i;
|
||||
const WINDOWS_DRIVE_RE = /^[a-zA-Z]:/;
|
||||
const API_FILE_URL_RE = /\/api\/(media\/stream|resources\/(view|download))\?/;
|
||||
|
||||
function safeDecode(value) {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function parentDirOf(filePath) {
|
||||
const index = filePath.lastIndexOf("/");
|
||||
return index <= 0 ? "" : filePath.slice(0, index);
|
||||
}
|
||||
|
||||
function readFileParam(url) {
|
||||
const queryIndex = url.indexOf("?");
|
||||
if (queryIndex === -1) {
|
||||
return null;
|
||||
}
|
||||
const query = url.slice(queryIndex + 1).split("#")[0];
|
||||
return new URLSearchParams(query).get("file");
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a bare filename (no directory part) against the model's directory.
|
||||
* Uses the sibling listing when known; otherwise falls back to `textures/`.
|
||||
*/
|
||||
function resolveBareFilename(filename, modelDir, parentDirItems) {
|
||||
if (!Array.isArray(parentDirItems)) {
|
||||
return `${modelDir}/textures/${filename}`;
|
||||
}
|
||||
if (parentDirItems.some((item) => item.name === filename && item.type !== "directory")) {
|
||||
return `${modelDir}/${filename}`;
|
||||
}
|
||||
const texturesDir = parentDirItems.find(
|
||||
(item) => item.type === "directory" && item.name.toLowerCase() === "textures",
|
||||
);
|
||||
if (texturesDir) {
|
||||
return `${modelDir}/${texturesDir.name}/${filename}`;
|
||||
}
|
||||
return `${modelDir}/${filename}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a loader-emitted URL to the FileBrowser file path it refers to.
|
||||
*
|
||||
* @param {string} url Reference as emitted by the loader (may be encoded).
|
||||
* @param {{ modelPath?: string, parentDirItems?: Array<{name: string, type?: string}> }} [context]
|
||||
* @returns {string|null} Absolute file path inside the source, or null when the
|
||||
* URL must not be rewritten (blob:, data:, external http(s), or unresolvable).
|
||||
*/
|
||||
export function resolveAssetFilePath(url, { modelPath = "", parentDirItems } = {}) {
|
||||
if (!url || url.startsWith("blob:") || url.startsWith("data:")) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (API_FILE_URL_RE.test(url)) {
|
||||
const file = readFileParam(url);
|
||||
if (!file) {
|
||||
return null;
|
||||
}
|
||||
return file.startsWith("/") ? file : `/${file}`;
|
||||
}
|
||||
|
||||
const cleanUrl = safeDecode(url.split(/[?#]/)[0]);
|
||||
let ref;
|
||||
if (cleanUrl.includes("/api/resources/")) {
|
||||
ref = cleanUrl.split("/api/resources/").pop() || "";
|
||||
} else if (EXTERNAL_URL_RE.test(cleanUrl)) {
|
||||
return null;
|
||||
} else {
|
||||
ref = cleanUrl;
|
||||
}
|
||||
|
||||
// Windows exporters (FBX, OBJ/MTL, 3DS) often embed absolute drive paths such as
|
||||
// C:\art\diffuse.png. Those directories never exist on the server, so only the
|
||||
// filename is meaningful.
|
||||
ref = ref.replace(/\\/g, "/");
|
||||
const isDriveAbsolute = WINDOWS_DRIVE_RE.test(ref);
|
||||
if (isDriveAbsolute) {
|
||||
ref = ref.replace(WINDOWS_DRIVE_RE, "");
|
||||
}
|
||||
|
||||
ref = ref.replace(/^\/+/, "");
|
||||
const filename = ref.split("/").filter(Boolean).pop();
|
||||
if (!filename) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const modelDir = parentDirOf(modelPath);
|
||||
if (isDriveAbsolute || !ref.includes("/")) {
|
||||
return resolveBareFilename(filename, modelDir, parentDirItems);
|
||||
}
|
||||
|
||||
return resolveRelativeTo(modelPath, ref);
|
||||
}
|
||||
|
||||
function resolveRelativeTo(baseFilePath, relativeRef) {
|
||||
const parts = `${parentDirOf(baseFilePath)}/${relativeRef}`.split("/").filter(Boolean);
|
||||
const resolved = [];
|
||||
for (const part of parts) {
|
||||
if (part === ".") {
|
||||
continue;
|
||||
}
|
||||
if (part === "..") {
|
||||
resolved.pop();
|
||||
continue;
|
||||
}
|
||||
resolved.push(part);
|
||||
}
|
||||
return `/${resolved.join("/")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when a sibling file with this name exists. When the listing is unknown,
|
||||
* returns true so the caller still attempts the request.
|
||||
*/
|
||||
export function hasSiblingFile(parentDirItems, name) {
|
||||
if (!Array.isArray(parentDirItems)) {
|
||||
return true;
|
||||
}
|
||||
const lower = name.toLowerCase();
|
||||
return parentDirItems.some(
|
||||
(item) => item.type !== "directory" && item.name?.toLowerCase() === lower,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { hasSiblingFile, resolveAssetFilePath } from "./threeAssetUrl.js";
|
||||
|
||||
const MODEL = "/3D Prints/Snap/model.stl";
|
||||
const TEXTURES_DIR = { name: "textures", type: "directory" };
|
||||
|
||||
describe("resolveAssetFilePath", () => {
|
||||
it("passes through blob, data and external URLs (returns null)", () => {
|
||||
expect(resolveAssetFilePath("blob:http://x/abc", { modelPath: MODEL })).toBeNull();
|
||||
expect(resolveAssetFilePath("data:image/png;base64,AAAA", { modelPath: MODEL })).toBeNull();
|
||||
expect(resolveAssetFilePath("https://cdn.example.com/a.png", { modelPath: MODEL })).toBeNull();
|
||||
expect(resolveAssetFilePath("", { modelPath: MODEL })).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves relative paths against the model directory", () => {
|
||||
expect(resolveAssetFilePath("textures/albedo.png", { modelPath: MODEL })).toBe(
|
||||
"/3D Prints/Snap/textures/albedo.png",
|
||||
);
|
||||
expect(resolveAssetFilePath("../shared/tex.png", { modelPath: MODEL })).toBe(
|
||||
"/3D Prints/shared/tex.png",
|
||||
);
|
||||
});
|
||||
|
||||
it("decodes percent-encoded filenames exactly once", () => {
|
||||
expect(resolveAssetFilePath("Wood%20Diffuse.png", { modelPath: MODEL })).toBe(
|
||||
"/3D Prints/Snap/textures/Wood Diffuse.png",
|
||||
);
|
||||
expect(resolveAssetFilePath("textures/Wood%20Diffuse.png", { modelPath: MODEL })).toBe(
|
||||
"/3D Prints/Snap/textures/Wood Diffuse.png",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the sibling file for bare names when it exists beside the model", () => {
|
||||
const items = [{ name: "diffuse.png", type: "file" }];
|
||||
expect(resolveAssetFilePath("diffuse.png", { modelPath: MODEL, parentDirItems: items })).toBe(
|
||||
"/3D Prints/Snap/diffuse.png",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses a case-insensitive textures directory when listing shows one", () => {
|
||||
const items = [{ name: "Textures", type: "directory" }];
|
||||
expect(resolveAssetFilePath("diffuse.png", { modelPath: MODEL, parentDirItems: items })).toBe(
|
||||
"/3D Prints/Snap/Textures/diffuse.png",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not invent a textures directory when the listing shows none", () => {
|
||||
const items = [{ name: "other.stl", type: "file" }];
|
||||
expect(resolveAssetFilePath("diffuse.png", { modelPath: MODEL, parentDirItems: items })).toBe(
|
||||
"/3D Prints/Snap/diffuse.png",
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to textures/ when the listing is unknown", () => {
|
||||
expect(resolveAssetFilePath("diffuse.png", { modelPath: MODEL })).toBe(
|
||||
"/3D Prints/Snap/textures/diffuse.png",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps only the filename for Windows absolute paths", () => {
|
||||
const items = [TEXTURES_DIR];
|
||||
expect(
|
||||
resolveAssetFilePath("C:\\Users\\art\\diffuse.png", { modelPath: MODEL, parentDirItems: items }),
|
||||
).toBe("/3D Prints/Snap/textures/diffuse.png");
|
||||
expect(
|
||||
resolveAssetFilePath("C:/Users/art/diffuse.png", { modelPath: MODEL, parentDirItems: items }),
|
||||
).toBe("/3D Prints/Snap/textures/diffuse.png");
|
||||
});
|
||||
|
||||
it("normalizes Windows backslashes in relative paths", () => {
|
||||
expect(resolveAssetFilePath("textures\\albedo.png", { modelPath: MODEL })).toBe(
|
||||
"/3D Prints/Snap/textures/albedo.png",
|
||||
);
|
||||
});
|
||||
|
||||
it("reads the file parameter from FileBrowser API URLs", () => {
|
||||
expect(
|
||||
resolveAssetFilePath("/api/resources/view?source=default&file=%2F3D%20Prints%2Ftex.png&viewToken=abc", {
|
||||
modelPath: MODEL,
|
||||
}),
|
||||
).toBe("/3D Prints/tex.png");
|
||||
expect(resolveAssetFilePath("/api/resources/view?source=default", { modelPath: MODEL })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasSiblingFile", () => {
|
||||
it("returns true when the listing is unknown so the request is still attempted", () => {
|
||||
expect(hasSiblingFile(undefined, "model.mtl")).toBe(true);
|
||||
});
|
||||
|
||||
it("matches sibling names case-insensitively", () => {
|
||||
expect(hasSiblingFile([{ name: "Model.MTL", type: "file" }], "model.mtl")).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when no matching file exists", () => {
|
||||
expect(hasSiblingFile([{ name: "other.obj", type: "file" }], "model.mtl")).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores directories with the same name", () => {
|
||||
expect(hasSiblingFile([{ name: "model.mtl", type: "directory" }], "model.mtl")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -68,8 +68,14 @@ import FloatingActionButton from "@/components/settings/FloatingActionButton.vue
|
||||
import { state, mutations, getters } from "@/store";
|
||||
import { resourcesApi } from "@/api";
|
||||
import { getCachedViewToken, ensureViewToken, requestViewIdentity } from "@/api/viewToken";
|
||||
import { removeLastDir, resolveRelativePath } from "@/utils/url";
|
||||
import { getObjectProperty } from '@/utils/object.js';
|
||||
import { resolveAssetFilePath, hasSiblingFile } from "@/utils/threeAssetUrl.js";
|
||||
|
||||
// Texture slots on three.js materials that hold a Texture needing disposal.
|
||||
const TEXTURE_SLOTS = [
|
||||
'map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap',
|
||||
'aoMap', 'alphaMap', 'bumpMap', 'specularMap', 'envMap', 'displacementMap', 'lightMap',
|
||||
];
|
||||
|
||||
const LOADERS = {
|
||||
gltf: GLTFLoader,
|
||||
@@ -129,8 +135,9 @@ export default {
|
||||
loadTimer: null,
|
||||
hasInitialized: false,
|
||||
isInView: false,
|
||||
viewTokenByPath: {},
|
||||
fetchedDirs: new Set(),
|
||||
// Source-scoped view token: one token authorizes the model and all of its
|
||||
// external assets (textures, .mtl) within the same source.
|
||||
activeViewToken: "",
|
||||
lastRender: 0,
|
||||
};
|
||||
},
|
||||
@@ -363,7 +370,7 @@ export default {
|
||||
if (!filePath) {
|
||||
return "";
|
||||
}
|
||||
const viewToken = this.resolveViewTokenForPath(filePath);
|
||||
const viewToken = this.resolveViewToken();
|
||||
if (!viewToken) {
|
||||
return "";
|
||||
}
|
||||
@@ -387,183 +394,42 @@ export default {
|
||||
return url || "";
|
||||
},
|
||||
|
||||
normalizeAssetPath(filePath) {
|
||||
if (!filePath) {
|
||||
return filePath;
|
||||
}
|
||||
const trimmed = filePath.replace(/\/+$/, "");
|
||||
return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
|
||||
},
|
||||
|
||||
indexViewTokens(items) {
|
||||
if (!items?.length) {
|
||||
return;
|
||||
}
|
||||
for (const item of items) {
|
||||
if (item.path && item.viewToken) {
|
||||
this.viewTokenByPath[this.normalizeAssetPath(item.path)] = item.viewToken;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
directoryListingPath(dirPath) {
|
||||
const normalized = this.normalizeAssetPath(dirPath);
|
||||
return `${normalized}/`;
|
||||
},
|
||||
|
||||
async fetchDirectoryTokens(dirPath) {
|
||||
const listingPath = this.directoryListingPath(dirPath);
|
||||
if (this.fetchedDirs.has(listingPath)) {
|
||||
return;
|
||||
}
|
||||
this.fetchedDirs.add(listingPath);
|
||||
try {
|
||||
let listing;
|
||||
if (getters.isShare()) {
|
||||
listing = await resourcesApi.fetchFilesPublic(
|
||||
listingPath,
|
||||
state.shareInfo.hash,
|
||||
"",
|
||||
false,
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
listing = await resourcesApi.fetchFiles(
|
||||
this.fbdata.source,
|
||||
listingPath,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
}
|
||||
if (listing?.type === "directory" && listing.items?.length) {
|
||||
this.indexViewTokens(listing.items);
|
||||
}
|
||||
} catch {
|
||||
// Missing or inaccessible directories are ignored.
|
||||
}
|
||||
},
|
||||
|
||||
async prefetchAssetViewTokens() {
|
||||
/**
|
||||
* Resolve the single source-scoped view token used for this model and all of
|
||||
* its external assets. Refreshes it if it is near expiry.
|
||||
*/
|
||||
async ensureModelViewToken() {
|
||||
const viewIdentity = requestViewIdentity(state.req);
|
||||
let token = "";
|
||||
try {
|
||||
const token = await ensureViewToken(this.fbdata.source);
|
||||
token = await ensureViewToken(this.fbdata.source);
|
||||
if (token && requestViewIdentity(state.req) === viewIdentity) {
|
||||
mutations.setRequestViewToken(token);
|
||||
if (this.fbdata.path) {
|
||||
this.viewTokenByPath[this.normalizeAssetPath(this.fbdata.path)] = token;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Failed to refresh view token for 3D preview:", err);
|
||||
}
|
||||
this.indexViewTokens(this.fbdata.parentDirItems);
|
||||
if (this.fbdata.path && this.fbdata.viewToken) {
|
||||
this.viewTokenByPath[this.normalizeAssetPath(this.fbdata.path)] = this.fbdata.viewToken;
|
||||
}
|
||||
|
||||
const modelDir = removeLastDir(this.fbdata.path);
|
||||
await this.fetchDirectoryTokens(modelDir);
|
||||
if (this.fbdata.parentDirItems?.some((item) => item.name === "textures" && item.type === "directory")) {
|
||||
await this.fetchDirectoryTokens(`${modelDir}/textures`);
|
||||
}
|
||||
this.activeViewToken = token || this.fbdata.viewToken || getCachedViewToken(this.fbdata.source) || "";
|
||||
},
|
||||
|
||||
resolveViewTokenForPath(filePath) {
|
||||
const normalizedPath = this.normalizeAssetPath(filePath);
|
||||
const cachedToken = getObjectProperty(this.viewTokenByPath, normalizedPath);
|
||||
if (cachedToken) {
|
||||
return cachedToken;
|
||||
}
|
||||
if (
|
||||
this.normalizeAssetPath(this.fbdata.path) === normalizedPath &&
|
||||
this.fbdata.viewToken
|
||||
) {
|
||||
return this.fbdata.viewToken;
|
||||
}
|
||||
const items = this.fbdata.parentDirItems;
|
||||
if (!items?.length) {
|
||||
return getCachedViewToken(this.fbdata.source);
|
||||
}
|
||||
|
||||
const exact = items.find(
|
||||
(item) => this.normalizeAssetPath(item.path) === normalizedPath,
|
||||
);
|
||||
if (exact?.viewToken) {
|
||||
return exact.viewToken;
|
||||
}
|
||||
|
||||
const fileDir = removeLastDir(normalizedPath);
|
||||
const name = normalizedPath.split("/").filter(Boolean).pop();
|
||||
if (!name) {
|
||||
return getCachedViewToken(this.fbdata.source);
|
||||
}
|
||||
|
||||
const sibling = items.find((item) => {
|
||||
if (item.name !== name) {
|
||||
return false;
|
||||
}
|
||||
if (item.path) {
|
||||
return removeLastDir(this.normalizeAssetPath(item.path)) === fileDir;
|
||||
}
|
||||
return fileDir === removeLastDir(this.fbdata.path);
|
||||
});
|
||||
return sibling?.viewToken ?? getCachedViewToken(this.fbdata.source);
|
||||
resolveViewToken() {
|
||||
return this.activeViewToken || this.fbdata.viewToken || getCachedViewToken(this.fbdata.source) || "";
|
||||
},
|
||||
|
||||
/** Map a loader-emitted asset URL to a view URL; passthrough for blob:, data:, external. */
|
||||
resolveTextureUrl(url) {
|
||||
if (!url) {
|
||||
const filePath = resolveAssetFilePath(url, {
|
||||
modelPath: this.fbdata.path,
|
||||
parentDirItems: this.fbdata.parentDirItems,
|
||||
});
|
||||
if (!filePath) {
|
||||
return url;
|
||||
}
|
||||
if (url.startsWith("blob:") || url.startsWith("data:")) {
|
||||
return url;
|
||||
}
|
||||
if (
|
||||
url.includes("/api/media/stream?") ||
|
||||
url.includes("/api/resources/view?") ||
|
||||
url.includes("/api/resources/download?")
|
||||
) {
|
||||
try {
|
||||
const parsed = new URL(url, window.origin);
|
||||
const filePath = parsed.searchParams.get("file") || parsed.searchParams.getAll("file")[0];
|
||||
if (filePath) {
|
||||
return this.resourceViewUrl(filePath);
|
||||
}
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
const cleanUrl = url.split(/[?#]/)[0];
|
||||
let relativePath;
|
||||
if (cleanUrl.includes("/api/resources/")) {
|
||||
relativePath = cleanUrl.split("/api/resources/").pop() || "";
|
||||
} else if (/^https?:\/\//i.test(cleanUrl)) {
|
||||
return url;
|
||||
} else {
|
||||
relativePath = cleanUrl;
|
||||
}
|
||||
|
||||
relativePath = relativePath.replace(/^\/+/, "");
|
||||
const filename = relativePath.split("/").pop();
|
||||
if (!filename) {
|
||||
return url;
|
||||
}
|
||||
|
||||
const modelDir = removeLastDir(this.fbdata.path);
|
||||
let texturePath;
|
||||
if (relativePath.includes("/")) {
|
||||
texturePath = resolveRelativePath(this.fbdata.path, relativePath);
|
||||
} else if (this.fbdata.parentDirItems?.some((item) => item.name === filename)) {
|
||||
texturePath = `${modelDir}/${filename}`;
|
||||
} else {
|
||||
texturePath = `${modelDir}/textures/${filename}`;
|
||||
}
|
||||
return this.resourceViewUrl(texturePath);
|
||||
return this.resourceViewUrl(filePath);
|
||||
},
|
||||
|
||||
async loadModel() {
|
||||
await this.prefetchAssetViewTokens();
|
||||
await this.ensureModelViewToken();
|
||||
if (!this.modelUrl) {
|
||||
this.handleError(new Error("No view token available for model"), "Failed to load model");
|
||||
return;
|
||||
@@ -659,7 +525,10 @@ export default {
|
||||
// Remove trailing slash if present before replacing extension
|
||||
const cleanPath = this.fbdata.path.replace(/\/$/, '');
|
||||
const mtlPath = cleanPath.replace(/\.obj$/i, '.mtl');
|
||||
const mtlUrl = this.resourceViewUrl(mtlPath);
|
||||
const mtlName = mtlPath.split("/").pop();
|
||||
// Skip the .mtl request when the directory listing proves it does not exist.
|
||||
// Note: this assumes mtllib names the .mtl by basename; a differing mtllib name will still fall back gracefully.
|
||||
const mtlUrl = hasSiblingFile(this.fbdata.parentDirItems, mtlName) ? this.resourceViewUrl(mtlPath) : "";
|
||||
if (!mtlUrl) {
|
||||
this.doLoad(loader);
|
||||
return;
|
||||
@@ -711,7 +580,8 @@ export default {
|
||||
// Format specifics
|
||||
if (ext === '3mf') object.rotation.set(-Math.PI / 2, 0, 0);
|
||||
|
||||
if (['stl', 'ply', 'amf'].includes(ext)) {
|
||||
// AMFLoader returns a Group with its own materials, so only geometry-only formats are wrapped.
|
||||
if (['stl', 'ply'].includes(ext)) {
|
||||
const material = new MeshStandardMaterial({
|
||||
color: 0x4fc3f7,
|
||||
flatShading: ext === 'stl',
|
||||
@@ -755,7 +625,6 @@ export default {
|
||||
const mats = Array.isArray(child.material) ? child.material : [child.material];
|
||||
for (const m of mats) {
|
||||
m.side = DoubleSide;
|
||||
if (child.isSkinnedMesh) m.skinning = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -871,7 +740,12 @@ export default {
|
||||
this.model.traverse((c) => {
|
||||
if (c.geometry) c.geometry.dispose();
|
||||
if (c.material) {
|
||||
for (const m of [].concat(c.material)) { m.dispose(); }
|
||||
for (const m of [].concat(c.material)) {
|
||||
for (const slot of TEXTURE_SLOTS) {
|
||||
m[slot]?.dispose?.();
|
||||
}
|
||||
m.dispose();
|
||||
}
|
||||
}
|
||||
});
|
||||
this.model = null;
|
||||
@@ -889,8 +763,7 @@ export default {
|
||||
},
|
||||
|
||||
reinit() {
|
||||
this.viewTokenByPath = {};
|
||||
this.fetchedDirs = new Set();
|
||||
this.activeViewToken = "";
|
||||
this.cleanup();
|
||||
this.initScene();
|
||||
void this.loadModel();
|
||||
|
||||
Reference in new issue
Block a user