Source

backend/cloud_sync/cloud_module_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/>. */


const fs = require('fs');
const path = require('path');
const syncProviderFactory = require('./sync_provider_factory.js');

/**
 * SWORD module type strings as returned by node-sword-interface.
 * These must be kept in sync with app/frontend/helpers/sword_module_helper.js
 */
const SWORD_MODULE_TYPE = {
  BIBLE: 'Biblical Texts',
  COMMENTARY: 'Commentaries',
  DICTIONARY: 'Lexicons / Dictionaries',
  IMAGES: 'Images',
  MAPS: 'Maps'
};

const USE_CUSTOM_MODULE_REPO_KEY = 'cloudSyncUseCustomModuleRepo';
const CUSTOM_MODULE_REPO_KEY = 'cloudSyncCustomModuleRepo';
const CUSTOM_MODULE_REPO_VALIDATED_KEY = 'cloudSyncCustomModuleRepoValidated';

// Settings that the frontend may override when validating a repository before the configuration is saved
const OVERRIDABLE_SETTINGS = ['cloudSyncProvider', 'nextcloudUrl', 'nextcloudUsername', 'nextcloudPassword'];

const CACHE_FILE_NAME = 'cloud_modules_cache.json';
const LEGACY_DROPBOX_CACHE_FILE_NAME = 'dropbox_modules_cache.json';
const MODS_INDEX_FILE = 'mods.d.tar.gz';

/**
 * Repository names shown in the module assistant for the custom module repository of each provider.
 */
const REPOSITORY_NAMES = {
  dropbox: 'Dropbox',
  nextcloud: 'Nextcloud'
};

function normalizeRepoPath(repoPath) {
  let normalized = (repoPath || '').trim();
  if (!normalized.startsWith('/')) normalized = '/' + normalized;
  if (normalized.endsWith('/')) normalized = normalized.slice(0, -1);
  return normalized;
}

function withOverrides(config, overrides) {
  const allowed = {};

  if (overrides) {
    OVERRIDABLE_SETTINGS.forEach(key => {
      if (Object.prototype.hasOwnProperty.call(overrides, key)) {
        allowed[key] = overrides[key];
      }
    });
  }

  if (Object.keys(allowed).length === 0) {
    return config;
  }

  return {
    get: (key, defaultValue) => Object.prototype.hasOwnProperty.call(allowed, key) ? allowed[key] : config.get(key, defaultValue),
    has: (key) => Object.prototype.hasOwnProperty.call(allowed, key) || config.has(key)
  };
}

function isNetworkError(error) {
  return error.code === 'EAI_AGAIN' || error.errno === 'EAI_AGAIN' ||
         error.code === 'ENOTFOUND' || error.code === 'ETIMEDOUT' ||
         error.code === 'ECONNREFUSED' || error.type === 'system';
}

function removeIfExisting(filePath) {
  if (fs.existsSync(filePath)) {
    fs.rmSync(filePath, { recursive: true, force: true });
  }
}

/**
 * CloudModuleHelper provides functionality for managing SWORD modules stored in the cloud storage
 * of the active cloud sync provider (Dropbox or Nextcloud).
 *
 * This helper class handles:
 * - Validation of the custom module repository structure
 * - Caching and retrieval of available modules from the custom module repository
 * - Parsing of SWORD module configuration files
 * - Installation of modules from the custom module repository to the local SWORD directory
 * - Installation of modules from arbitrary zip files in the cloud storage
 *
 * The custom repository is expected to have the following structure:
 * - /mods.d.tar.gz - Compressed archive containing mods.d directory with module configuration files
 * - /packages/ - Directory containing module installation packages (.zip files)
 *
 * Paths are relative to the app folder of the provider (/Apps/Ezra Bible App on Dropbox, /EzraBibleApp on Nextcloud).
 *
 * @class CloudModuleHelper
 */
class CloudModuleHelper {
  constructor(platformHelper, nsi, getConfig=undefined) {
    this._platformHelper = platformHelper;
    this._nsi = nsi;
    this._getConfig = getConfig || (() => global.ipc.ipcSettingsHandler.getConfig());
  }

