All files / backend/src/import pogozipper.ts

3.21% Statements 7/218
0% Branches 0/69
7.69% Functions 1/13
3.21% Lines 7/218

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593                                      2x 2x 2x                                                                                     9x 9x 9x 9x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
/**
 * Pogozipper - ZIP-based Import/Export for Quiqr Sites
 *
 * Handles import and export of:
 * - Complete sites (.pogosite)
 * - Themes only (.pogotheme)
 * - Content only (.pogocontent)
 */
 
import fs from 'fs-extra';
import fssimple from 'fs';
import path from 'path';
import AdmZip from 'adm-zip';
import type { PathHelper } from '../utils/path-helper.js';
import type { LibraryService } from '../services/library/library-service.js';
import type { DialogAdapter, WindowAdapter } from '../adapters/types.js';
import { recurForceRemove, fileRegexRemove } from '../utils/file-dir-utils.js';
 
// File extensions for Quiqr ZIP packages
const PogoSiteExtension = 'pogosite';
const PogoThemeExtension = 'pogotheme';
const PogoContentExtension = 'pogocontent';
 
/**
 * Options for exporting a site
 */
export interface ExportSiteOptions {
  siteKey: string;
  sitePath: string;
  newSiteKey?: string; // Optional: rename the site during export
}
 
/**
 * Options for importing a site
 */
export interface ImportSiteOptions {
  filePath?: string; // If not provided, will show file picker
  autoConfirm?: boolean; // Skip confirmation dialog
}
 
/**
 * Options for exporting/importing themes and content
 */
export interface ExportImportThemeContentOptions {
  siteKey: string;
  sitePath: string;
  filePath?: string; // For import: path to ZIP file
}
 
/**
 * Pogozipper - Handles ZIP-based import/export of Quiqr sites
 */
export class Pogozipper {
  private pathHelper: PathHelper;
  private libraryService: LibraryService;
  private dialogAdapter: DialogAdapter;
  private windowAdapter: WindowAdapter;
 
  constructor(
    pathHelper: PathHelper,
    libraryService: LibraryService,
    dialogAdapter: DialogAdapter,
    windowAdapter: WindowAdapter
  ) {
    this.pathHelper = pathHelper;
    this.libraryService = libraryService;
    this.dialogAdapter = dialogAdapter;
    this.windowAdapter = windowAdapter;
  }
 
  /**
   * Export a complete site to a .pogosite ZIP file
   */
  async exportSite(options: ExportSiteOptions): Promise<void> {
    const { siteKey, sitePath, newSiteKey = siteKey } = options;
 
    // Show directory picker for export destination
    const dirs = await this.dialogAdapter.showOpenDialog({
      properties: ['openDirectory'],
    });
 
    if (!dirs || dirs.length !== 1) {
      return;
    }
 
    const exportDir = dirs[0];
    const tmpPath = path.join(this.pathHelper.getRoot(), 'sites', siteKey, 'exportTmp');
 
    try {
      // Clean up temp directory
      await recurForceRemove(tmpPath);
 
      // Copy site to temp directory
      fs.copySync(sitePath, tmpPath);
      console.log('Copied site to temp dir');
 
      // Remove files that shouldn't be exported
      await this.cleanupSiteForExport(tmpPath);
 
      // Read and update site config
      const configJsonPath = this.pathHelper.getSiteMountConfigPath(siteKey);
      const confText = fssimple.readFileSync(configJsonPath, { encoding: 'utf8' });
      const config = JSON.parse(confText);
      config.key = newSiteKey;
      config.name = newSiteKey;
      const newConfigJson = JSON.stringify(config);
 
      // Create ZIP file
      const zip = new AdmZip();
      zip.addFile('sitekey', Buffer.from(newSiteKey, 'utf8'));
      zip.addFile(
        `config.${newSiteKey}.json`,
        Buffer.from(newConfigJson, 'utf8')
      );
      zip.addLocalFolder(tmpPath);
 
      // Write ZIP to export directory
      const exportFilePath = path.join(exportDir, `${newSiteKey}.${PogoSiteExtension}`);
      zip.writeZip(exportFilePath);
 
      // Show success message
      await this.dialogAdapter.showMessageBox({
        type: 'info',
        buttons: ['Close'],
        title: 'Finished site export',
        message: `Site exported to:\n${exportFilePath}`,
      });
    } finally {
      // Clean up temp directory
      await recurForceRemove(tmpPath);
    }
  }
 
