/* This file is part of Ezra Bible App.
Copyright (C) 2019 - 2026 Ezra Bible App Development Team <contact@ezrabibleapp.net>
Ezra Bible App is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
Ezra Bible App is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Ezra Bible App. See the file LICENSE.
If not, see <http://www.gnu.org/licenses/>. */
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { DOMParser } = require('@xmldom/xmldom');
const RemoteFileSync = require('./remote_file_sync.js');
const DAV_NS = 'DAV:';
const DEFAULT_FOLDER_NAME = 'EzraBibleApp';
const PROPFIND_BODY = '<?xml version="1.0" encoding="utf-8"?>' +
'<d:propfind xmlns:d="DAV:"><d:prop>' +
'<d:getlastmodified/><d:getcontentlength/><d:getetag/><d:resourcetype/>' +
'</d:prop></d:propfind>';
function normalizeEtag(etag) {
if (etag == null) {
return null;
}
return etag.trim().replace(/^W\//, '');
}
function sha256(buffer) {
return crypto.createHash('sha256').update(buffer).digest('hex');
}
/**
* Synchronizes a file with a Nextcloud (or any WebDAV) server using HTTP Basic authentication.
*
* WebDAV has no standard content hash, so "in sync" is determined by comparing the remote ETag
* and the local SHA-256 hash with the values recorded after the last successful transfer
* (see getSyncState(), persisted by the caller).
*/
class NextcloudSync extends RemoteFileSync {
static buildDavRoot(serverUrl, username) {
const trimmed = (serverUrl || '').trim();
const url = new URL(trimmed);
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
throw new Error(`Unsupported protocol in Nextcloud URL: ${url.protocol}`);
}
if (!url.hostname) {
throw new Error('Nextcloud URL has no host');
}
let pathname = url.pathname;
if (pathname.indexOf('/remote.php/') === -1) {
pathname = pathname.replace(/\/+$/, '') + '/remote.php/dav/files/' + encodeURIComponent(username) + '/';
} else if (!pathname.endsWith('/')) {
pathname += '/';
}
return url.origin + pathname;
}
constructor(serverUrl, username, password, options = {}) {
super();
this.providerName = 'Nextcloud';
this.davRoot = NextcloudSync.buildDavRoot(serverUrl, username);
this._authHeader = 'Basic ' + Buffer.from(`${username}:${password}`, 'utf8').toString('base64');
this._fetch = options.fetch || require('isomorphic-fetch');
this._folderSegments = (options.folderName || DEFAULT_FOLDER_NAME).split('/').filter(s => s.length > 0);
const syncState = options.syncState || {};
this._syncState = {
etag: syncState.etag || null,
localHash: syncState.localHash || null
};
}
getSyncState() {
return { ...this._syncState };
}
resolveRemoteUrl(remotePath) {
const fileSegments = remotePath.split('/').filter(s => s.length > 0);
const segments = this._folderSegments.concat(fileSegments);
return this.davRoot + segments.map(encodeURIComponent).join('/');
}
// ---------- HTTP ----------
async _rawRequest(method, url, { headers = {}, body = undefined, acceptStatus = [] } = {}) {
let response;
try {
response = await this._fetch(url, {
method,
headers: { Authorization: this._authHeader, ...headers },
body
});
} catch (e) {
// Normalize network error codes (Node's built-in fetch nests them in e.cause)
if (!e.code && e.cause && e.cause.code) {
e.code = e.cause.code;
}
throw e;
}
if (response.ok || acceptStatus.includes(response.status)) {
return response;
}
const error = new Error(`${method} ${url} failed with HTTP status ${response.status}`);
error.status = response.status;
const retryAfter = response.headers && response.headers.get ? response.headers.get('retry-after') : null;
if (retryAfter) {
error.headers = { 'retry-after': retryAfter };
}
throw error;
}
_request(method, url, options) {
return this._withRetry(() => this._rawRequest(method, url, options), `WebDAV ${method}`);
}
async _propfind(url) {
const response = await this._request('PROPFIND', url, {
headers: { Depth: '0', 'Content-Type': 'application/xml; charset=utf-8' },
body: PROPFIND_BODY
});
return await response.text();
}
_parsePropfind(xml) {
const doc = new DOMParser().parseFromString(xml, 'text/xml');
const firstText = (localName) => {
const nodes = doc.getElementsByTagNameNS(DAV_NS, localName);
return nodes.length > 0 ? nodes[0].textContent : null;
};
const size = firstText('getcontentlength');
const modified = firstText('getlastmodified');
return {
size: size != null ? parseInt(size, 10) : 0,
modified: modified != null ? new Date(modified) : new Date(0),
etag: normalizeEtag(firstText('getetag'))
};
}
async _ensureFolder() {
let url = this.davRoot;
for (const segment of this._folderSegments) {
url += encodeURIComponent(segment) + '/';
// 405 Method Not Allowed = collection already exists
await this._request('MKCOL', url, { acceptStatus: [405] });
}
}
/**
* Remember the remote ETag and local hash after a successful transfer.
* Falls back to a PROPFIND if the server did not send an ETag header.
*/
async _recordSyncState(response, remotePath, content) {
let etag = normalizeEtag(response.headers.get('etag'));
if (!etag) {
const info = await this.getRemoteFileInfo(remotePath);
etag = info ? info.etag : null;
}
this._syncState = { etag, localHash: sha256(content) };
}
// ---------- RemoteFileSync primitives ----------
async testAuthentication() {
await this._propfind(this.davRoot);
}
/**
* @typedef {object} ConnectionTestResult
* @property {boolean} success
* @property {string} [errorKey]
*/
/**
* Check whether the server is reachable with the configured credentials.
* @returns {Promise<ConnectionTestResult>}
*/
async testConnection() {
try {
await this.testAuthentication();
return { success: true };
} catch (e) {
let errorKey = 'cloud-sync.nextcloud-connection-failed';
if (e.status === 401 || e.status === 403) {
errorKey = 'cloud-sync.nextcloud-auth-failed';
} else if (e.status === 404) {
errorKey = 'cloud-sync.nextcloud-not-found';
}
console.log(`Nextcloud connection test failed: ${e.status || e.code || e.message}`);
return { success: false, errorKey };
}
}
async listFolderEntries(remotePath) {
const requestedPath = '/' + remotePath.split('/').filter(s => s.length > 0).join('/');
const folderUrl = this.resolveRemoteUrl(remotePath).replace(/\/*$/, '/');
let xml;
try {
const response = await this._request('PROPFIND', folderUrl, {
headers: { Depth: '1', 'Content-Type': 'application/xml; charset=utf-8' },
body: PROPFIND_BODY
});
xml = await response.text();
} catch (e) {
if (e.status === 404) {
e.notFound = true;
}
throw e;
}
// Entry paths are returned relative to the app folder, like the paths accepted by downloadFile()
const basePath = decodeURIComponent(new URL(this.resolveRemoteUrl('')).pathname).replace(/\/+$/, '');
const doc = new DOMParser().parseFromString(xml, 'text/xml');
const responses = doc.getElementsByTagNameNS(DAV_NS, 'response');
const entries = [];
for (let i = 0; i < responses.length; i++) {
const response = responses[i];
const hrefNodes = response.getElementsByTagNameNS(DAV_NS, 'href');
if (hrefNodes.length === 0) {
continue;
}
const hrefPath = decodeURIComponent(new URL(hrefNodes[0].textContent.trim(), this.davRoot).pathname).replace(/\/+$/, '');
if (!hrefPath.startsWith(basePath + '/')) {
continue;
}
const entryPath = hrefPath.substring(basePath.length);
if (entryPath === requestedPath) {
// The requested folder itself
continue;
}
const sizeNodes = response.getElementsByTagNameNS(DAV_NS, 'getcontentlength');
const size = sizeNodes.length > 0 ? parseInt(sizeNodes[0].textContent, 10) : 0;
entries.push({
name: entryPath.substring(entryPath.lastIndexOf('/') + 1),
path: entryPath,
isFolder: response.getElementsByTagNameNS(DAV_NS, 'collection').length > 0,
size: isNaN(size) ? 0 : size
});
}
return entries;
}
async getRemoteFileInfo(remotePath) {
try {
const xml = await this._propfind(this.resolveRemoteUrl(remotePath));
return this._parsePropfind(xml);
} catch (e) {
if (e.status === 404) {
return null;
}
throw e;
}
}
async uploadFile(localPath, remotePath) {
let content;
try {
content = fs.readFileSync(localPath);
} catch (err) {
throw new Error(`Failed to read file ${localPath} for upload: ${err.message}`);
}
await this._ensureFolder();
const response = await this._request('PUT', this.resolveRemoteUrl(remotePath), {
headers: { 'Content-Type': 'application/octet-stream' },
body: content
});
await this._recordSyncState(response, remotePath, content);
}
async downloadFile(remotePath, destinationDir) {
const response = await this._request('GET', this.resolveRemoteUrl(remotePath));
const content = Buffer.from(await response.arrayBuffer());
const destFilePath = path.join(destinationDir, path.basename(remotePath));
try {
fs.writeFileSync(destFilePath, content);
} catch (err) {
throw new Error(`Failed to write downloaded file to ${destFilePath}: ${err.message}`);
}
await this._recordSyncState(response, remotePath, content);
}
async isFileSynced(localFilePath, remotePath) {
if (!fs.existsSync(localFilePath)) {
throw new Error(`File ${localFilePath} does not exist!`);
}
const remoteInfo = await this.getRemoteFileInfo(remotePath);
if (remoteInfo == null || !this._syncState.etag || !this._syncState.localHash) {
return false;
}
if (remoteInfo.etag !== this._syncState.etag) {
return false;
}
const localHash = await this.getLocalFileHash(localFilePath);
return localHash === this._syncState.localHash;
}
async getLocalFileHash(fileName) {
const hasher = crypto.createHash('sha256');
const stream = fs.createReadStream(fileName);
return new Promise((resolve, reject) => {
stream.on('data', (buf) => hasher.update(buf));
stream.on('end', () => resolve(hasher.digest('hex')));
stream.on('error', (err) => reject(new Error('Error reading from file: ' + err)));
});
}
}
module.exports = NextcloudSync;
Source