  getActiveProvider(config=this._getConfig()) {
    return syncProviderFactory.getActiveCloudSyncProvider(config);
  }

  hasCloudStorage(config=this._getConfig()) {
    return syncProviderFactory.hasCloudStorageCredentials(config);
  }

  /**
   * @returns {string|null} The name of the custom module repository (the name of the active provider)
   */
  getRepositoryName(config=this._getConfig()) {
    const provider = this.getActiveProvider(config);
    return provider ? REPOSITORY_NAMES[provider] : null;
  }

  isCloudRepository(repositoryName) {
    return repositoryName != null && repositoryName === this.getRepositoryName();
  }

  /**
   * Checks whether a custom module repository is configured for the active provider.
   * @param {boolean} requireValidated whether the repository must have been validated successfully
   */
  isCustomModuleRepoEnabled(requireValidated=true) {
    const config = this._getConfig();

    return this.hasCloudStorage(config) &&
           !!config.get(USE_CUSTOM_MODULE_REPO_KEY, false) &&
           !!config.get(CUSTOM_MODULE_REPO_KEY, null) &&
           (!requireValidated || !!config.get(CUSTOM_MODULE_REPO_VALIDATED_KEY, false));
  }

  async _connect(config=this._getConfig()) {
    const storage = syncProviderFactory.createCloudStorageProvider(config);

    if (storage != null) {
      await storage.refreshAccessToken();
    }

    return storage;
  }

  getCacheFilePath() {
    return path.join(this._platformHelper.getUserDataPath(), CACHE_FILE_NAME);
  }

  getLegacyDropboxCacheFilePath() {
    return path.join(this._platformHelper.getUserDataPath(), LEGACY_DROPBOX_CACHE_FILE_NAME);
  }

  clearCache() {
    removeIfExisting(this.getCacheFilePath());
    removeIfExisting(this.getLegacyDropboxCacheFilePath());
  }

  /**
   * Validate the structure of a custom module repository.
   * @param {string} customModuleRepo repository folder path
   * @param {Object} settingsOverride unsaved provider settings from the configuration dialog
   *                 (cloudSyncProvider, nextcloudUrl, nextcloudUsername, nextcloudPassword)
   */
  async validateCustomModuleRepo(customModuleRepo, settingsOverride={}) {
    console.log('[CloudModuleHelper] Starting validation of custom module repo:', customModuleRepo);

    const config = withOverrides(this._getConfig(), settingsOverride);

    if (!this.hasCloudStorage(config)) {
      console.log('[CloudModuleHelper] Validation failed: Cloud storage not configured');
      return { valid: false, errorKey: 'cloud-sync.repo-validation-error-not-configured' };
    }

    if (!customModuleRepo || customModuleRepo.trim() === '') {
      console.log('[CloudModuleHelper] Validation failed: Custom module repository path is empty');
      return { valid: false, errorKey: 'cloud-sync.repo-validation-error-empty-path' };
    }

    try {
      const storage = await this._connect(config);
      if (storage == null) {
        return { valid: false, errorKey: 'cloud-sync.repo-validation-error-not-configured' };
      }

      const repoPath = normalizeRepoPath(customModuleRepo);
      console.log(`[CloudModuleHelper] Listing ${storage.providerName} repository folder:`, repoPath);

      let repoContents;
      try {
        repoContents = await storage.listFolderEntries(repoPath);
        console.log(`[CloudModuleHelper] Repository folder contains ${repoContents.length} items`);
      } catch (e) {
        if (e.notFound) {
          console.log('[CloudModuleHelper] Validation failed: Repository folder not found');
          return { valid: false, errorKey: 'cloud-sync.repo-validation-error-not-found' };
        }
        throw e;
      }

      const modsIndexExists = repoContents.some(item => item.name === MODS_INDEX_FILE && !item.isFolder);
      if (!modsIndexExists) {
        console.log('[CloudModuleHelper] Validation failed: Index file not found');
        return { valid: false, errorKey: 'cloud-sync.repo-validation-error-index-not-found' };
      }

      const packagesFolder = repoContents.find(item => item.name === 'packages' && item.isFolder);
      if (!packagesFolder) {
        console.log('[CloudModuleHelper] Validation failed: packages folder not found');
        return { valid: false, errorKey: 'cloud-sync.repo-validation-error-packages-not-found' };
      }

      const packagesContents = await storage.listFolderEntries(packagesFolder.path);
      console.log(`[CloudModuleHelper] packages folder contains ${packagesContents.length} items`);

      if (packagesContents.length === 0) {
        console.log('[CloudModuleHelper] Validation failed: packages folder is empty');
        return { valid: false, errorKey: 'cloud-sync.repo-validation-error-packages-empty' };
      }

      console.log('[CloudModuleHelper] Validation successful - all checks passed');
      return { valid: true, errorKey: '' };

    } catch (error) {
      console.error('[CloudModuleHelper] Error validating custom module repo:', error);
      return { valid: false, errorKey: 'cloud-sync.repo-validation-error-unknown', errorParams: { error: error.message || 'Unknown error' } };
    }
  }