  /**
   * Import a site from a .pogosite ZIP file
   */
  async importSite(options: ImportSiteOptions = {}): Promise<void> {
    let { filePath } = options;
    const { autoConfirm = false } = options;
 
    // Show file picker if no path provided
    if (!filePath) {
      const files = await this.dialogAdapter.showOpenDialog({
        filters: [{ name: 'Quiqr Sites', extensions: [PogoSiteExtension] }],
        properties: ['openFile'],
      });
 
      if (!files || files.length !== 1) {
        return;
      }
      filePath = files[0];
    } else if (!autoConfirm) {
      // Show confirmation dialog
      const filename = path.basename(filePath);
      const response = await this.dialogAdapter.showMessageBox({
        buttons: ['Yes', 'Cancel'],
        message: `You're about to import the site ${filename}. Do you want to continue?`,
      });
      if (response === 1) {
        return;
      }
    }
 
    try {
      // Extract and validate ZIP
      const zip = new AdmZip(filePath);
      const zipEntries = zip.getEntries();
 
      // Find sitekey
      let siteKey = '';
      zipEntries.forEach((entry: AdmZip.IZipEntry) => {
        if (entry.entryName === 'sitekey') {
          siteKey = zip.readAsText('sitekey');
          console.log('Found sitekey:', siteKey);
        }
      });
 
      if (!siteKey) {
        await this.dialogAdapter.showMessageBox({
          type: 'warning',
          buttons: ['Close'],
          title: 'Failed task',
          message: 'Failed to import site. Invalid site file: no sitekey found.',
        });
        return;
      }
 
      this.windowAdapter.appendToOutputConsole(`Found a site with key ${siteKey}`);
 
      // Read and validate config
      const confFileName = `config.${siteKey}.json`;
      const confText = zip.readAsText(confFileName);
      if (!confText) {
        await this.dialogAdapter.showMessageBox({
          type: 'warning',
          buttons: ['Close'],
          title: 'Failed task',
          message: `Failed to import site. Invalid site file: unreadable ${confFileName}.`,
        });
        return;
      }
 
      // Create site directories
      const todayDate = new Date().toISOString().replace(/:/g, '-').slice(0, -5);
      const pathSite = path.join(this.pathHelper.getRoot(), 'sites', siteKey);
      const pathSiteSources = path.join(pathSite, 'sources');
      const pathSource = path.join(pathSiteSources, `${siteKey}-${todayDate}`);
 
      await fs.ensureDir(pathSite);
      await fs.ensureDir(pathSiteSources);
      await fs.ensureDir(pathSource);
 
      // Update config with new source path
      const newConf = JSON.parse(confText);
      newConf.source.path = pathSource;
 
      // Write site config
      const newConfigJsonPath = this.pathHelper.getSiteMountConfigPath(siteKey);
      fssimple.writeFileSync(newConfigJsonPath, JSON.stringify(newConf), {
        encoding: 'utf8',
      });
 
      this.windowAdapter.appendToOutputConsole('Wrote new site configuration');
 
      // Extract ZIP to source directory
      zip.extractAllTo(pathSource, true);
 
      // Remove the config file from extracted content (it's in site config dir)
      await fs.removeSync(path.join(pathSource, confFileName));
 
      // Show success message
      await this.dialogAdapter.showMessageBox({
        type: 'info',
        buttons: ['Close'],
        title: 'Finished task',
        message: 'Site has been imported.',
      });
 
      // Redirect to site library
      await this.windowAdapter.openSiteLibrary();
    } catch (error) {
      console.error('Error importing site:', error);
      await this.dialogAdapter.showMessageBox({
        type: 'error',
        buttons: ['Close'],
        title: 'Import Failed',
        message: `Failed to import site: ${error instanceof Error ? error.message : 'Unknown error'}`,
      });
    }
  }
 
