|
| 1 | +"use strict"; |
| 2 | +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { |
| 3 | + if (k2 === undefined) k2 = k; |
| 4 | + var desc = Object.getOwnPropertyDescriptor(m, k); |
| 5 | + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { |
| 6 | + desc = { enumerable: true, get: function() { return m[k]; } }; |
| 7 | + } |
| 8 | + Object.defineProperty(o, k2, desc); |
| 9 | +}) : (function(o, m, k, k2) { |
| 10 | + if (k2 === undefined) k2 = k; |
| 11 | + o[k2] = m[k]; |
| 12 | +})); |
| 13 | +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { |
| 14 | + Object.defineProperty(o, "default", { enumerable: true, value: v }); |
| 15 | +}) : function(o, v) { |
| 16 | + o["default"] = v; |
| 17 | +}); |
| 18 | +var __importStar = (this && this.__importStar) || function (mod) { |
| 19 | + if (mod && mod.__esModule) return mod; |
| 20 | + var result = {}; |
| 21 | + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); |
| 22 | + __setModuleDefault(result, mod); |
| 23 | + return result; |
| 24 | +}; |
| 25 | +Object.defineProperty(exports, "__esModule", { value: true }); |
| 26 | +exports.BackupHandler = void 0; |
| 27 | +const path = __importStar(require("path")); |
| 28 | +const tar = __importStar(require("tar")); |
| 29 | +const fs_1 = require("./wrapper/fs"); |
| 30 | +const defaultOptions = { |
| 31 | + isDeleted: false, |
| 32 | + concepts: [], |
| 33 | + turncate: false |
| 34 | +}; |
| 35 | +class BackupHandler { |
| 36 | + constructor() { |
| 37 | + this.groups = []; |
| 38 | + this.dishes = []; |
| 39 | + this.tar = tar; |
| 40 | + } |
| 41 | + // Export data and images to a tar file |
| 42 | + async exportToTar(filePath, options = {}) { |
| 43 | + try { |
| 44 | + const finalOptions = { ...defaultOptions, ...options }; |
| 45 | + // Получаем текущую директорию для создания временной папки |
| 46 | + const currentDir = process.cwd(); |
| 47 | + // Создаем временную директорию для экспорта |
| 48 | + const timestamp = Date.now(); |
| 49 | + const exportDir = path.join(currentDir, `.tmp/backup-${timestamp}`); |
| 50 | + // Создаем папку, если она не существует |
| 51 | + await fs_1.fsw.mkdir(exportDir); |
| 52 | + // Путь для JSON файла |
| 53 | + const jsonFilePath = path.join(exportDir, 'data.json'); |
| 54 | + // Создание JSON данных |
| 55 | + const jsonData = await this.createJSON(finalOptions); |
| 56 | + await fs_1.fsw.writeFile(jsonFilePath, jsonData); |
| 57 | + // Экспорт изображений в временную директорию |
| 58 | + await this.exportImages(this.dishes, exportDir); |
| 59 | + // Упаковка всего содержимого в tar файл |
| 60 | + await this.tar.c({ |
| 61 | + gzip: true, |
| 62 | + file: filePath, |
| 63 | + cwd: exportDir |
| 64 | + }, ['.']); |
| 65 | + // Удаление временных файлов |
| 66 | + await fs_1.fsw.unlink(jsonFilePath); |
| 67 | + console.log('Export completed:', filePath); |
| 68 | + } |
| 69 | + catch (error) { |
| 70 | + new Error; |
| 71 | + console.error('Export error:', error); |
| 72 | + } |
| 73 | + } |
| 74 | + // Import data and images from a tar file |
| 75 | + async importFromTar(filePath) { |
| 76 | + try { |
| 77 | + // Получаем текущую директорию |
| 78 | + const currentDir = process.cwd(); |
| 79 | + // Создаем директорию для распаковки |
| 80 | + const timestamp = Date.now(); |
| 81 | + const extractDir = path.join(currentDir, `.tmp/backup-${timestamp}`); |
| 82 | + // Создаем папку, если она не существует |
| 83 | + await fs_1.fsw.mkdir(extractDir); |
| 84 | + console.log(`Extracting tar file to: ${extractDir}`); |
| 85 | + // Распаковываем архив в указанную директорию |
| 86 | + await this.tar.x({ |
| 87 | + file: filePath, |
| 88 | + cwd: extractDir, |
| 89 | + }); |
| 90 | + // Читаем данные JSON |
| 91 | + const jsonFilePath = path.join(extractDir, 'data.json'); |
| 92 | + const jsonData = await fs_1.fsw.readFile(jsonFilePath); |
| 93 | + const importedData = JSON.parse(jsonData); |
| 94 | + this.groups = importedData.groups; |
| 95 | + this.dishes = importedData.dishes; |
| 96 | + // Проверяем и загружаем изображения |
| 97 | + for (const dish of this.dishes) { |
| 98 | + if (dish.images && Array.isArray(dish.images)) { |
| 99 | + for (const image of dish.images) { |
| 100 | + const imagePath = path.join(extractDir, `${image.id}.jpg`); |
| 101 | + this.checkAndLoadImage(imagePath); // Предположим, что это ваш метод для проверки и загрузки изображений |
| 102 | + } |
| 103 | + } |
| 104 | + } |
| 105 | + console.log('Import completed:', filePath); |
| 106 | + } |
| 107 | + catch (error) { |
| 108 | + console.error('Import error:', error); |
| 109 | + } |
| 110 | + } |
| 111 | + // Create JSON data |
| 112 | + async createJSON(options) { |
| 113 | + const groups = await Group.find({ |
| 114 | + isDeleted: options.isDeleted, |
| 115 | + ...(options.concepts.length && { concepts: { $in: options.concepts } }) |
| 116 | + }); |
| 117 | + const dishes = await Dish.find({ |
| 118 | + isDeleted: options.isDeleted, |
| 119 | + ...(options.concepts.length && { concepts: { $in: options.concepts } }) |
| 120 | + }); |
| 121 | + this.groups = groups; |
| 122 | + this.dishes = dishes; |
| 123 | + const kernelVersion = process.version; |
| 124 | + return JSON.stringify({ kernelVersion, groups, dishes }, null, 2); |
| 125 | + } |
| 126 | + // Check file existence and load image |
| 127 | + async checkAndLoadImage(imagePath) { |
| 128 | + if (await fs_1.fsw.exists(imagePath)) { |
| 129 | + this.loadImage(imagePath); |
| 130 | + } |
| 131 | + else { |
| 132 | + console.warn(`Image not found: ${imagePath}`); |
| 133 | + } |
| 134 | + } |
| 135 | + // Simulate loading an image |
| 136 | + loadImage(imagePath) { |
| 137 | + console.log(`Loading image: ${imagePath}`); |
| 138 | + } |
| 139 | + // Export images to a directory |
| 140 | + async exportImages(dishes, exportDir) { |
| 141 | + const imagesDir = path.join(exportDir); |
| 142 | + dishes.forEach(dish => { |
| 143 | + if (dish.images && Array.isArray(dish.images)) { |
| 144 | + dish.images.forEach((image) => { |
| 145 | + Object.entries(image.variant).forEach(async ([variantName, variantPath]) => { |
| 146 | + if (variantPath) { |
| 147 | + const imageFileName = `${variantName}_${image.id}.jpg`; |
| 148 | + const destinationPath = path.join(imagesDir, imageFileName); |
| 149 | + if (await fs_1.fsw.exists(variantPath)) { |
| 150 | + await fs_1.fsw.copyFile(variantPath, destinationPath); |
| 151 | + console.log(`Image exported: ${imageFileName}`); |
| 152 | + } |
| 153 | + else { |
| 154 | + console.warn(`Image file not found: ${variantPath}`); |
| 155 | + } |
| 156 | + } |
| 157 | + }); |
| 158 | + }); |
| 159 | + } |
| 160 | + }); |
| 161 | + } |
| 162 | +} |
| 163 | +exports.BackupHandler = BackupHandler; |
0 commit comments