  async updateCloudModulesCache() {
    const config = this._getConfig();

    if (!this.isCustomModuleRepoEnabled(false)) {
      // No custom module repository configured, clear cache
      this.clearCache();
      return;
    }

    try {
      const storage = await this._connect(config);
      const tempDir = this._platformHelper.getTempDir();
      const provider = this.getActiveProvider(config);
      const repoPath = normalizeRepoPath(config.get(CUSTOM_MODULE_REPO_KEY));

      await storage.downloadFile(`${repoPath}/${MODS_INDEX_FILE}`, tempDir);

      const tarballPath = path.join(tempDir, MODS_INDEX_FILE);
      const extractDir = path.join(tempDir, 'cloud_mods');

      // Start from an empty directory, so that no configs of a previous repository remain
      removeIfExisting(extractDir);
      fs.mkdirSync(extractDir, { recursive: true });

      this._nsi.unTarGZ(tarballPath, extractDir);

      const modules = [];
      const modsDDir = path.join(extractDir, 'mods.d');

      if (fs.existsSync(modsDDir)) {
        const files = fs.readdirSync(modsDDir);

        for (const file of files) {
          if (file.endsWith('.conf')) {
            const moduleConfig = this.parseModuleConfig(path.join(modsDDir, file));
            if (moduleConfig) {
              modules.push(moduleConfig);
            } else {
              console.warn('[CloudModuleHelper] Failed to parse config for:', file);
            }
          }
        }
      } else {
        console.warn('[CloudModuleHelper] mods.d directory not found after extraction');
      }

      const cache = { provider, repoPath, modules };
      fs.writeFileSync(this.getCacheFilePath(), JSON.stringify(cache, null, 2), 'utf-8');
      removeIfExisting(this.getLegacyDropboxCacheFilePath());

    } catch (error) {
      console.error('[CloudModuleHelper] Error updating cloud modules cache:', error);
    }
  }

  _readCache(config) {
    const provider = this.getActiveProvider(config);
    const repoPath = normalizeRepoPath(config.get(CUSTOM_MODULE_REPO_KEY, ''));
    const cacheFile = this.getCacheFilePath();

    if (fs.existsSync(cacheFile)) {
      const cache = JSON.parse(fs.readFileSync(cacheFile, 'utf-8'));

      // Ignore a cache that was created for another provider or repository
      if (cache && cache.provider === provider && cache.repoPath === repoPath && Array.isArray(cache.modules)) {
        return cache.modules;
      }

      return [];
    }

    // Cache created by earlier versions, which only supported Dropbox
    const legacyCacheFile = this.getLegacyDropboxCacheFilePath();
    if (provider === 'dropbox' && fs.existsSync(legacyCacheFile)) {
      const modules = JSON.parse(fs.readFileSync(legacyCacheFile, 'utf-8'));
      return Array.isArray(modules) ? modules : [];
    }

    return [];
  }

