Example-flows + noder: defaults pekar bara på filer som finns

Flöden (flows/example-flows.json):
- Kedjor som skapar det de behöver: png→asset, templates:list→create→
  extract/fill/transform/extractFields, create A+B→compareVersionsPdf
- Defaults /Dokument/Example.md, /Dokument/exempel.odt, dest
  /Dokument/OfficeOut/, mall-id 230 (Invoice.odt via templates:list)
- Ingen referens till /Mallar/avtal.docx, avtal-ny.docx eller logotyp.png
- Debug-noder med tostatus=false (undviker TypeError-length i status)

Noder:
- nc-office templates:create: skickar path+template (richdocuments-
  kontrakt), ärver extension från mallen, MKCOL av mapp, idempotent
  (återanvänd existerande fil i stället för 'namn (2)') — fixar OCS 400
- nc-office document:direct: fileId camelCase (+fileid), 996-fel
  inkluderar nu OCS-body i felmeddelandet
- collabora-wopi discovery: rewrite urlsrc/favIconUrl till
  collaboraPublicUrl så iframe inte går mot CODE bridge-IP
- webdavGet/PROPFIND 404: feltext med föreslagen åtgärd
- resolveDestNcPath: tvingar rätt filändelse (.pdf/.png/…)
- Nytt: listUserExamples (PROPFIND /Dokument+/Documents) +
  bridge-op pickDemoSource; scripts/discover-examples.js

