@webiny/api-page-builder-import-export 0.0.0-unstable.c2780f51fe → 0.0.0-unstable.c7dec08bb0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/export/combine/index.js +20 -18
  2. package/export/combine/index.js.map +1 -1
  3. package/export/process/index.js +20 -18
  4. package/export/process/index.js.map +1 -1
  5. package/export/utils.js +9 -3
  6. package/export/utils.js.map +1 -1
  7. package/graphql/crud/blocks.crud.js +8 -4
  8. package/graphql/crud/blocks.crud.js.map +1 -1
  9. package/graphql/crud/forms.crud.js +14 -9
  10. package/graphql/crud/forms.crud.js.map +1 -1
  11. package/graphql/crud/importExportTasks.crud.js +38 -34
  12. package/graphql/crud/importExportTasks.crud.js.map +1 -1
  13. package/graphql/crud/pages.crud.js +8 -4
  14. package/graphql/crud/pages.crud.js.map +1 -1
  15. package/graphql/crud/templates.crud.js +8 -4
  16. package/graphql/crud/templates.crud.js.map +1 -1
  17. package/graphql/graphql/utils/resolve.d.ts +1 -1
  18. package/import/create/index.js +20 -18
  19. package/import/create/index.js.map +1 -1
  20. package/import/process/index.js +20 -18
  21. package/import/process/index.js.map +1 -1
  22. package/import/utils/uploadAssets.js +2 -4
  23. package/import/utils/uploadAssets.js.map +1 -1
  24. package/mockSecurity.js +0 -1
  25. package/mockSecurity.js.map +1 -1
  26. package/package.json +32 -36
  27. package/import/process/blocksHandler.d.ts +0 -3
  28. package/import/process/blocksHandler.js +0 -175
  29. package/import/process/blocksHandler.js.map +0 -1
  30. package/import/process/pagesHandler.d.ts +0 -3
  31. package/import/process/pagesHandler.js +0 -180
  32. package/import/process/pagesHandler.js.map +0 -1
  33. package/import/utils.d.ts +0 -49
  34. package/import/utils.js +0 -641
  35. package/import/utils.js.map +0 -1