  async getCloudModules() {
    const config = this._getConfig();
    const repositoryName = this.getRepositoryName(config);

    try {
      return this._readCache(config).map(m => ({ ...m, repository: repositoryName }));
    } catch (error) {
      console.error('[CloudModuleHelper] Error reading cloud modules cache:', error);
      return [];
    }
  }

  parseModuleConfig(configPath) {
    try {
      const content = fs.readFileSync(configPath, 'utf-8');
      const lines = content.split('\n');
      const config = {};
      let currentSection = null;

      for (const line of lines) {
        const trimmedLine = line.trim();
        if (trimmedLine.startsWith('[') && trimmedLine.endsWith(']')) {
          currentSection = trimmedLine.substring(1, trimmedLine.length - 1);
          config.name = currentSection;
        } else if (trimmedLine.includes('=')) {
          const parts = trimmedLine.split('=');
          const key = parts[0].trim();
          const value = parts.slice(1).join('=').trim();

          if (key === 'Description') config.description = value;
          if (key === 'Lang') config.language = value;
          if (key === 'Version') config.version = value;
          if (key === 'About') config.about = value;
          if (key === 'InstallSize') config.size = parseInt(value);
          if (key === 'ModDrv') {
             if (value === 'zText') config.type = SWORD_MODULE_TYPE.BIBLE;
             if (value === 'zCom') config.type = SWORD_MODULE_TYPE.COMMENTARY;
             if (value === 'zLD') config.type = SWORD_MODULE_TYPE.DICTIONARY;
          }
          if (key === 'GlobalOptionFilter') {
            if (value === 'OSISStrongs') {
              config.hasStrongs = true;
            }
            if (value === 'OSISHeadings') {
              config.hasHeadings = true;
            }
          }
        }
      }
      return config;
    } catch (e) {
      console.error('Error parsing module config:', e);
      return null;
    }
  }

  async installCloudModule(moduleCode, progressCB) {
    const config = this._getConfig();
    const repoPath = normalizeRepoPath(config.get(CUSTOM_MODULE_REPO_KEY, ''));
    const zipFile = `${moduleCode.toLowerCase()}.zip`;
    const remotePath = `${repoPath}/packages/${zipFile}`;

    try {
      const storage = await this._connect(config);
      if (storage == null) {
        console.log('[CloudModuleHelper] Cloud storage not configured.');
        return -1;
      }

      const tempDir = this._platformHelper.getTempDir();

      if (progressCB) progressCB({ totalPercent: 10, message: '' });

      await storage.downloadFile(remotePath, tempDir);

      if (progressCB) progressCB({ totalPercent: 50, message: '' });

      const zipFilePath = path.join(tempDir, zipFile);
      const swordPath = this._nsi.getSwordPath();

      console.log(`Installing ${storage.providerName} module ${moduleCode} from ${zipFilePath} to ${swordPath}`);
      const unzipSuccessful = this._nsi.unZip(zipFilePath, swordPath);
      removeIfExisting(zipFilePath);

      if (unzipSuccessful) {
        this._nsi.refreshLocalModules();
        console.log(`${storage.providerName} module ${moduleCode} installed successfully.`);
        if (progressCB) progressCB({ totalPercent: 100, message: '' });
        return 0;
      } else {
        console.log(`Failed to unzip ${storage.providerName} module ${moduleCode}.`);
        return -1;
      }

    } catch (error) {
      console.error('Error installing cloud module:', error);
      return -1;
    }
  }