  /**
   * Export a theme to a .pogotheme ZIP file
   */
  async exportTheme(options: ExportImportThemeContentOptions): Promise<void> {
    const { siteKey, sitePath } = options;
 
    // Show directory picker
    const dirs = await this.dialogAdapter.showOpenDialog({
      properties: ['openDirectory'],
    });
 
    if (!dirs || dirs.length !== 1) {
      return;
    }
 
    const exportDir = dirs[0];
    const tmpPath = path.join(this.pathHelper.getRoot(), 'sites', siteKey, 'exportTmp');
 
    try {
      // Clean up temp directory
      await recurForceRemove(tmpPath);
 
      // Copy site to temp directory
      fs.copySync(sitePath, tmpPath);
      console.log('Copied site to temp dir');
 
      // Remove everything except themes
      await this.cleanupThemeForExport(tmpPath);
 
      // Create ZIP file
      const zip = new AdmZip();
      zip.addFile('sitekey', Buffer.from(siteKey, 'utf8'));
      zip.addLocalFolder(tmpPath);
 
      // Write ZIP
      const exportFilePath = path.join(exportDir, `${siteKey}.${PogoThemeExtension}`);
      zip.writeZip(exportFilePath);
 
      // Show success message
      await this.dialogAdapter.showMessageBox({
        type: 'info',
        buttons: ['Close'],
        title: 'Finished task',
        message: `Finished theme export:\n${exportFilePath}`,
      });
    } finally {
      // Clean up temp directory
      await recurForceRemove(tmpPath);
    }
  }
 
  /**
   * Import a theme from a .pogotheme ZIP file
   */
  async importTheme(options: ExportImportThemeContentOptions): Promise<void> {
    const { siteKey, sitePath } = options;
    let { filePath } = options;
 
    // Show file picker if no path provided
    if (!filePath) {
      const files = await this.dialogAdapter.showOpenDialog({
        filters: [{ name: 'Quiqr Themes', extensions: [PogoThemeExtension] }],
        properties: ['openFile'],
      });
 
      if (!files || files.length !== 1) {
        return;
      }
      filePath = files[0];
    } else {
      // Show confirmation dialog
      const filename = path.basename(filePath);
      const response = await this.dialogAdapter.showMessageBox({
        buttons: ['Yes', 'Cancel'],
        message: `You're about to import the theme ${filename} into ${siteKey}. Do you want to continue?`,
      });
      if (response === 1) {
        return;
      }
    }
 
    try {
      // Extract and validate ZIP
      const zip = new AdmZip(filePath);
      const zipEntries = zip.getEntries();
 
      // Find sitekey
      let zipSiteKey = '';
      zipEntries.forEach((entry: AdmZip.IZipEntry) => {
        if (entry.entryName === 'sitekey') {
          zipSiteKey = zip.readAsText('sitekey');
          console.log('Found sitekey:', zipSiteKey);
        }
      });
 
      if (!zipSiteKey) {
        await this.dialogAdapter.showMessageBox({
          type: 'warning',
          buttons: ['Close'],
          title: 'Failed task',
          message: 'Failed to import theme. Invalid theme file: no sitekey found.',
        });
        return;
      }
 
      // Warn if sitekey doesn't match
      if (zipSiteKey !== siteKey) {
        const response = await this.dialogAdapter.showMessageBox({
          buttons: ['Yes', 'Cancel'],
          message: 'The sitekey of the theme file does not match. Do you want to continue?',
        });
        if (response === 1) {
          return;
        }
      }
 
      this.windowAdapter.appendToOutputConsole(`Found a theme with key ${zipSiteKey}`);
 
      // Remove existing themes directory
      await recurForceRemove(path.join(sitePath, 'themes'));
 
      // Extract theme
      zip.extractAllTo(sitePath, true);
 
      // Show success message
      await this.dialogAdapter.showMessageBox({
        type: 'info',
        buttons: ['Close'],
        title: 'Finished task',
        message: 'Theme has been imported.',
      });
    } catch (error) {
      console.error('Error importing theme:', error);
      await this.dialogAdapter.showMessageBox({
        type: 'error',
        buttons: ['Close'],
        title: 'Import Failed',
        message: `Failed to import theme: ${error instanceof Error ? error.message : 'Unknown error'}`,
      });
    }
  }
 
