"use strict"; // ================================================================ // AMPP Folder Placer — lib/ampp-folder-placer.js // // placeAsset() — original v3.5 port (filename -- parsing) // placeAssetInFolderById() — direct placement by known folder ID // listAmppFolders() — fetch AMPP virtual folder tree (probes endpoints) // amppRequest() — shared low-level REST helper // ================================================================ const PREFIX_DELIM = "--"; // ── Low-level REST helper ───────────────────────────────────────────────────── async function amppRequest(method, baseUrl, token, apiPath, body = null) { const url = `${baseUrl.replace(/\/$/, "")}/${apiPath}`; const opts = { method, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, signal: AbortSignal.timeout(15000), }; if (body !== null) { opts.body = typeof body === "string" ? body : JSON.stringify(body); } const r = await fetch(url, opts); if (!r.ok) { const text = await r.text().catch(() => ""); throw new Error( `AMPP API ${method} ${apiPath} → HTTP ${r.status}: ${text.slice(0, 200)}` ); } return r.json(); } // ── List AMPP virtual folders ──────────────────────────────────────────────── // Probes multiple candidate endpoints in order; uses the first that responds. // Returns: { folders: [{id, name, parentId, path}], endpoint } const FOLDER_LIST_CANDIDATES = [ "api/v1/store/folder/folders?limit=500", "api/v1/store/folder/folders", "api/v1/store/folder/folder/list", "api/v1/store/folder/folders/list", ]; async function listAmppFolders(baseUrl, token) { let lastError = null; for (const candidate of FOLDER_LIST_CANDIDATES) { try { const resp = await amppRequest("GET", baseUrl, token, candidate); // Normalise whatever shape AMPP returns into an array const raw = Array.isArray(resp) ? resp : resp?.["folder:list"] ?? resp?.folders ?? resp?.items ?? resp?.results ?? []; if (!Array.isArray(raw)) { console.warn(`[AMPP folders] ${candidate} returned non-array: ${typeof raw}`); continue; } const folders = raw.map((f) => ({ id: (f["folder:id"] ?? f.id ?? "").toString().trim(), name: (f["name:text"] ?? f.name ?? f["folder:name"] ?? "").toString().trim(), parentId: (f["parentFolder:id"] ?? f.parentId ?? f["parent:id"] ?? "").toString().trim(), path: (f["folder:path"] ?? f.path ?? "").toString().trim(), })).filter(f => f.id && f.name); console.log(`[AMPP folders] ${folders.length} folders via ${candidate}`); return { folders, endpoint: candidate }; } catch (err) { lastError = err; console.warn(`[AMPP folders] ${candidate} failed: ${err.message}`); } } throw new Error(`Could not list AMPP folders — all endpoints failed. Last error: ${lastError?.message}`); } // ── Direct placement by known folder ID ────────────────────────────────────── // Used by the background placement worker. No filename parsing — we already // know the folder ID from what the user selected in the UI. async function placeAssetInFolderById(baseUrl, assetId, folderId, token) { if (!assetId) throw new Error("assetId is required"); if (!folderId) throw new Error("folderId is required"); const linkBody = JSON.stringify( { "folder:id": folderId, "asset:id": assetId }, null, 0 ); await amppRequest("POST", baseUrl, token, "api/v1/store/folder/references", linkBody); return { placed: true, folderId, assetId }; } // ── Original v3.5 placement (filename -- parsing) ──────────────────────────── // Kept for the manual /api/ampp/place endpoint. async function placeAsset(baseUrl, assetName, assetId, token) { if (!assetName.includes(PREFIX_DELIM)) { return { placed: false, folderId: null, path: "", reason: `no "${PREFIX_DELIM}" delimiter in filename` }; } const parts = assetName.split(PREFIX_DELIM); if (parts.length < 2) { return { placed: false, folderId: null, path: "", reason: "fewer than 2 parts after split" }; } const folderNames = parts.slice(0, -1); let parentId = null; let currentPath = ""; let expectedDepth = 0; for (const rawName of folderNames) { const fname = rawName.trim(); if (!fname) continue; currentPath = currentPath ? `${currentPath}/${fname}` : fname; expectedDepth++; let folderId = null; try { const encoded = currentPath.split("/").map(encodeURIComponent).join("/"); const resp = await amppRequest("GET", baseUrl, token, `api/v1/store/folder/folders/hierarchy?path=${encoded}`); if (!resp || typeof resp !== "object" || Array.isArray(resp)) throw new Error(`Hierarchy resp is not an object: ${typeof resp}`); const hlist = resp["hierarchy:list"]; if (!Array.isArray(hlist)) throw new Error(`hierarchy:list is not an array: ${typeof hlist}`); if (hlist.length === expectedDepth) { const last = hlist[hlist.length - 1]; const candidateId = (last?.["folder:id"] ?? "").toString().trim(); if (candidateId) folderId = candidateId; } } catch (lookupEx) { folderId = null; console.warn(`[AMPP folder] Hierarchy lookup failed for '${currentPath}': ${lookupEx.message}`); } if (!folderId) { const createBody = { "name:text": fname }; if (parentId) createBody["parentFolders:tags"] = [parentId]; try { const fresp = await amppRequest("POST", baseUrl, token, "api/v1/store/folder/folders", createBody); if (!fresp || typeof fresp !== "object" || Array.isArray(fresp)) throw new Error(`Folder create resp is not an object: ${typeof fresp}`); const createdId = (fresp["folder:id"] ?? "").toString().trim(); if (!createdId) throw new Error("Folder create resp missing folder:id"); folderId = createdId; } catch (ex) { throw new Error(`Failed to create folder '${fname}' under path '${currentPath}': ${ex.message}`); } } parentId = folderId; } if (parentId) { const linkBody = JSON.stringify({ "folder:id": parentId, "asset:id": assetId }, null, 0); await amppRequest("POST", baseUrl, token, "api/v1/store/folder/references", linkBody); } return { placed: true, folderId: parentId, path: currentPath }; } module.exports = { placeAsset, placeAssetInFolderById, listAmppFolders, amppRequest };