  /**
   * Recursively list all zip files in the app folder of the cloud storage.
   * @returns {Promise<Array<{name: string, path: string, size: number}>>}
   */
  async listZipFiles() {
    const storage = await this._connect();
    if (storage == null) {
      const error = new Error('Cloud storage not configured');
      error.code = 'not-configured';
      throw error;
    }

    try {
      // Recursive function to list files in a folder and its subfolders
      const listFilesRecursive = async (folderPath) => {
        let entries;
        try {
          entries = await storage.listFolderEntries(folderPath);
        } catch (folderError) {
          if (folderPath === '' && !folderError.notFound) {
            throw folderError;
          }

          console.error('[listZipFiles] Error listing folder "' + (folderPath || '/') + '":', folderError.message);
          return [];
        }

        let zipFiles = [];

        for (const entry of entries) {
          if (!entry.isFolder && entry.name.toLowerCase().endsWith('.zip')) {
            zipFiles.push({
              name: entry.name,
              path: entry.path,
              size: entry.size
            });
          } else if (entry.isFolder) {
            // Recursively search in subdirectories
            const subFolderZipFiles = await listFilesRecursive(entry.path);
            zipFiles = zipFiles.concat(subFolderZipFiles);
          }
        }

        return zipFiles;
      };

      return await listFilesRecursive('');

    } catch (error) {
      console.error(`Error listing zip files from ${storage.providerName}:`, error);

      // Provide more user-friendly error messages for common network issues
      if (isNetworkError(error)) {
        const networkError = new Error(`Unable to connect to ${storage.providerName}. Please check your internet connection.`);
        networkError.code = 'NETWORK_ERROR';
        networkError.originalError = error;
        throw networkError;
      }

      throw error;
    }
  }

