Source

frontend/controllers/cloud_sync/cloud_zip_install_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 the dialog for listing, selecting and installing SWORD module ZIP files
 * from the active cloud-sync provider's storage.
 * @module cloudZipInstallController
 * @category Controller
 */

const Mousetrap = require('mousetrap');
const PlatformHelper = require('../../../lib/platform_helper.js');
const platformHelper = new PlatformHelper();
const eventController = require('../event_controller.js');
const { html } = require('../../helpers/ezra_helper.js');
const cloudSyncController = require('./cloud_sync_controller.js');
const swordModuleHelper = require('../../helpers/sword_module_helper.js');

module.exports.showCloudZipInstallDialog = async function() {
  const cloudSyncInitDone = await cloudSyncController.isInitDone();
  if (!cloudSyncInitDone) {
    await cloudSyncController.init();
  }

  const provider = await cloudSyncController.getActiveProviderDisplayName();

  // Check if the cloud storage is configured
  if (!(await cloudSyncController.isCloudStorageConfigured())) {
    // eslint-disable-next-line no-undef
    iziToast.error({
      title: i18n.t('cloud-sync.install-from-zip'),
      message: i18n.t('cloud-sync.cloud-storage-not-configured'),
      position: platformHelper.getIziPosition(),
      timeout: 7000
    });
    return;
  }

  // Create dialog HTML
  const dialogBoxTemplate = html`
  <div id="cloud-zip-install-dialog" style="padding: 1em; display: flex; flex-direction: column; height: 100%;">
    <p style="margin-top: 0; flex-shrink: 0;">${i18n.t('cloud-sync.install-from-zip-explanation', { provider })}</p>
    <div id="zip-file-list" class="scrollable" style="overflow-y: auto; margin: 1em 0; flex: 1;">
      <div style="display: flex; align-items: center; justify-content: center; padding: 2em;">
        <p style="margin: 0 1em 0 0;">${i18n.t('cloud-sync.loading-zip-files', { provider })}</p>
        <loading-indicator></loading-indicator>
      </div>
    </div>
  </div>
  `;

  document.querySelector('#boxes').appendChild(dialogBoxTemplate.content);
  const $dialogBox = $('#cloud-zip-install-dialog');

  const width = 800;
  const height = 600;

  let dialogOptions = uiHelper.getDialogOptions(width, height, true);
  dialogOptions.title = i18n.t('cloud-sync.install-from-zip-provider', { provider });
  dialogOptions.dialogClass = 'ezra-dialog cloud-zip-install-dialog';
  dialogOptions.close = () => {
    $dialogBox.dialog('destroy');
    $dialogBox.remove();
  };

  dialogOptions.buttons = {};
  dialogOptions.buttons[i18n.t('general.cancel')] = function() {
    $dialogBox.dialog('close');
  };
  dialogOptions.buttons[i18n.t('general.install')] = {
    id: 'install-zip-modules-button',
    text: i18n.t('general.install'),
    click: async () => {
      await installSelectedZipModules();
    }
  };

  $dialogBox.dialog(dialogOptions);
  uiHelper.fixDialogCloseIconOnCordova('cloud-zip-install-dialog');
  Mousetrap.bind('esc', () => { $dialogBox.dialog('close'); });

  // Load zip files from the cloud storage
  await loadCloudZipFiles();

  async function loadCloudZipFiles() {
    try {
      const response = await ipcGeneral.cloudListZipFiles();

      const zipFileList = document.getElementById('zip-file-list');
      zipFileList.innerHTML = '';

      // Check if response indicates an error
      if (!response.success) {
        zipFileList.innerHTML = `
          <div style="padding: 2em; text-align: center;">
            <p style="color: #d00; margin-bottom: 1em;">${i18n.t('cloud-sync.error-loading-files', { provider })}</p>
            <p style="color: #666; font-size: 0.9em; margin-bottom: 1.5em;">${response.error}</p>
            <button id="retry-load-files">
              ${i18n.t('general.retry')}
            </button>
          </div>
        `;

        $('#install-zip-modules-button').button('disable');
        
        $('#retry-load-files').button().click(async () => {
          const zipFileList = document.getElementById('zip-file-list');
          zipFileList.innerHTML = `
            <div style="display: flex; align-items: center; justify-content: center; padding: 2em;">
              <p style="margin: 0 1em 0 0;">${i18n.t('cloud-sync.loading-zip-files', { provider })}</p>
              <loading-indicator></loading-indicator>
            </div>
          `;
          await loadCloudZipFiles();
        });
        return;
      }

      const zipFiles = response.files;
      if (!zipFiles || !Array.isArray(zipFiles) || zipFiles.length === 0) {
        zipFileList.innerHTML = `<p style="text-align: center; color: #888;">${i18n.t('cloud-sync.no-zip-files-found', { provider })}</p>`;
        $('#install-zip-modules-button').button('disable');
        return;
      }


      // Render file list
      zipFiles.forEach((file) => {
        const fileItem = document.createElement('div');
        fileItem.className = 'zip-file-item';
        fileItem.style.padding = '0.5em';
        fileItem.style.borderBottom = '1px solid #ccc';
        let displayPath = file.path;
        if (displayPath.startsWith('/')) {
          displayPath = displayPath.substring(1);
        }
        fileItem.innerHTML = `
          <label style="cursor: pointer; display: flex; align-items: center;">
            <input type="checkbox" class="zip-file-checkbox" data-filepath="${file.path}" style="margin-right: 0.5em;">
            <span style="flex: 1;">${displayPath}</span>
            <span class="validation-status" style="margin-left: auto; font-size: 0.9em;"></span>
          </label>
        `;
        zipFileList.appendChild(fileItem);
      });

      // Enable/disable install button based on selection
      function updateInstallButtonState() {
        const checked = document.querySelectorAll('.zip-file-checkbox:checked').length > 0;
        if (checked) {
          $('#install-zip-modules-button').button('enable');
        } else {
          $('#install-zip-modules-button').button('disable');
        }
      }
      // Attach event listeners
      zipFileList.querySelectorAll('.zip-file-checkbox').forEach(cb => {
        cb.addEventListener('change', updateInstallButtonState);
      });
      // Initial state
      updateInstallButtonState();

    } catch (error) {
      console.error(`Error loading ${provider} zip files:`, error);
      const zipFileList = document.getElementById('zip-file-list');
      zipFileList.innerHTML = `
        <div style="padding: 2em; text-align: center;">
          <p style="color: #d00; margin-bottom: 1em;">${i18n.t('cloud-sync.error-loading-files', { provider })}</p>
          <p style="color: #666; font-size: 0.9em; margin-bottom: 1.5em;">${error.message}</p>
          <button id="retry-load-files" class="ui-button ui-widget ui-corner-all" style="padding: 0.5em 1em;">
            ${i18n.t('general.retry')}
          </button>
        </div>
      `;
      $('#install-zip-modules-button').button('disable');
      
      // Add click handler for retry button
      document.getElementById('retry-load-files').addEventListener('click', async () => {
        const zipFileList = document.getElementById('zip-file-list');
        zipFileList.innerHTML = `
          <div style="display: flex; align-items: center; justify-content: center; padding: 2em;">
            <p style="margin: 0 1em 0 0;">${i18n.t('cloud-sync.loading-zip-files', { provider })}</p>
            <loading-indicator></loading-indicator>
          </div>
        `;
        await loadCloudZipFiles();
      });
    }
  }

  async function installSelectedZipModules() {
    const checkboxes = document.querySelectorAll('.zip-file-checkbox:checked');
    if (checkboxes.length === 0) {
      return;
    }

    const selectedFiles = Array.from(checkboxes).map(cb => cb.dataset.filepath);

    // Always disable install button during installation
    $('#install-zip-modules-button').button('disable');
    $dialogBox.dialog('option', 'buttons', [
      {
        text: i18n.t('general.finish'),
        click: function() {
          $(this).dialog('close');
        }
      }
    ]);

    // Show installation progress table
    const zipFileList = document.getElementById('zip-file-list');
    const originalContent = zipFileList.innerHTML;
    zipFileList.innerHTML = `
      <div style="padding: 1em;">
        <p style="margin-bottom: 1em;">${i18n.t('cloud-sync.installing-modules')}</p>
        <table style="width: 100%; border-collapse: collapse;">
          <thead>
            <tr style="border-bottom: 2px solid #ccc;">
              <th style="text-align: left; padding: 0.5em; max-width: 200px;">${i18n.t('cloud-sync.module-header')}</th>
              <th style="text-align: left; padding: 0.5em; width: 120px;">${i18n.t('cloud-sync.status-header')}</th>
            </tr>
          </thead>
          <tbody id="installation-status-table">
          </tbody>
        </table>
      </div>
    `;

    let successCount = 0;
    let skippedCount = 0;
    let failedCount = 0;

    try {
      const statusTable = document.getElementById('installation-status-table');

      // Process each file
      for (const filepath of selectedFiles) {
        const displayPath = filepath.replace('/Apps/Ezra Bible App/', '').replace(/^\//, '');
        const moduleId = `module-${selectedFiles.indexOf(filepath)}`;
        
        // Add row to table with pending status
        const row = document.createElement('tr');
        row.id = moduleId;
        row.style.borderBottom = '1px solid #eee';
        row.innerHTML = `
          <td style="padding: 0.5em; max-width: 200px; word-break: break-word; overflow-wrap: break-word;">${displayPath}</td>
          <td style="padding: 0.5em;">
            <span style="display: flex; align-items: center;">
              <loading-indicator style="width: 16px; height: 16px;"></loading-indicator>
              <span style="margin-left: 0.5em;">${i18n.t('cloud-sync.processing')}</span>
            </span>
          </td>
        `;
        statusTable.appendChild(row);

        // Install the module
        const result = await ipcGeneral.cloudInstallZipModule(filepath);

        // Log the full result for debugging
        console.log(`[CloudZipInstall] Installation result for ${displayPath}:`, JSON.stringify(result, null, 2));

        // Update row with result
        const statusCell = row.querySelector('td:last-child');
        if (result.success) {
          successCount++;
          statusCell.innerHTML = `<span style="color: green;">${i18n.t('cloud-sync.row-installed')}</span>`;
          
          // Raise appropriate event based on module type
          if (swordModuleHelper.isBibleModule(result.moduleType)) {
            await eventController.publishAsync('on-translation-added', result.moduleId);
          } else if (swordModuleHelper.isDictionaryModule(result.moduleType)) {
            await eventController.publishAsync('on-dictionary-added', result.moduleId);
          } else if (swordModuleHelper.isCommentaryModule(result.moduleType)) {
            await eventController.publishAsync('on-commentary-added', result.moduleId);
          }
        } else if (result.alreadyInstalled) {
          skippedCount++;
          statusCell.innerHTML = `<span style="color: #888;">⊘ ${i18n.t('cloud-sync.module-already-installed')}</span>`;
        } else {
          failedCount++;
          const errorMsg = result.errorCode === 'not-configured'
            ? i18n.t('cloud-sync.repo-validation-error-not-configured', { provider })
            : (result.error || i18n.t('cloud-sync.unknown-error'));
          const errorDetails = result.errorCode === 'not-configured'
            ? i18n.t('cloud-sync.cloud-storage-not-configured')
            : (result.errorDetails || '');
          const fullError = errorDetails ? `${errorMsg}: ${errorDetails}` : errorMsg;
          console.error(`[CloudZipInstall] Failed to install ${displayPath}: ${fullError}`);
          statusCell.innerHTML = `<span style="color: red;" title="${fullError}">${i18n.t('cloud-sync.row-failed', {error: errorMsg})}</span>`;
        }
      }

      // Add summary row
      const summaryRow = document.createElement('tr');
      summaryRow.style.borderTop = '2px solid #ccc';
      summaryRow.style.fontWeight = 'bold';
      summaryRow.innerHTML = `
        <td style="padding: 1em 0.5em;">${i18n.t('cloud-sync.install-summary')}</td>
        <td style="padding: 1em 0.5em;">
          <div style="font-size: 0.9em;">
            ${successCount > 0 ? `<div style="color: green;">${i18n.t('cloud-sync.modules-installed', {count: successCount})}</div>` : ''}
            ${skippedCount > 0 ? `<div style="color: #888;">${i18n.t('cloud-sync.modules-skipped', {count: skippedCount})}</div>` : ''}
            ${failedCount > 0 ? `<div style="color: red;">${i18n.t('cloud-sync.modules-failed', {count: failedCount})}</div>` : ''}
          </div>
        </td>
      `;
      statusTable.appendChild(summaryRow);

      // Refresh module list if any modules were installed
      if (successCount > 0) {
        await app_controller.translation_controller.initTranslationsMenu();
      }

    } catch (error) {
      console.error('Error installing zip modules:', error);
      
      zipFileList.innerHTML = originalContent;
      
      // eslint-disable-next-line no-undef
      iziToast.error({
        title: i18n.t('cloud-sync.install-from-zip-provider', { provider }),
        message: error.message || i18n.t('cloud-sync.installation-failed'),
        position: platformHelper.getIziPosition(),
        timeout: 7000
      });

      // Re-enable buttons
      $('#install-zip-modules-button').button('enable');
      $('.ui-dialog-buttonpane button:contains("Cancel")').button('enable');
    }
  }
};