@@ -26,37 +26,37 @@ export class BackupHandler {
26
26
async exportToTar ( filePath : string , options : Partial < BackupOptions > = { } ) : Promise < void > {
27
27
try {
28
28
const finalOptions = { ...defaultOptions , ...options } ;
29
-
29
+
30
30
// Получаем текущую директорию для создания временной папки
31
31
const currentDir = process . cwd ( ) ;
32
-
32
+
33
33
// Создаем временную директорию для экспорта
34
34
const timestamp = Date . now ( ) ;
35
35
this . workDir = path . join ( currentDir , `.tmp/backup-${ timestamp } ` ) ;
36
-
36
+
37
37
// Создаем папку, если она не существует
38
38
await fsw . mkdir ( this . workDir ) ;
39
-
39
+
40
40
// Путь для JSON файла
41
41
const jsonFilePath = path . join ( this . workDir , 'data.json' ) ;
42
-
42
+
43
43
// Создание JSON данных
44
44
const jsonData = await this . createJSON ( finalOptions ) ;
45
45
await fsw . writeFile ( jsonFilePath , jsonData ) ;
46
46
47
47
// Экспорт изображений в временную директорию
48
48
await this . exportImages ( this . dishes , this . workDir ) ;
49
-
49
+
50
50
// Упаковка всего содержимого в tar файл
51
51
await this . tar . c ( {
52
52
gzip : true ,
53
53
file : filePath ,
54
54
cwd : this . workDir
55
55
} , [ '.' ] ) ;
56
-
56
+
57
57
// Удаление временных файлов
58
58
await fsw . unlink ( jsonFilePath ) ;
59
-
59
+
60
60
console . log ( 'Export completed:' , filePath ) ;
61
61
} catch ( error ) {
62
62
new Error
@@ -67,46 +67,46 @@ export class BackupHandler {
67
67
// Import data and images from a tar file
68
68
async importFromTar ( filePath : string ) : Promise < void > {
69
69
try {
70
- // Получаем текущую директорию
70
+ // Get the current directory
71
71
const currentDir = process . cwd ( ) ;
72
-
73
- // Создаем директорию для распаковки
72
+
73
+ // Create a directory for unpacking
74
74
const timestamp = Date . now ( ) ;
75
75
this . workDir = path . join ( currentDir , `.tmp/backup-${ timestamp } ` ) ;
76
-
77
- // Создаем папку, если она не существует
76
+
77
+ // Create a folder if it does not exist
78
78
await fsw . mkdir ( this . workDir ) ;
79
-
79
+
80
80
console . log ( `Extracting tar file to: ${ this . workDir } ` ) ;
81
-
82
- // Распаковываем архив в указанную директорию
81
+
82
+ // Unpack the archive into the specified directory
83
83
await this . tar . x ( {
84
84
file : filePath ,
85
85
cwd : this . workDir ,
86
86
} ) ;
87
-
88
- // Читаем данные JSON
87
+
88
+ // Reading JSON data
89
89
const jsonFilePath = path . join ( this . workDir , 'data.json' ) ;
90
90
const jsonData = await fsw . readFile ( jsonFilePath ) ;
91
91
const importedData = JSON . parse ( jsonData ) ;
92
-
92
+
93
93
this . groups = importedData . groups ;
94
94
this . dishes = importedData . dishes ;
95
-
96
- // Проверяем и загружаем изображения
95
+
96
+ // Checking and uploading images
97
97
for ( const dish of this . dishes ) {
98
98
if ( dish . images && Array . isArray ( dish . images ) ) {
99
99
let count = 1 ;
100
100
for ( const image of dish . images ) {
101
101
const ext = path . extname ( image . originalFilePath ) || '.webp' ;
102
- const imagePath = path . join ( this . workDir , `${ dish . id } _ ${ count } ${ ext } ` ) ;
102
+ const imagePath = path . join ( this . workDir , `${ dish . id } __ ${ count } ${ ext } ` ) ;
103
103
this . checkAndLoadImage ( imagePath ) ;
104
104
count ++ ;
105
105
}
106
106
}
107
107
}
108
108
109
-
109
+
110
110
console . log ( 'Import completed:' , filePath ) ;
111
111
} catch ( error ) {
112
112
console . error ( 'Import error:' , error ) ;
@@ -134,23 +134,59 @@ export class BackupHandler {
134
134
135
135
// Check file existence and load image
136
136
private async checkAndLoadImage ( imagePath : string ) : Promise < void > {
137
+ // Извлечение имени файла
138
+ const fileName = path . basename ( imagePath ) ;
139
+
140
+ // Разделение имени файла по разделителю "__"
141
+ const parts = fileName . split ( '__' ) ;
142
+ if ( parts . length !== 2 ) {
143
+ console . warn ( `File name format is incorrect: ${ fileName } ` ) ;
144
+ return ;
145
+ }
146
+
147
+ const dishID = parts [ 0 ] ; // Левая часть до "__"
148
+ const countPart = parts [ 1 ] . split ( '.' ) ; // Правая часть (порядковый номер и расширение)
149
+
150
+ if ( countPart . length < 2 ) {
151
+ console . warn ( `File name format is incorrect: ${ fileName } ` ) ;
152
+ return ;
153
+ }
154
+
155
+ const count = parseInt ( countPart [ 0 ] , 10 ) ; // Извлекаем порядковый номер (число)
156
+ if ( isNaN ( count ) ) {
157
+ console . warn ( `File name format is incorrect: ${ fileName } ` ) ;
158
+ return ;
159
+ }
160
+
161
+ // Проверка существования файла
137
162
if ( await fsw . exists ( imagePath ) ) {
138
- this . loadImage ( imagePath ) ;
163
+ await this . loadImage ( imagePath , dishID , count ) ;
139
164
} else {
140
165
console . warn ( `Image not found: ${ imagePath } ` ) ;
141
166
}
142
167
}
143
168
169
+
144
170
// Simulate loading an image
145
- private loadImage ( imagePath : string ) : void {
171
+ private async loadImage ( imagePath : string , dishId : string , sortOrder : number ) : Promise < void > {
146
172
console . log ( `Loading image: ${ imagePath } ` ) ;
173
+
174
+ const model = 'dish'
175
+ const mfAdater = await Adapter . getMediaFileAdapter ( ) ;
176
+ const mediaFileImage = await mfAdater . toProcess ( `file://${ imagePath } ` , model , "image" ) ;
177
+
178
+ let init : Record < string , string | number > = { } ;
179
+ init [ `mediafile_${ model } ` ] = mediaFileImage . id ;
180
+ init [ model ] = dishId ;
181
+ init [ "sortOrder" ] = sortOrder ;
182
+ await SelectedMediaFile . create ( init ) . fetch ( ) ;
147
183
}
148
184
149
185
// Export images to a directory
150
186
private async exportImages ( dishes : DishRecord [ ] , exportDir : string ) : Promise < void > {
151
187
this . workDir = exportDir ;
152
188
const imagesDir = path . join ( this . workDir ) ;
153
-
189
+
154
190
for ( const dish of dishes ) {
155
191
if ( dish . images && Array . isArray ( dish . images ) ) {
156
192
let count = 1 ;
@@ -159,19 +195,19 @@ export class BackupHandler {
159
195
const ext = path . extname ( image . originalFilePath ) ;
160
196
const imageFileName = `${ dish . id } _${ count } ${ ext } ` ;
161
197
const destinationPath = path . join ( imagesDir , imageFileName ) ;
162
-
198
+
163
199
if ( await fsw . exists ( image . originalFilePath ) ) {
164
200
await fsw . copyFile ( image . originalFilePath , destinationPath ) ;
165
201
console . log ( `Image exported: ${ imageFileName } ` ) ;
166
202
} else {
167
203
console . warn ( `Image file not found: ${ image . originalFilePath } ` ) ;
168
204
}
169
-
205
+
170
206
count ++ ;
171
207
}
172
208
}
173
209
}
174
210
}
175
211
}
176
-
212
+
177
213
}
0 commit comments