Source

frontend/controllers/cloud_sync/cloud_sync_config_helper.js

/* 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/>. */

/**
 * Pure helpers backing the "Setup cloud sync" dialog.
 * @module cloudSyncConfigHelper
 * @category Helper
 */

// Settings that describe the history of the last sync with the remote.
// They are cleared whenever the remote changes (other provider, other server/account).
const SYNC_HISTORY_KEYS = [
  'lastCloudSyncResult',
  'lastCloudSyncTime',
  'lastCloudDownloadTime',
  'lastCloudUploadTime',
  'nextcloudLastSyncEtag',
  'nextcloudLastSyncLocalHash',
];

const DROPBOX_CREDENTIAL_KEYS = ['dropboxToken', 'dropboxRefreshToken', 'dropboxLinkStatus'];
const NEXTCLOUD_CREDENTIAL_KEYS = ['nextcloudUrl', 'nextcloudUsername', 'nextcloudPassword'];

function normalizeUrl(url) {
  return (url || '').trim().replace(/\/+$/, '');
}

function normalizeUsername(username) {
  return (username || '').trim();
}

/**
 * Validate the Nextcloud form fields.
 * @returns {{valid: boolean, errors: Object, warnings: string[]}} errors/warnings are i18n keys
 */
function validateNextcloudConfig({ url, username, password } = {}) {
  const errors = {};
  const warnings = [];
  const trimmedUrl = (url || '').trim();

  if (trimmedUrl === '') {
    errors.url = 'cloud-sync.nextcloud-url-required';
  } else {
    let parsed = null;

    try {
      parsed = new URL(trimmedUrl);
    } catch {
      // Invalid URL, handled below
    }

    if (parsed === null || !['http:', 'https:'].includes(parsed.protocol) || !parsed.hostname) {
      errors.url = 'cloud-sync.nextcloud-url-invalid';
    } else if (parsed.protocol === 'http:') {
      warnings.push('cloud-sync.nextcloud-insecure-http');
    }
  }

  if (normalizeUsername(username) === '') {
    errors.username = 'cloud-sync.nextcloud-username-required';
  }

  if (password === undefined || password === null || password === '') {
    errors.password = 'cloud-sync.nextcloud-password-required';
  }

  return { valid: Object.keys(errors).length === 0, errors, warnings };
}

/**
 * Compute the settings changes resulting from saving the cloud sync dialog.
 *
 * @param {Object} current - effective current values: { cloudSyncProvider, nextcloudUrl, nextcloudUsername }
 * @param {Object} form - { provider, nextcloud: {url, username, password}, onlyWifi, enableBackgroundSync, syncAfterChanges }
 * @returns {{set: Object, remove: string[]}}
 */
function buildCloudSyncSettingsUpdate(current, form) {
  const set = {
    cloudSyncProvider: form.provider,
    cloudSyncOnlyWifi: form.onlyWifi,
    cloudSyncEnableBackgroundSync: form.enableBackgroundSync,
    cloudSyncAfterChanges: form.syncAfterChanges,
  };
  const remove = [];

  const previousProvider = current.cloudSyncProvider || null;
  const providerChanged = previousProvider !== form.provider;
  let remoteChanged = providerChanged;

  if (form.provider === 'nextcloud') {
    const nextcloud = form.nextcloud || {};
    const url = normalizeUrl(nextcloud.url);
    const username = normalizeUsername(nextcloud.username);

    set.nextcloudUrl = url;
    set.nextcloudUsername = username;
    set.nextcloudPassword = nextcloud.password;

    if (!providerChanged &&
        (normalizeUrl(current.nextcloudUrl) !== url || normalizeUsername(current.nextcloudUsername) !== username)) {
      remoteChanged = true;
    }
  }

  if (providerChanged) {
    if (previousProvider === 'dropbox') {
      remove.push(...DROPBOX_CREDENTIAL_KEYS);
    } else if (previousProvider === 'nextcloud') {
      remove.push(...NEXTCLOUD_CREDENTIAL_KEYS);
    }
  }

  if (remoteChanged) {
    remove.push(...SYNC_HISTORY_KEYS);
    set.firstCloudSyncDone = false;
  }

  return { set, remove };
}

module.exports = {
  SYNC_HISTORY_KEYS,
  validateNextcloudConfig,
  buildCloudSyncSettingsUpdate,
};