30 lines
1.2 KiB
JavaScript
30 lines
1.2 KiB
JavaScript
// Nextcloud exposes the per-user WebDAV tree under this fixed prefix.
|
|
const DAV_FILES_ROOT = 'remote.php/dav/files'
|
|
|
|
// Builds the absolute WebDAV URL of a resource owned by `username`.
|
|
// `path` is relative to that user's root, e.g. 'Tofu/plannings/2026-W38.json'.
|
|
// An empty path yields the user root, with its trailing slash (a collection URL).
|
|
export function buildDavUrl({ serverUrl, username, path }) {
|
|
const origin = normalizeServerUrl(serverUrl)
|
|
const user = encodeURIComponent(String(username ?? '').trim())
|
|
return `${origin}/${DAV_FILES_ROOT}/${user}/${encodePath(path)}`
|
|
}
|
|
|
|
// Accepts what a user actually types: no scheme, or a trailing slash, or both.
|
|
// A server reachable only in http (a local instance) keeps its scheme.
|
|
function normalizeServerUrl(serverUrl) {
|
|
const trimmed = String(serverUrl ?? '').trim().replace(/\/+$/, '')
|
|
if (trimmed === '') return ''
|
|
if (/^https?:\/\//i.test(trimmed)) return trimmed
|
|
return `https://${trimmed}`
|
|
}
|
|
|
|
// Each segment is encoded on its own so the separators stay separators:
|
|
// spaces and accents become percent-escapes, slashes do not.
|
|
function encodePath(path) {
|
|
return String(path ?? '')
|
|
.split('/')
|
|
.filter(Boolean)
|
|
.map((segment) => encodeURIComponent(segment))
|
|
.join('/')
|
|
}
|