  async validateModuleZip(remotePath, storage) {
    const tempDir = this._platformHelper.getTempDir();
    const extractDir = path.join(tempDir, `extract_${Date.now()}`);

    // Extract filename from path
    const filename = path.basename(remotePath);
    const zipFilePath = path.join(tempDir, filename);

    try {
      console.log(`[validateModuleZip] Starting validation for: ${remotePath}`);

      // Download zip file to temp directory
      await storage.downloadFile(remotePath, tempDir);
      console.log(`[validateModuleZip] Downloaded to: ${zipFilePath}`);

      // Create extraction directory
      if (!fs.existsSync(extractDir)) {
        fs.mkdirSync(extractDir, { recursive: true });
      }

      // Extract zip to temp directory
      console.log(`[validateModuleZip] Extracting to: ${extractDir}`);
      const unzipSuccessful = this._nsi.unZip(zipFilePath, extractDir);

      if (!unzipSuccessful) {
        console.log(`[validateModuleZip] Unzip failed for: ${zipFilePath}`);
        removeIfExisting(zipFilePath);
        removeIfExisting(extractDir);

        return {
          valid: false,
          moduleId: null,
          alreadyInstalled: false,
          error: `Failed to extract zip file: ${zipFilePath}`
        };
      }

      console.log(`[validateModuleZip] Unzip successful, checking structure...`);

      // Check for required directories
      const modsDPath = path.join(extractDir, 'mods.d');
      const modulesPath = path.join(extractDir, 'modules');

      const hasModsD = fs.existsSync(modsDPath) && fs.statSync(modsDPath).isDirectory();
      const hasModules = fs.existsSync(modulesPath) && fs.statSync(modulesPath).isDirectory();

      console.log(`[validateModuleZip] hasModsD=${hasModsD}, hasModules=${hasModules}`);
      // Find .conf file in mods.d directory and extract module ID from its content
      let moduleId = null;
      if (hasModsD) {
        const files = fs.readdirSync(modsDPath);
        const confFile = files.find(f => f.endsWith('.conf'));
        if (confFile) {
          // Read the .conf file content to extract the actual module ID
          const confFilePath = path.join(modsDPath, confFile);
          const confContent = fs.readFileSync(confFilePath, 'utf8');

          // Extract module ID from the section header [ModuleID]
          const moduleIdMatch = confContent.match(/^\[([^\]]+)\]/m);
          if (moduleIdMatch) {
            moduleId = moduleIdMatch[1];
            console.log(`[validateModuleZip] Extracted module ID from .conf file: ${moduleId}`);
          } else {
            console.warn(`[validateModuleZip] Could not extract module ID from ${confFile}`);
          }
        }
      }

      // Check if module is already installed
      let alreadyInstalled = false;
      if (moduleId) {
        const localModule = this._nsi.getLocalModule(moduleId);
        alreadyInstalled = localModule !== undefined && localModule !== null;
        console.log(`[validateModuleZip] Module ${moduleId} already installed: ${alreadyInstalled}`);
      }

      // Clean up temp files and directories
      removeIfExisting(zipFilePath);
      removeIfExisting(extractDir);

      return {
        valid: hasModsD && hasModules && moduleId !== null,
        moduleId: moduleId,
        alreadyInstalled: alreadyInstalled,
        hasModsD: hasModsD,
        hasModules: hasModules
      };

    } catch (error) {
      console.error('Error validating module zip:', error);

      // Clean up on error
      try {
        removeIfExisting(zipFilePath);
        removeIfExisting(extractDir);
      } catch (cleanupError) {
        console.error('Error during cleanup:', cleanupError);
      }

      return {
        valid: false,
        moduleId: null,
        alreadyInstalled: false,
        error: error.message
      };
    }
  }

  async installModuleFromZip(remotePath) {
    const tempDir = this._platformHelper.getTempDir();

    // Extract filename from path
    const filename = path.basename(remotePath);

    console.log(`[installModuleFromZip] Installing from: ${remotePath}`);

    try {
      const storage = await this._connect();
      if (storage == null) {
        return {
          success: false,
          alreadyInstalled: false,
          error: 'Cloud storage not configured',
          errorCode: 'not-configured'
        };
      }

      // Validate first
      const validation = await this.validateModuleZip(remotePath, storage);

      console.log(`[installModuleFromZip] Validation result:`, validation);

      if (!validation.valid) {
        const errorDetails = `hasModsD=${validation.hasModsD}, hasModules=${validation.hasModules}, moduleId=${validation.moduleId}`;
        console.log(`[installModuleFromZip] Validation failed - invalid structure: ${errorDetails}`);
        return {
          success: false,
          alreadyInstalled: false,
          error: 'Invalid module structure',
          errorDetails: validation.error || errorDetails
        };
      }

      if (validation.alreadyInstalled) {
        console.log(`[installModuleFromZip] Module ${validation.moduleId} is already installed - skipping`);
        return {
          success: false,
          alreadyInstalled: true,
          moduleId: validation.moduleId
        };
      }

      console.log(`[installModuleFromZip] Proceeding with installation of ${validation.moduleId}`);

      // Download zip file
      await storage.downloadFile(remotePath, tempDir);
      const zipFilePath = path.join(tempDir, filename);

      // Install to SWORD directory
      const swordPath = this._nsi.getSwordPath();
      console.log(`Installing module from ${zipFilePath} to ${swordPath}`);

      const unzipSuccessful = this._nsi.unZip(zipFilePath, swordPath);

      // Clean up temp file
      removeIfExisting(zipFilePath);

      if (unzipSuccessful) {
        this._nsi.refreshLocalModules();
        console.log(`Module ${validation.moduleId} installed successfully from zip.`);

        // Get the installed module to retrieve its type
        const installedModule = this._nsi.getLocalModule(validation.moduleId);
        const moduleType = installedModule ? installedModule.type : null;

        return {
          success: true,
          alreadyInstalled: false,
          moduleId: validation.moduleId,
          moduleType: moduleType
        };
      } else {
        console.log(`Failed to unzip module from ${filename}.`);
        return {
          success: false,
          alreadyInstalled: false,
          error: 'Failed to extract zip file',
          errorDetails: `zipFilePath=${zipFilePath}, swordPath=${swordPath}`
        };
      }

    } catch (error) {
      console.error('Error installing module from zip:', error);
      return {
        success: false,
        alreadyInstalled: false,
        error: error.message,
        errorDetails: error.stack || error.code || 'No additional details'
      };
    }
  }
}

CloudModuleHelper.SWORD_MODULE_TYPE = SWORD_MODULE_TYPE;

module.exports = CloudModuleHelper;