Verifierat mot cloud.domain.name (your-user): capabilities, discovery-
rewrite, pdf/png, asset-länk, mall-skapa+extract/fill/transform,
compare A/B→pdf, document:direct, htmlToOffice — ALL PASS.
This commit is contained in:
dev
2026-08-22 22:50:47 +02:00
parent 5ca7b4d4e0
commit 5ee179539e
11 changed files with 801 additions and 69 deletions
+23 -1
View File
@@ -1,6 +1,6 @@
'use strict';
const { webdavGet, webdavPut, webdavPropfindFileId } = require('./webdav');
const { webdavGet, webdavPut, webdavPropfindFileId, listUserExamples } = require('./webdav');
const { ocsRequest } = require('./ocs');
const { requestBuffer } = require('./http-client');
const { convertTo, extractStructure, transformStructure } = require('./collabora');
@@ -50,6 +50,27 @@ async function loadSourceBuffer(config, msg) {
return file;
}
// Bridge-op "pickDemoSource": slå upp en fil som FAKTISKT finns hos användaren
// (/Dokument först, sedan /Documents) och lägg den på msg.ncPath. Endast för
// demo/generator-flöden — ingen silent fallback inne i convert-operationer.
async function pickDemoSource(config, msg) {
const examples = await listUserExamples(config);
if (!examples.length) {
throw new Error(
'Ingen exempelfil hittad i /Dokument eller /Documents — ladda upp en .md/.odt/.docx ' +
'eller ange msg.ncPath manuellt.'
);
}
msg.demoSources = examples.map((e) => e.ncPath);
if (!pickMsgField(msg, 'ncPath')) {
msg.ncPath = examples[0].ncPath;
}
return {
payload: examples,
picked: msg.ncPath
};
}
async function saveResult(config, msg, buffer, format, sourceNcPath) {
const destNcPath = assertSafeDestination(
resolveDestNcPath(msg, sourceNcPath, format),
@@ -266,6 +287,7 @@ module.exports = {
compareVersionsPdf,
extractToPayload,
createAssetLink,
pickDemoSource,
loadSourceBuffer,
saveResult,
resolveFileId
+17 -5
View File
@@ -24,10 +24,13 @@ function parseOcsBody(bodyBuffer) {
const json = JSON.parse(text);
const ocs = json.ocs || json;
const meta = ocs.meta || {};
const statuscode = meta.statuscode ?? meta.statusCode ?? 200;
const statuscode = Number(meta.statuscode ?? meta.statusCode ?? 200);
if (statuscode >= 400) {
const message = meta.message || meta.status || text.slice(0, 200);
throw new Error(`OCS ${statuscode}: ${message}`);
// 996 = intern serverfel, 998 = not found m.m. — inkludera alltid
// OCS-bodyn så felet går att felsöka utan logggrävning.
const message = meta.message || meta.status || '';
const raw = text.slice(0, 300);
throw new Error(`OCS ${statuscode}: ${message}${message && raw !== message ? ` (${raw})` : raw}`);
}
return {
statusCode: statuscode,
@@ -38,7 +41,7 @@ function parseOcsBody(bodyBuffer) {
if (err.message.startsWith('OCS ')) {
throw err;
}
throw new Error(`OCS-svar kunde inte parsas: ${text.slice(0, 200)}`);
throw new Error(`OCS-svar kunde inte parsas (HTTP-body): ${text.slice(0, 200)}`);
}
}
@@ -77,9 +80,18 @@ async function ocsRequest(config, { method = 'GET', path, query, body, headers =
throw new Error(`OCS ${res.statusCode}: kontrollera app-lösenord`);
}
// OCS-fel (996/998/…) kommer med HTTP 4xx/5xx men har parsbar meta-body —
// försök alltid parsa först så felet innehåller OCS-meddelandet.
const parsed = parseOcsBody(res.body);
if (res.statusCode < 200 || res.statusCode >= 300) {
const bodyText = res.body.toString('utf8').slice(0, 200);
throw new Error(`OCS-anrop misslyckades (HTTP ${res.statusCode}) för ${path}: ${bodyText || '<tom body>'}`);
}
return {
httpStatus: res.statusCode,
...parseOcsBody(res.body)
...parsed
};
}
+6 -1
View File
@@ -60,7 +60,12 @@ function resolveDestNcPath(msg, sourceNcPath, format) {
if (msg.destFolder || msg.destName) {
const folder = normalizeNcPath(msg.destFolder || DEFAULT_OUTPUT_FOLDER);
const folderWithSlash = folder.endsWith('/') ? folder : folder + '/';
const name = msg.destName || replaceExtension(basenameFromNcPath(sourceNcPath), format || 'bin');
let name = msg.destName || replaceExtension(basenameFromNcPath(sourceNcPath), format || 'bin');
// Rätt filändelse tvingas in — annars landar filer utan ändelse i NC.
const fmt = String(format || '').toLowerCase();
if (fmt && !new RegExp(`\\.${fmt}$`, 'i').test(name)) {
name = replaceExtension(name, fmt);
}
return normalizeNcPath(folderWithSlash + name);
}
return defaultDestNcPath(sourceNcPath, format);
+82 -2
View File
@@ -41,7 +41,11 @@ async function webdavGet(config, ncPath) {
});
if (res.statusCode === 404) {
throw new Error(`WebDAV 404: filen finns inte: ${normalizeNcPath(ncPath)}`);
throw new Error(
`WebDAV 404: filen finns inte: ${normalizeNcPath(ncPath)} — ` +
'ange msg.ncPath till en fil som finns; defaults är /Dokument/Example.md ' +
'eller en mall via templates:list (se bridge-op pickDemoSource).'
);
}
if (res.statusCode === 401 || res.statusCode === 403) {
throw new Error(`WebDAV ${res.statusCode}: kontrollera app-lösenord och användare`);
@@ -134,6 +138,12 @@ async function webdavPropfindFileId(config, ncPath) {
rejectUnauthorized: tlsOptions(config).rejectUnauthorized
});
if (res.statusCode === 404) {
throw new Error(
`PROPFIND 404: ${normalizeNcPath(ncPath)} finns inte — ` +
'ange msg.ncPath till en fil som finns (t.ex. /Dokument/Example.md).'
);
}
if (res.statusCode < 200 || res.statusCode >= 300) {
throw new Error(`PROPFIND misslyckades (${res.statusCode}) för ${normalizeNcPath(ncPath)}`);
}
@@ -146,10 +156,80 @@ async function webdavPropfindFileId(config, ncPath) {
return parseInt(match[1], 10);
}
// Discovery av riktiga defaults: PROPFIND /Dokument och /Documents (Depth 1),
// returnera kandidater (.md/.odt/.docx) i prioritetsordning. Används BARA av
// example-flow-generator / bridge-op pickDemoSource — aldrig inne i convert.
async function listUserExamples(config, folders) {
const candidates = folders || ['/Dokument', '/Documents'];
const found = [];
const wanted = /\.(md|odt|docx)$/i;
for (const folder of candidates) {
let res;
try {
res = await requestBuffer({
url: webDavUrl(config, folder),
method: 'PROPFIND',
headers: {
Authorization: authHeader(config),
Depth: '1',
'Content-Type': 'application/xml; charset=utf-8'
},
body: '<?xml version="1.0" encoding="UTF-8"?><d:propfind xmlns:d="DAV:"/>',
rejectUnauthorized: tlsOptions(config).rejectUnauthorized
});
} catch (err) {
continue; // mapp finns ej — prova nästa
}
if (res.statusCode < 200 || res.statusCode >= 300) {
continue;
}
const text = res.body.toString('utf8');
const responses = text.split('<d:response>').slice(1);
for (const chunk of responses) {
const hrefMatch = chunk.match(/<d:href>([^<]+)<\/d:href>/i);
if (!hrefMatch) {
continue;
}
let href;
try {
href = decodeURIComponent(hrefMatch[1]);
} catch {
href = hrefMatch[1];
}
// href: /remote.php/dav/files/<user>/Dokument/exempel.odt → ncPath
const marker = `/files/${config.username}/`;
const idx = href.indexOf(marker);
if (idx === -1) {
continue;
}
const ncPath = normalizeNcPath(href.substring(idx + marker.length));
if (!wanted.test(ncPath)) {
continue;
}
const isCollection = /<d:collection\s*\/?>/i.test(chunk);
if (isCollection) {
continue;
}
found.push({ ncPath, folder: normalizeNcPath(folder), name: filenameFromPath(ncPath) });
}
}
const priority = { md: 0, odt: 1, docx: 2 };
found.sort((a, b) => {
const extA = a.ncPath.split('.').pop().toLowerCase();
const extB = b.ncPath.split('.').pop().toLowerCase();
return (priority[extA] ?? 9) - (priority[extB] ?? 9);
});
return found;
}
module.exports = {
webDavUrl,
webdavGet,
webdavPut,
webdavPropfindFileId,
ensureFolder
ensureFolder,
listUserExamples
};