  /**
   * Export content to a .pogocontent ZIP file
   */
  async exportContent(options: ExportImportThemeContentOptions): Promise<void> {
    const { siteKey, sitePath } = options;
 
    // Show directory picker
    const dirs = await this.dialogAdapter.showOpenDialog({
      properties: ['openDirectory'],
    });
 
    if (!dirs || dirs.length !== 1) {
      return;
    }
 
    const exportDir = dirs[0];
    const tmpPath = path.join(this.pathHelper.getRoot(), 'sites', siteKey, 'exportTmp');
 
    try {
      // Clean up temp directory
      await recurForceRemove(tmpPath);
 
      // Copy site to temp directory
      fs.copySync(sitePath, tmpPath);
      console.log('Copied site to temp dir');
 
      // Remove everything except content
      await this.cleanupContentForExport(tmpPath);
 
      // Create ZIP file
      const zip = new AdmZip();
      zip.addFile('sitekey', Buffer.from(siteKey, 'utf8'));
      zip.addLocalFolder(tmpPath);
 
      // Write ZIP
      const exportFilePath = path.join(exportDir, `${siteKey}.${PogoContentExtension}`);
      zip.writeZip(exportFilePath);
 
      // Show success message
      await this.dialogAdapter.showMessageBox({
        type: 'info',
        buttons: ['Close'],
        title: 'Finished task',
        message: `Finished content export:\n${exportFilePath}`,
      });
    } finally {
      // Clean up temp directory
      await recurForceRemove(tmpPath);
    }
  }
 
  /**
   * Import content from a .pogocontent ZIP file
   */
  async importContent(options: ExportImportThemeContentOptions): Promise<void> {
    const { siteKey, sitePath } = options;
    let { filePath } = options;
 
    // Show file picker if no path provided
    if (!filePath) {
      const files = await this.dialogAdapter.showOpenDialog({
        filters: [{ name: 'Quiqr Content', extensions: [PogoContentExtension] }],
        properties: ['openFile'],
      });
 
      if (!files || files.length !== 1) {
        return;
      }
      filePath = files[0];
    } else {
      // Show confirmation dialog
      const filename = path.basename(filePath);
      const response = await this.dialogAdapter.showMessageBox({
        buttons: ['Yes', 'Cancel'],
        message: `You're about to import the content ${filename} into ${siteKey}. Do you want to continue?`,
      });
      if (response === 1) {
        return;
      }
    }
 
    try {
      // Extract and validate ZIP
      const zip = new AdmZip(filePath);
      const zipEntries = zip.getEntries();
 
      // Find sitekey
      let zipSiteKey = '';
      zipEntries.forEach((entry: AdmZip.IZipEntry) => {
        if (entry.entryName === 'sitekey') {
          zipSiteKey = zip.readAsText('sitekey');
          console.log('Found sitekey:', zipSiteKey);
        }
      });
 
      if (!zipSiteKey) {
        await this.dialogAdapter.showMessageBox({
          type: 'warning',
          buttons: ['Close'],
          title: 'Failed task',
          message: 'Failed to import content. Invalid content file: no sitekey found.',
        });
        return;
      }
 
      // Warn if sitekey doesn't match
      if (zipSiteKey !== siteKey) {
        const response = await this.dialogAdapter.showMessageBox({
          buttons: ['Yes', 'Cancel'],
          message: 'The sitekey of the content file does not match. Do you want to continue?',
        });
        if (response === 1) {
          return;
        }
      }
 
      this.windowAdapter.appendToOutputConsole(`Found content with key ${zipSiteKey}`);
 
      // Remove existing content directory
      await recurForceRemove(path.join(sitePath, 'content'));
 
      // Extract content
      zip.extractAllTo(sitePath, true);
 
      // Show success message
      await this.dialogAdapter.showMessageBox({
        type: 'info',
        buttons: ['Close'],
        title: 'Finished task',
        message: 'Content has been imported.',
      });
    } catch (error) {
      console.error('Error importing content:', error);
      await this.dialogAdapter.showMessageBox({
        type: 'error',
        buttons: ['Close'],
        title: 'Import Failed',
        message: `Failed to import content: ${error instanceof Error ? error.message : 'Unknown error'}`,
      });
    }
  }
 
