Source

frontend/controllers/cloud_sync/custom_module_repo_controller.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/>. */

/**
 * Manages custom cloud module repository controls, validation and settings.
 * It debounces path validation and caches results for the selected provider
 * and configuration.
 */
class CustomModuleRepoController {
  constructor(context) {
    this.context = context;
    this.debounceTimer = null;
    this.lastValidationKey = null;
    this.lastValidationResult = null;
  }

  bindEvents() {
    $('#use-custom-module-repo').bind('change', () => {
      this.updateVisibility();
    });

    $('#custom-module-repo-folder').bind('input', () => {
      this.schedule();
    });

    $('#custom-module-repo-folder').bind('blur', async () => {
      this.clearDebounce();

      if (this.shouldValidate()) {
        await this.validate(this.getSelectedPath());
      }
    });

    $('#validate-custom-repo-button').bind('click', async () => {
      this.reset();

      if (this.shouldValidate()) {
        await this.validate(this.getSelectedPath());
      }
    });
  }

  clearDebounce() {
    clearTimeout(this.debounceTimer);
  }

  reset() {
    clearTimeout(this.debounceTimer);
    this.lastValidationKey = null;
    this.lastValidationResult = null;

    if (document.getElementById('use-custom-module-repo').checked) {
      this.hideStatus();
    }
  }

  getSelectedPath() {
    return document.getElementById('custom-module-repo-folder').value;
  }

  shouldValidate() {
    const useCustomModuleRepo = document.getElementById('use-custom-module-repo').checked;
    const customModuleRepo = this.getSelectedPath();

    return useCustomModuleRepo &&
           this.context.isSelectedStorageAvailable() &&
           customModuleRepo && customModuleRepo.trim() !== '';
  }

  schedule() {
    this.reset();

    if (this.shouldValidate()) {
      this.debounceTimer = setTimeout(async () => {
        await this.validate(this.getSelectedPath());
      }, 1000);
    }
  }

  async revalidate() {
    this.reset();

    if (this.shouldValidate()) {
      await this.validate(this.getSelectedPath());
    }
  }

  getSettingsOverride() {
    const provider = this.context.getSelectedProvider();
    const adapter = this.context.getProviderAdapter(provider);
    return adapter ? adapter.getSettingsOverride() : { cloudSyncProvider: provider };
  }

  getValidationKey(customModuleRepo, settingsOverride) {
    return JSON.stringify({ customModuleRepo, ...settingsOverride });
  }

  isValidated(customModuleRepo) {
    return this.lastValidationResult !== null &&
           this.lastValidationResult.valid &&
           this.lastValidationKey === this.getValidationKey(customModuleRepo, this.getSettingsOverride());
  }

  showLoading() {
    document.getElementById('custom-repo-validation-loading').style.display = 'block';
    document.getElementById('custom-repo-validation-status').style.visibility = 'hidden';
    this.context.setSaveButtonEnabled(false);
  }

  hideLoading() {
    document.getElementById('custom-repo-validation-loading').style.display = 'none';
  }

  showStatus(type, errorKey, errorParams) {
    const status = document.getElementById('custom-repo-validation-status');
    status.textContent = '';
    status.style.visibility = 'visible';
    status.classList.remove('success', 'failed');

    if (type === 'success') {
      status.textContent = '✓ ' + i18n.t('cloud-sync.repo-validation-success');
      status.classList.add('success');
      this.context.setSaveButtonEnabled(true);
    } else {
      status.textContent = '✗ ' + i18n.t(errorKey, errorParams || {});
      status.classList.add('failed');
      this.context.setSaveButtonEnabled(false);
    }
  }

  hideStatus() {
    const status = document.getElementById('custom-repo-validation-status');
    status.textContent = '';
    status.style.visibility = 'hidden';
    status.classList.remove('success', 'failed');
    this.context.setSaveButtonEnabled(true);
  }

  async validate(customModuleRepo) {
    const settingsOverride = this.getSettingsOverride();
    const validationKey = this.getValidationKey(customModuleRepo, settingsOverride);

    if (this.lastValidationKey === validationKey && this.lastValidationResult !== null) {
      if (this.lastValidationResult.valid) {
        this.showStatus('success');
      } else {
        this.showStatus('error', this.lastValidationResult.errorKey, this.lastValidationResult.errorParams);
      }
      return this.lastValidationResult;
    }

    this.showLoading();

    try {
      const result = await ipcNsi.validateCustomModuleRepo(customModuleRepo, settingsOverride);
      this.hideLoading();

      if (!result.valid) {
        this.showStatus('error', result.errorKey, result.errorParams);
      } else {
        this.showStatus('success');
      }

      this.lastValidationKey = validationKey;
      this.lastValidationResult = result;
      return result;
    } catch (error) {
      this.hideLoading();
      const result = {
        valid: false,
        errorKey: 'cloud-sync.repo-validation-error-unknown',
        errorParams: { error: error.message }
      };
      this.showStatus('error', result.errorKey, result.errorParams);
      this.lastValidationKey = validationKey;
      this.lastValidationResult = result;
      return result;
    }
  }

  async validateBeforeSave() {
    const useCustomModuleRepo = document.getElementById('use-custom-module-repo').checked;

    if (useCustomModuleRepo && this.context.isSelectedStorageAvailable()) {
      const result = await this.validate(this.getSelectedPath());
      return result.valid;
    }

    return true;
  }

  async saveSettings() {
    const useCustomModuleRepo = document.getElementById('use-custom-module-repo').checked &&
                               this.context.isSelectedStorageAvailable();
    let customModuleRepo = this.getSelectedPath();

    if (!customModuleRepo) {
      customModuleRepo = 'custom_module_repo';
    }

    await ipcSettings.set('cloudSyncUseCustomModuleRepo', useCustomModuleRepo);
    await ipcSettings.set('cloudSyncCustomModuleRepo', customModuleRepo);

    const validated = useCustomModuleRepo && this.isValidated(customModuleRepo);
    await ipcSettings.set('cloudSyncCustomModuleRepoValidated', validated);
  }

  updateVisibility() {
    const useCustomModuleRepo = document.getElementById('use-custom-module-repo').checked;
    const settings = document.getElementById('custom-module-repo-settings');

    if (useCustomModuleRepo) {
      settings.style.display = 'block';
    } else {
      settings.style.display = 'none';
      this.hideStatus();
      this.context.setSaveButtonEnabled(true);
    }
  }
}

module.exports = CustomModuleRepoController;