package/import/utils.d.ts DELETED
@@ -1,49 +0,0 @@
1
- import { File } from "@webiny/api-file-manager/types";
2
- import { PbImportExportContext } from "../graphql/types";
3
- import { ExportedPageData, ExportedBlockData } from "../export/utils";
4
- interface UploadAssetsParams {
5
- context: PbImportExportContext;
6
- filesData: File[];
7
- fileUploadsData: FileUploadsData;
8
- }
9
- interface UploadAssetsReturnType {
10
- fileIdToKeyMap: Map<string, string>;
11
- }
12
- export declare const uploadAssets: (params: UploadAssetsParams) => Promise<UploadAssetsReturnType>;
13
- interface FileUploadsData {
14
- data: string;
15
- assets: Record<string, string>;
16
- }
17
- interface ImportPageParams {
18
- key: string;
19
- pageKey: string;
20
- context: PbImportExportContext;
21
- fileUploadsData: FileUploadsData;
22
- }
23
- export declare function importPage({ pageKey, context, fileUploadsData }: ImportPageParams): Promise<ExportedPageData["page"]>;
24
- interface ImportBlockParams {
25
- key: string;
26
- blockKey: string;
27
- context: PbImportExportContext;
28
- fileUploadsData: FileUploadsData;
29
- }
30
- export declare function importBlock({ blockKey, context, fileUploadsData }: ImportBlockParams): Promise<ExportedBlockData["block"]>;
31
- interface ImportData {
32
- assets: Record<string, string>;
33
- data: string;
34
- key: string;
35
- }
36
- /**
37
- * Function will read the given zip file from S3 via stream, extract its content and upload it to S3 bucket.
38
- * @param zipFileUrl
39
- * @return ImportData S3 file keys for all uploaded assets group by page/block.
40
- */
41
- export declare function readExtractAndUploadZipFileContents(zipFileUrl: string): Promise<ImportData[]>;
42
- export declare function initialStats(total: number): {
43
- pending: number;
44
- processing: number;
45
- completed: number;
46
- failed: number;
47
- total: number;
48
- };
49
- export {};
package/import/utils.js DELETED
@@ -1,641 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
-
5
- Object.defineProperty(exports, "__esModule", {
6
- value: true
7
- });
8
- exports.importBlock = importBlock;
9
- exports.importPage = importPage;
10
- exports.initialStats = initialStats;
11
- exports.readExtractAndUploadZipFileContents = readExtractAndUploadZipFileContents;
12
- exports.uploadAssets = void 0;
13
-
14
- var _uniqid = _interopRequireDefault(require("uniqid"));
15
-
16
- var _dotPropImmutable = _interopRequireDefault(require("dot-prop-immutable"));
17
-
18
- var _fs = require("fs");
19
-
20
- var _fsExtra = require("fs-extra");
21
-
22
- var _util = require("util");
23
-
24
- var _stream = require("stream");
25
-
26
- var _nodeFetch = _interopRequireDefault(require("node-fetch"));
27
-
28
- var _path = _interopRequireDefault(require("path"));
29
-
30
- var _yauzl = _interopRequireDefault(require("yauzl"));
31
-
32
- var _chunk = _interopRequireDefault(require("lodash/chunk"));
33
-
34
- var _loadJsonFile = _interopRequireDefault(require("load-json-file"));
35
-
36
- var _error = _interopRequireDefault(require("@webiny/error"));
37
-
38
- var _downloadInstallFiles = require("@webiny/api-page-builder/graphql/crud/install/utils/downloadInstallFiles");
39
-
40
- var _types = require("../types");
41
-
42
- var _s3Stream = require("../export/s3Stream");
43
-
44
- const streamPipeline = (0, _util.promisify)(_stream.pipeline);
45
- const INSTALL_DIR = "/tmp";
46
-
47
- const INSTALL_EXTRACT_DIR = _path.default.join(INSTALL_DIR, "apiPageBuilderImport");
48
-
49
- const FILES_COUNT_IN_EACH_BATCH = 15;
50
-
51
- function updateImageInPageSettings(params) {
52
- const {
53
- settings,
54
- fileIdToKeyMap,
55
- srcPrefix
56
- } = params;
57
- let newSettings = settings;
58
- const srcPrefixWithoutTrailingSlash = srcPrefix.endsWith("/") ? srcPrefix.slice(0, -1) : srcPrefix;
59
-
60
- if (_dotPropImmutable.default.get(newSettings, "general.image.src")) {
61
- var _settings$general, _settings$general$ima;
62
-
63
- newSettings = _dotPropImmutable.default.set(newSettings, "general.image.src", `${srcPrefixWithoutTrailingSlash}/${fileIdToKeyMap.get(((_settings$general = settings.general) === null || _settings$general === void 0 ? void 0 : (_settings$general$ima = _settings$general.image) === null || _settings$general$ima === void 0 ? void 0 : _settings$general$ima.id) || "")}`);
64
- }
65
-
66
- if (_dotPropImmutable.default.get(newSettings, "social.image.src")) {
67
- var _settings$social, _settings$social$imag;
68
-
69
- newSettings = _dotPropImmutable.default.set(newSettings, "social.image.src", `${srcPrefixWithoutTrailingSlash}/${fileIdToKeyMap.get(((_settings$social = settings.social) === null || _settings$social === void 0 ? void 0 : (_settings$social$imag = _settings$social.image) === null || _settings$social$imag === void 0 ? void 0 : _settings$social$imag.id) || "")}`);
70
- }
71
-
72
- return newSettings;
73
- }
74
-
75
- function updateBlockPreviewImage(params) {
76
- const {
77
- file,
78
- fileIdToKeyMap,
79
- srcPrefix
80
- } = params;
81
- const newFile = file;
82
- const srcPrefixWithoutTrailingSlash = srcPrefix.endsWith("/") ? srcPrefix.slice(0, -1) : srcPrefix;
83
- newFile.src = `${srcPrefixWithoutTrailingSlash}/${fileIdToKeyMap.get(file.id || "")}`;
84
- return newFile;
85
- }
86
-
87
- function updateFilesInData({
88
- data,
89
- fileIdToKeyMap,
90
- srcPrefix
91
- }) {
92
- // BASE CASE: Termination point
93
- if (!data || typeof data !== "object") {
94
- return;
95
- } // Recursively call function if data is array
96
-
97
-
98
- if (Array.isArray(data)) {
99
- for (let i = 0; i < data.length; i++) {
100
- const element = data[i];
101
- updateFilesInData({
102
- data: element,
103
- fileIdToKeyMap,
104
- srcPrefix
105
- });
106
- }
107
-
108
- return;
109
- } // Main logic
110
-
111
-
112
- const tuple = Object.entries(data);
113
-
114
- for (let i = 0; i < tuple.length; i++) {
115
- const [key, value] = tuple[i];
116
-
117
- if (key === "file" && value && fileIdToKeyMap.has(value.id)) {
118
- value.key = fileIdToKeyMap.get(value.id);
119
- value.name = fileIdToKeyMap.get(value.id);
120
- value.src = `${srcPrefix}${srcPrefix.endsWith("/") ? "" : "/"}${fileIdToKeyMap.get(value.id)}`;
121
- } else {
122
- updateFilesInData({
123
- data: value,
124
- srcPrefix,
125
- fileIdToKeyMap
126
- });
127
- }
128
- }
129
- }
130
-
131
- const uploadAssets = async params => {
132
- const {
133
- context,
134
- filesData,
135
- fileUploadsData
136
- } = params; // Save uploaded file key against static id for later use.
137
-
138
- const fileIdToKeyMap = new Map();
139
- /**
140
- * This function contains logic of file download from S3.
141
- * Current we're not mocking zip file download from S3 in tests at the moment.
142
- * So, we're manually mocking it in case of test just by returning an empty object.
143
- */
144
-
145
- if (process.env.NODE_ENV === "test") {
146
- return {
147
- fileIdToKeyMap
148
- };
149
- } // Save files meta data against old key for later use.
150
-
151
-
152
- const fileKeyToFileMap = new Map(); // Initialize maps.
153
-
154
- for (let i = 0; i < filesData.length; i++) {
155
- const file = filesData[i];
156
- fileKeyToFileMap.set(file.key, file); // Initialize the value
157
-
158
- fileIdToKeyMap.set(file.id, file.type);
159
- }
160
-
161
- const fileUploadResults = await uploadFilesFromS3({
162
- fileKeyToFileMap,
163
- oldKeyToNewKeyMap: fileUploadsData.assets
164
- }); // Create files in File Manager
165
-
166
- const createFilesInput = fileUploadResults.map(uploadResult => {
167
- const newKey = uploadResult.Key;
168
- const file = fileKeyToFileMap.get(getOldFileKey(newKey));
169
-
170
- if (!file) {
171
- return null;
172
- } // Update the file map with newly uploaded file.
173
-
174
-
175
- fileIdToKeyMap.set(file.id, newKey);
176
- return {
177
- key: newKey,
178
- name: file.name,
179
- size: file.size,
180
- type: file.type,
181
- meta: file.meta,
182
- tags: file.tags
183
- };
184
- }).filter(Boolean);
185
- const createFilesPromises = []; // Gives an array of chunks (each consists of FILES_COUNT_IN_EACH_BATCH items).
186
-
187
- const createFilesInputChunks = (0, _chunk.default)(createFilesInput, FILES_COUNT_IN_EACH_BATCH);
188
-
189
- for (let i = 0; i < createFilesInputChunks.length; i++) {
190
- const createFilesInputChunk = createFilesInputChunks[i];
191
- createFilesPromises.push(
192
- /*
193
- * We need to break down files into chunks because
194
- * `createFilesInBatch` operation has a limit on number of files it can handle at once.
195
- */
196
- context.fileManager.files.createFilesInBatch(createFilesInputChunk));
197
- }
198
-
199
- await Promise.all(createFilesPromises);
200
- return {
201
- fileIdToKeyMap
202
- };
203
- };
204
-
205
- exports.uploadAssets = uploadAssets;
206
-
207
- async function importPage({
208
- pageKey,
209
- context,
210
- fileUploadsData
211
- }) {
212
- const log = console.log; // Making Directory for page in which we're going to extract the page data file.
213
-
214
- const PAGE_EXTRACT_DIR = _path.default.join(INSTALL_EXTRACT_DIR, pageKey);
215
-
216
- (0, _fsExtra.ensureDirSync)(PAGE_EXTRACT_DIR);
217
-
218
- const pageDataFileKey = _dotPropImmutable.default.get(fileUploadsData, `data`);
219
-
220
- const PAGE_DATA_FILE_PATH = _path.default.join(PAGE_EXTRACT_DIR, _path.default.basename(pageDataFileKey));
221
-
222
- log(`Downloading Page data file: ${pageDataFileKey} at "${PAGE_DATA_FILE_PATH}"`); // Download and save page data file in disk.
223
-
224
- await new Promise((resolve, reject) => {
225
- _s3Stream.s3Stream.readStream(pageDataFileKey).on("error", reject).pipe((0, _fs.createWriteStream)(PAGE_DATA_FILE_PATH)).on("error", reject).on("finish", resolve);
226
- }); // Load the page data file from disk.
227
-
228
- log(`Load file ${pageDataFileKey}`);
229
- const {
230
- page,
231
- files
232
- } = await (0, _loadJsonFile.default)(PAGE_DATA_FILE_PATH); // Only update page data if there are files.
233
-
234
- if (files && Array.isArray(files) && files.length > 0) {
235
- // Upload page assets.
236
- const {
237
- fileIdToKeyMap
238
- } = await uploadAssets({
239
- context,
240
-
241
- /**
242
- * TODO @ts-refactor @ashutosh figure out correct types.
243
- */
244
- // @ts-ignore
245
- filesData: files,
246
- fileUploadsData
247
- });
248
- const settings = await context.fileManager.settings.getSettings();
249
- const {
250
- srcPrefix = ""
251
- } = settings || {};
252
- updateFilesInData({
253
- data: page.content || {},
254
- fileIdToKeyMap,
255
- srcPrefix
256
- });
257
- page.settings = updateImageInPageSettings({
258
- settings: page.settings || {},
259
- fileIdToKeyMap,
260
- srcPrefix
261
- });
262
- }
263
-
264
- log("Removing Directory for page...");
265
- await (0, _downloadInstallFiles.deleteFile)(pageKey);
266
- log(`Remove page contents from S3...`);
267
- await deleteS3Folder(_path.default.dirname(fileUploadsData.data));
268
- return page;
269
- }
270
-
271
- async function importBlock({
272
- blockKey,
273
- context,
274
- fileUploadsData
275
- }) {
276
- const log = console.log; // Making Directory for block in which we're going to extract the block data file.
277
-
278
- const BLOCK_EXTRACT_DIR = _path.default.join(INSTALL_EXTRACT_DIR, blockKey);
279
-
280
- (0, _fsExtra.ensureDirSync)(BLOCK_EXTRACT_DIR);
281
-
282
- const blockDataFileKey = _dotPropImmutable.default.get(fileUploadsData, `data`);
283
-
284
- const BLOCK_DATA_FILE_PATH = _path.default.join(BLOCK_EXTRACT_DIR, _path.default.basename(blockDataFileKey));
285
-
286
- log(`Downloading Block data file: ${blockDataFileKey} at "${BLOCK_DATA_FILE_PATH}"`); // Download and save block data file in disk.
287
-
288
- await new Promise((resolve, reject) => {
289
- _s3Stream.s3Stream.readStream(blockDataFileKey).on("error", reject).pipe((0, _fs.createWriteStream)(BLOCK_DATA_FILE_PATH)).on("error", reject).on("finish", resolve);
290
- }); // Load the block data file from disk.
291
-
292
- log(`Load file ${blockDataFileKey}`);
293
- const {
294
- block,
295
- files
296
- } = await (0, _loadJsonFile.default)(BLOCK_DATA_FILE_PATH); // Only update block data if there are files.
297
-
298
- if (files && Array.isArray(files) && files.length > 0) {
299
- // Upload block assets.
300
- const {
301
- fileIdToKeyMap
302
- } = await uploadAssets({
303
- context,
304
- filesData: files,
305
- fileUploadsData
306
- });
307
- const settings = await context.fileManager.settings.getSettings();
308
- const {
309
- srcPrefix = ""
310
- } = settings || {};
311
- updateFilesInData({
312
- data: block.content || {},
313
- fileIdToKeyMap,
314
- srcPrefix
315
- });
316
- block.preview = updateBlockPreviewImage({
317
- file: block.preview || {},
318
- fileIdToKeyMap,
319
- srcPrefix
320
- });
321
- }
322
-
323
- log("Removing Directory for block...");
324
- await (0, _downloadInstallFiles.deleteFile)(blockKey);
325
- log(`Remove block contents from S3...`);
326
- await deleteS3Folder(_path.default.dirname(fileUploadsData.data));
327
- return block;
328
- }
329
-
330
- async function uploadFilesFromS3({
331
- fileKeyToFileMap,
332
- oldKeyToNewKeyMap
333
- }) {
334
- const oldKeysForAssets = Object.keys(oldKeyToNewKeyMap);
335
- const promises = []; // Upload all assets.
336
-
337
- for (let i = 0; i < oldKeysForAssets.length; i++) {
338
- const oldKey = oldKeysForAssets[i];
339
- const tempNewKey = oldKeyToNewKeyMap[oldKey]; // Read file.
340
-
341
- const readStream = _s3Stream.s3Stream.readStream(tempNewKey); // Get file meta data.
342
-
343
-
344
- const fileMetaData = fileKeyToFileMap.get(oldKey);
345
-
346
- if (fileMetaData) {
347
- const newKey = (0, _uniqid.default)("", `-${fileMetaData.key}`);
348
-
349
- const {
350
- streamPassThrough,
351
- streamPassThroughUploadPromise: promise
352
- } = _s3Stream.s3Stream.writeStream(newKey, fileMetaData.type);
353
-
354
- readStream.pipe(streamPassThrough);
355
- promises.push(promise);
356
- console.log(`Successfully queued file "${newKey}"`);
357
- }
358
- }
359
-
360
- return Promise.all(promises);
361
- }
362
-
363
- function getOldFileKey(key) {
364
- /*
365
- * Because we know the naming convention, we can extract the old key from new key.
366
- */
367
- try {
368
- const [, ...rest] = key.split("-");
369
- return rest.join("-");
370
- } catch (e) {
371
- return key;
372
- }
373
- }
374
-
375
- const FILE_CONTENT_TYPE = "application/octet-stream";
376
-
377
- function getFileNameWithoutExt(fileName) {
378
- return _path.default.basename(fileName).replace(_path.default.extname(fileName), "");
379
- }
380
-
381
- /**
382
- * Function will read the given zip file from S3 via stream, extract its content and upload it to S3 bucket.
383
- * @param zipFileUrl
384
- * @return ImportData S3 file keys for all uploaded assets group by page/block.
385
- */
386
- async function readExtractAndUploadZipFileContents(zipFileUrl) {
387
- const log = console.log;
388
- const importDataList = [];
389
-
390
- const zipFileName = _path.default.basename(zipFileUrl).split("?")[0];
391
-
392
- const response = await (0, _nodeFetch.default)(zipFileUrl);
393
-
394
- if (!response.ok) {
395
- throw new _error.default(`Unable to downloading file: "${zipFileUrl}"`, response.statusText);
396
- }
397
-
398
- const readStream = response.body;
399
- const uniquePath = (0, _uniqid.default)("IMPORTS/"); // Read export file and download it in the disk
400
-
401
- const ZIP_FILE_PATH = _path.default.join(INSTALL_DIR, zipFileName);
402
-
403
- const writeStream = (0, _fs.createWriteStream)(ZIP_FILE_PATH);
404
- await streamPipeline(readStream, writeStream);
405
- log(`Downloaded file "${zipFileName}" at ${ZIP_FILE_PATH}`); // Extract the downloaded zip file
406
-
407
- const zipFilePaths = await extractZipToDisk(ZIP_FILE_PATH);
408
- log(`Removing ZIP file "${zipFileUrl}" from ${ZIP_FILE_PATH}`);
409
- await (0, _downloadInstallFiles.deleteFile)(ZIP_FILE_PATH); // Extract each page/block zip and upload their content's to S3
410
-
411
- for (let i = 0; i < zipFilePaths.length; i++) {
412
- const currentPath = zipFilePaths[i];
413
- const dataMap = await extractZipAndUploadToS3(currentPath, uniquePath);
414
- importDataList.push(dataMap);
415
- }
416
-
417
- log("Removing all ZIP files located at ", _path.default.dirname(zipFilePaths[0]));
418
- await (0, _downloadInstallFiles.deleteFile)(_path.default.dirname(zipFilePaths[0]));
419
- return importDataList;
420
- }
421
-
422
- const ASSETS_DIR_NAME = "/assets";
423
-
424
- function prepareDataDirMap({
425
- map,
426
- filePath,
427
- newKey
428
- }) {
429
- const dirname = _path.default.dirname(filePath);
430
-
431
- const fileName = _path.default.basename(filePath);
432
- /*
433
- * We want to use dot (.) as part of object key rather than creating nested object(s).
434
- * Also, the file name might contain dots in it beside the extension, so, we are escaping them all.
435
- */
436
-
437
-
438
- const oldKey = fileName.replace(/\./g, "\\.");
439
- const isAsset = dirname.endsWith(ASSETS_DIR_NAME);
440
-
441
- if (isAsset) {
442
- map = _dotPropImmutable.default.set(map, `assets.${oldKey}`, newKey);
443
- } else {
444
- // We only need to know the newKey for data file.
445
- map = _dotPropImmutable.default.set(map, `data`, newKey);
446
- }
447
-
448
- return map;
449
- }
450
-
451
- async function deleteS3Folder(key) {
452
- // Append trailing slash i.e "/" to key to make sure we only delete a specific folder.
453
- if (!key.endsWith("/")) {
454
- key = `${key}/`;
455
- }
456
-
457
- const response = await _s3Stream.s3Stream.listObject(key);
458
- const keys = (response.Contents || []).map(c => c.Key).filter(Boolean);
459
- console.log(`Found ${keys.length} files.`);
460
- const deleteFilePromises = keys.map(key => _s3Stream.s3Stream.deleteObject(key));
461
- await Promise.all(deleteFilePromises);
462
- console.log(`Successfully deleted ${deleteFilePromises.length} files.`);
463
- } // export const zeroPad = version => `${version}`.padStart(5, "0");
464
-
465
-
466
- function initialStats(total) {
467
- return {
468
- [_types.ImportExportTaskStatus.PENDING]: total,
469
- [_types.ImportExportTaskStatus.PROCESSING]: 0,
470
- [_types.ImportExportTaskStatus.COMPLETED]: 0,
471
- [_types.ImportExportTaskStatus.FAILED]: 0,
472
- total
473
- };
474
- }
475
-
476
- function extractZipToDisk(exportFileZipPath) {
477
- return new Promise((resolve, reject) => {
478
- const zipFilePaths = [];
479
- const uniqueFolderNameForExport = getFileNameWithoutExt(exportFileZipPath);
480
-
481
- const EXPORT_FILE_EXTRACTION_PATH = _path.default.join(INSTALL_DIR, uniqueFolderNameForExport); // Make sure DIR exists
482
-
483
-
484
- (0, _fsExtra.ensureDirSync)(EXPORT_FILE_EXTRACTION_PATH);
485
-
486
- _yauzl.default.open(exportFileZipPath, {
487
- lazyEntries: true
488
- }, function (err, zipFile) {
489
- if (err) {
490
- console.warn("ERROR: Failed to extract zip: ", exportFileZipPath, err);
491
- reject(err);
492
- return;
493
- }
494
-
495
- if (!zipFile) {
496
- console.log("ERROR: Missing zip file resource for path: " + exportFileZipPath);
497
- reject("Missing Zip File Resource.");
498
- return;
499
- }
500
-
501
- console.info(`The ZIP file contains ${zipFile.entryCount} entries.`);
502
- zipFile.on("end", function (err) {
503
- if (err) {
504
- console.warn("ERROR: Failed on END event for file: ", exportFileZipPath, err);
505
- reject(err);
506
- }
507
-
508
- resolve(zipFilePaths);
509
- });
510
- zipFile.readEntry();
511
- zipFile.on("entry", function (entry) {
512
- console.info(`Processing entry: "${entry.fileName}"`);
513
-
514
- if (/\/$/.test(entry.fileName)) {
515
- // Directory file names end with '/'.
516
- // Note that entries for directories themselves are optional.
517
- // An entry's fileName implicitly requires its parent directories to exist.
518
- zipFile.readEntry();
519
- } else {
520
- // file entry
521
- zipFile.openReadStream(entry, function (err, readStream) {
522
- if (err) {
523
- console.warn("ERROR: Failed to openReadStream for file: ", entry.fileName, err);
524
- reject(err);
525
- return;
526
- }
527
-
528
- if (!readStream) {
529
- console.log("ERROR: Missing Read Stream Resource when extracting to disk.");
530
- reject("Missing Read Stream Resource.");
531
- return;
532
- }
533
-
534
- const filePath = _path.default.join(EXPORT_FILE_EXTRACTION_PATH, entry.fileName);
535
-
536
- readStream.on("end", function () {
537
- zipFilePaths.push(filePath);
538
- zipFile.readEntry();
539
- });
540
- streamPipeline(readStream, (0, _fs.createWriteStream)(filePath)).catch(error => {
541
- reject(error);
542
- });
543
- });
544
- }
545
- });
546
- });
547
- });
548
- }
549
-
550
- function extractZipAndUploadToS3(dataZipFilePath, uniquePath) {
551
- return new Promise((resolve, reject) => {
552
- const filePaths = [];
553
- const fileUploadPromises = [];
554
- const uniqueKey = getFileNameWithoutExt(dataZipFilePath);
555
- let dataMap = {
556
- key: uniqueKey,
557
- assets: {},
558
- data: ""
559
- };
560
-
561
- _yauzl.default.open(dataZipFilePath, {
562
- lazyEntries: true
563
- }, function (err, zipFile) {
564
- if (err) {
565
- console.warn("ERROR: Failed to extract zip: ", dataZipFilePath, err);
566
- reject(err);
567
- return;
568
- }
569
-
570
- if (!zipFile) {
571
- console.log("ERROR: Probably failed to extract zip: " + dataZipFilePath);
572
- reject("Missing Zip File Resource.");
573
- return;
574
- }
575
-
576
- console.info(`The ZIP file contains ${zipFile.entryCount} entries.`);
577
- zipFile.on("end", function (err) {
578
- if (err) {
579
- console.warn('ERROR: Failed on "END" for file: ', dataZipFilePath, err);
580
- reject(err);
581
- }
582
-
583
- Promise.all(fileUploadPromises).then(res => {
584
- res.forEach(r => {
585
- console.info("Done uploading... ", r);
586
- });
587
- resolve(dataMap);
588
- });
589
- });
590
- zipFile.readEntry();
591
- zipFile.on("entry", function (entry) {
592
- console.info(`Processing entry: "${entry.fileName}"`);
593
-
594
- if (/\/$/.test(entry.fileName)) {
595
- // Directory file names end with '/'.
596
- // Note that entries for directories themselves are optional.
597
- // An entry's fileName implicitly requires its parent directories to exist.
598
- zipFile.readEntry();
599
- } else {
600
- // file entry
601
- zipFile.openReadStream(entry, function (err, readStream) {
602
- if (err) {
603
- console.warn("ERROR: Failed while performing [openReadStream] for file: ", entry.fileName, err);
604
- reject(err);
605
- return;
606
- }
607
-
608
- if (!readStream) {
609
- console.log("ERROR: Missing Read Stream while importing.");
610
- reject("Missing Read Strea Resource.");
611
- return;
612
- }
613
-
614
- readStream.on("end", function () {
615
- filePaths.push(entry.fileName);
616
- zipFile.readEntry();
617
- });
618
- const newKey = `${uniquePath}/${uniqueKey}/${entry.fileName}`; // Modify in place
619
-
620
- dataMap = prepareDataDirMap({
621
- map: dataMap,
622
- filePath: entry.fileName,
623
- newKey
624
- });
625
-
626
- const {
627
- streamPassThrough,
628
- streamPassThroughUploadPromise: promise
629
- } = _s3Stream.s3Stream.writeStream(newKey, FILE_CONTENT_TYPE);
630
-
631
- streamPipeline(readStream, streamPassThrough).then(() => {
632
- fileUploadPromises.push(promise);
633
- }).catch(error => {
634
- reject(error);
635
- });
636
- });
637
- }
638
- });
639
- });
640
- });
641
- }