  /**
   * Clean up site directory for export - remove files that shouldn't be exported
   */
  private async cleanupSiteForExport(tmpPath: string): Promise<void> {
    await recurForceRemove(path.join(tmpPath, '.git'));
    await recurForceRemove(path.join(tmpPath, 'public'));
    await recurForceRemove(path.join(tmpPath, 'resources'));
    await fileRegexRemove(tmpPath, /sitekey$/);
    await fileRegexRemove(tmpPath, /config.*.json/);
    await fileRegexRemove(tmpPath, /.gitignore/);
    await fileRegexRemove(tmpPath, /.gitlab-ci.yml/);
    await fileRegexRemove(tmpPath, /.gitmodules/);
    await fileRegexRemove(tmpPath, /.DS_Store/);
  }
 
  /**
   * Clean up theme directory for export - keep only themes
   */
  private async cleanupThemeForExport(tmpPath: string): Promise<void> {
    await recurForceRemove(path.join(tmpPath, '.git'));
    await recurForceRemove(path.join(tmpPath, 'public'));
    await recurForceRemove(path.join(tmpPath, 'content'));
    await recurForceRemove(path.join(tmpPath, 'static'));
    await recurForceRemove(path.join(tmpPath, 'archetypes'));
    await recurForceRemove(path.join(tmpPath, 'resources'));
    await recurForceRemove(path.join(tmpPath, 'layouts'));
    await recurForceRemove(path.join(tmpPath, 'data'));
    await fileRegexRemove(tmpPath, /sitekey$/);
    await fileRegexRemove(tmpPath, /config.*.json/);
    await fileRegexRemove(tmpPath, /.gitignore/);
    await fileRegexRemove(tmpPath, /.gitlab-ci.yml/);
    await fileRegexRemove(tmpPath, /.gitmodules/);
    await fileRegexRemove(tmpPath, /.DS_Store/);
  }
 
  /**
   * Clean up content directory for export - keep only content and data
   */
  private async cleanupContentForExport(tmpPath: string): Promise<void> {
    await recurForceRemove(path.join(tmpPath, '.git'));
    await recurForceRemove(path.join(tmpPath, 'public'));
    await recurForceRemove(path.join(tmpPath, 'themes'));
    await recurForceRemove(path.join(tmpPath, 'archetypes'));
    await recurForceRemove(path.join(tmpPath, 'resources'));
    await recurForceRemove(path.join(tmpPath, 'layouts'));
    await fileRegexRemove(tmpPath, /sitekey$/);
    await fileRegexRemove(tmpPath, /config.*.json/);
    await fileRegexRemove(tmpPath, /config\.toml/);
    await fileRegexRemove(tmpPath, /config\.yaml/);
    await fileRegexRemove(tmpPath, /config\.json/);
    await fileRegexRemove(tmpPath, /.gitignore/);
    await fileRegexRemove(tmpPath, /.gitlab-ci.yml/);
    await fileRegexRemove(tmpPath, /sukoh\.yml/);
    await fileRegexRemove(tmpPath, /.gitmodules/);
    await fileRegexRemove(tmpPath, /.DS_Store/);
  }
}