@bprotsyk/aso-core 2.0.33 → 2.0.34

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.
@@ -29,7 +29,9 @@ export declare class ServerUtil {
29
29
  setupCertbot(): Promise<boolean>;
30
30
  setupSSL(email: string, host: string): Promise<void>;
31
31
  refresh(): Promise<boolean>;
32
- uploadDirectoryToSftp(localDir: string, remoteDir: string, sftpConfig: ISFTP): Promise<void>;
32
+ uploadDirectoryToSftp(localDir: string, remoteDir: string, sftpConfig: any): Promise<void>;
33
33
  generateNginxConfig(domain: string, rootPath: string): Promise<string>;
34
+ extractUploadedZip(name: string, file: any): Promise<void>;
35
+ ensureDirectoryExistsViaSSH(sshConfig: ISFTP, remoteDir: string): Promise<void>;
34
36
  }
35
37
  export {};
@@ -4,11 +4,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ServerUtil = exports.PORT = exports.HOST = exports.PASSWORD = exports.IP = void 0;
7
+ const node_ssh_1 = require("node-ssh");
7
8
  const child_process_1 = __importDefault(require("child_process"));
8
9
  const ssh2_sftp_client_1 = __importDefault(require("ssh2-sftp-client"));
9
10
  const fs_1 = __importDefault(require("fs"));
10
11
  const mustache_1 = __importDefault(require("mustache"));
11
12
  const path_1 = __importDefault(require("path"));
13
+ const unzipper_1 = __importDefault(require("unzipper"));
12
14
  const { promisify } = require("util");
13
15
  const execPromise = promisify(child_process_1.default.exec);
14
16
  exports.IP = "185.123.53.227";
@@ -169,43 +171,31 @@ class ServerUtil {
169
171
  const sftp = new ssh2_sftp_client_1.default();
170
172
  try {
171
173
  await sftp.connect(sftpConfig);
172
- await sftp.stat(remoteDir).catch(async (err) => {
173
- if (err.code === 2) {
174
- // Код 2 означає, що директорія не існує
175
- await sftp.mkdir(remoteDir, true);
176
- console.log(`Папка створена: ${remoteDir}`);
177
- }
178
- else {
179
- console.error(`Помилка під час перевірки або створення папки: ${remoteDir}`, err);
180
- throw err;
181
- }
182
- });
183
174
  const items = fs_1.default.readdirSync(localDir, { withFileTypes: true });
184
175
  for (const item of items) {
185
176
  const localPath = path_1.default.join(localDir, item.name);
186
177
  const remotePath = `${remoteDir}/${item.name}`;
187
178
  if (item.isDirectory()) {
188
- await sftp.stat(remotePath).catch(async (err) => {
189
- if (err.code === 2) {
190
- await sftp.mkdir(remotePath, true);
191
- console.log(`Папка створена: ${remotePath}`);
192
- }
193
- else {
194
- console.error(`Помилка під час перевірки або створення папки: ${remotePath}`, err);
179
+ // Створення підкаталогу на віддаленому сервері
180
+ await sftp.mkdir(remotePath, true).catch(async (err) => {
181
+ if (err.code !== 4) { // Ігноруємо помилку "Directory already exists"
182
+ console.error(`Помилка під час створення папки: ${remotePath}`, err);
195
183
  throw err;
196
184
  }
197
185
  });
186
+ // Рекурсивне копіювання вмісту директорії
198
187
  await this.uploadDirectoryToSftp(localPath, remotePath, sftpConfig);
199
188
  }
200
189
  else {
190
+ // Завантаження файлу на віддалений сервер
201
191
  await sftp.put(localPath, remotePath);
202
192
  console.log(`Передано файл: ${localPath} -> ${remotePath}`);
203
193
  }
204
194
  }
205
- console.log("Усі файли та папки успішно передані.");
195
+ console.log('Усі файли та папки успішно передані.');
206
196
  }
207
197
  catch (err) {
208
- console.error("Помилка під час передавання файлів через SFTP:", err);
198
+ console.error('Помилка під час передавання файлів через SFTP:', err);
209
199
  }
210
200
  finally {
211
201
  await sftp.end();
@@ -217,5 +207,59 @@ class ServerUtil {
217
207
  const config = mustache_1.default.render(template, { domain, rootPath });
218
208
  return config;
219
209
  }
210
+ async extractUploadedZip(name, file) {
211
+ const zipFilePath = file.path;
212
+ const outputDir = path_1.default.join(__dirname, '..', 'uploads', name);
213
+ console.log('Looking for ZIP file at:', zipFilePath);
214
+ console.log('Extracting to:', outputDir);
215
+ ensureDirectoryExistence(outputDir);
216
+ if (!fs_1.default.existsSync(zipFilePath)) {
217
+ console.error('Error: File not found:', zipFilePath);
218
+ return;
219
+ }
220
+ try {
221
+ await new Promise((resolve, reject) => {
222
+ fs_1.default.createReadStream(zipFilePath)
223
+ .pipe(unzipper_1.default.Parse())
224
+ .on('entry', (entry) => {
225
+ // Видаляємо перший сегмент шляху, щоб уникнути кореневої директорії
226
+ const entryPath = path_1.default.join(outputDir, ...entry.path.split('/').slice(1));
227
+ if (entry.type === 'Directory') {
228
+ ensureDirectoryExistence(entryPath);
229
+ }
230
+ else {
231
+ ensureDirectoryExistence(path_1.default.dirname(entryPath));
232
+ entry.pipe(fs_1.default.createWriteStream(entryPath));
233
+ }
234
+ })
235
+ .on('close', resolve)
236
+ .on('error', reject);
237
+ });
238
+ console.log('File successfully extracted.');
239
+ }
240
+ catch (err) {
241
+ console.error('Error extracting file:', err);
242
+ }
243
+ }
244
+ async ensureDirectoryExistsViaSSH(sshConfig, remoteDir) {
245
+ const ssh = new node_ssh_1.NodeSSH();
246
+ try {
247
+ await ssh.connect(sshConfig);
248
+ // Перевірка, чи існує директорія, і створення її, якщо вона не існує
249
+ const command = `if [ ! -d "${remoteDir}" ]; then mkdir -p "${remoteDir}"; fi`;
250
+ await ssh.execCommand(command);
251
+ console.log(`Перевірено або створено папку: ${remoteDir}`);
252
+ }
253
+ catch (err) {
254
+ console.error('Помилка під час перевірки або створення папки через SSH:', err);
255
+ throw err;
256
+ }
257
+ finally {
258
+ ssh.dispose();
259
+ }
260
+ }
220
261
  }
221
262
  exports.ServerUtil = ServerUtil;
263
+ function ensureDirectoryExistence(outputDir) {
264
+ throw new Error("Function not implemented.");
265
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bprotsyk/aso-core",
3
- "version": "2.0.33",
3
+ "version": "2.0.34",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "scripts": {
@@ -37,7 +37,8 @@
37
37
  "replace-in-file": "^7.0.1",
38
38
  "sleep-promise": "^9.1.0",
39
39
  "ssh2-sftp-client": "^11.0.0",
40
- "styled-components": "^5.3.9"
40
+ "styled-components": "^5.3.9",
41
+ "unzipper": "^0.12.3"
41
42
  },
42
43
  "devDependencies": {
43
44
  "@types/mustache": "^4.2.5",
@@ -45,6 +46,7 @@
45
46
  "@types/react": "^18.2.14",
46
47
  "@types/react-dom": "^18.3.0",
47
48
  "@types/ssh2-sftp-client": "^9.0.4",
49
+ "@types/unzipper": "^0.10.10",
48
50
  "copyfiles": "^2.4.1",
49
51
  "typedoc": "^0.23.28",
50
52
  "typescript": "^4.9.5"
@@ -4,6 +4,8 @@ import Client from "ssh2-sftp-client";
4
4
  import fs from "fs";
5
5
  import mustache from "mustache";
6
6
  import path from "path";
7
+ import unzipper from 'unzipper';
8
+
7
9
  const { promisify } = require("util");
8
10
  const execPromise = promisify(ChildProcess.exec);
9
11
 
@@ -205,60 +207,42 @@ export class ServerUtil {
205
207
  return true;
206
208
  }
207
209
 
208
- async uploadDirectoryToSftp(
210
+ async uploadDirectoryToSftp(
209
211
  localDir: string,
210
212
  remoteDir: string,
211
- sftpConfig: ISFTP
213
+ sftpConfig: any
212
214
  ) {
213
215
  const sftp = new Client();
214
-
216
+
215
217
  try {
216
218
  await sftp.connect(sftpConfig);
217
-
218
- await sftp.stat(remoteDir).catch(async (err) => {
219
- if (err.code === 2) {
220
- // Код 2 означає, що директорія не існує
221
- await sftp.mkdir(remoteDir, true);
222
- console.log(`Папка створена: ${remoteDir}`);
223
- } else {
224
- console.error(
225
- `Помилка під час перевірки або створення папки: ${remoteDir}`,
226
- err
227
- );
228
- throw err;
229
- }
230
- });
231
-
232
219
  const items = fs.readdirSync(localDir, { withFileTypes: true });
233
-
220
+
234
221
  for (const item of items) {
235
222
  const localPath = path.join(localDir, item.name);
236
223
  const remotePath = `${remoteDir}/${item.name}`;
237
-
224
+
238
225
  if (item.isDirectory()) {
239
- await sftp.stat(remotePath).catch(async (err) => {
240
- if (err.code === 2) {
241
- await sftp.mkdir(remotePath, true);
242
- console.log(`Папка створена: ${remotePath}`);
243
- } else {
244
- console.error(
245
- `Помилка під час перевірки або створення папки: ${remotePath}`,
246
- err
247
- );
226
+ // Створення підкаталогу на віддаленому сервері
227
+ await sftp.mkdir(remotePath, true).catch(async (err) => {
228
+ if (err.code !== 4) { // Ігноруємо помилку "Directory already exists"
229
+ console.error(`Помилка під час створення папки: ${remotePath}`, err);
248
230
  throw err;
249
231
  }
250
232
  });
251
-
233
+
234
+ // Рекурсивне копіювання вмісту директорії
252
235
  await this.uploadDirectoryToSftp(localPath, remotePath, sftpConfig);
253
236
  } else {
237
+ // Завантаження файлу на віддалений сервер
254
238
  await sftp.put(localPath, remotePath);
255
239
  console.log(`Передано файл: ${localPath} -> ${remotePath}`);
256
240
  }
257
241
  }
258
-
259
- console.log("Усі файли та папки успішно передані.");
242
+
243
+ console.log('Усі файли та папки успішно передані.');
260
244
  } catch (err) {
261
- console.error("Помилка під час передавання файлів через SFTP:", err);
245
+ console.error('Помилка під час передавання файлів через SFTP:', err);
262
246
  } finally {
263
247
  await sftp.end();
264
248
  }
@@ -275,4 +259,72 @@ export class ServerUtil {
275
259
  const config = mustache.render(template, { domain, rootPath });
276
260
  return config;
277
261
  }
262
+
263
+
264
+ async extractUploadedZip(name:string, file:any) {
265
+ const zipFilePath = file.path;
266
+ const outputDir = path.join(__dirname, '..', 'uploads', name);
267
+
268
+ console.log('Looking for ZIP file at:', zipFilePath);
269
+ console.log('Extracting to:', outputDir);
270
+
271
+ ensureDirectoryExistence(outputDir);
272
+
273
+ if (!fs.existsSync(zipFilePath)) {
274
+ console.error('Error: File not found:', zipFilePath);
275
+ return;
276
+ }
277
+
278
+ try {
279
+ await new Promise((resolve, reject) => {
280
+ fs.createReadStream(zipFilePath)
281
+ .pipe(unzipper.Parse())
282
+ .on('entry', (entry) => {
283
+ // Видаляємо перший сегмент шляху, щоб уникнути кореневої директорії
284
+ const entryPath = path.join(
285
+ outputDir,
286
+ ...entry.path.split('/').slice(1)
287
+ );
288
+
289
+ if (entry.type === 'Directory') {
290
+ ensureDirectoryExistence(entryPath);
291
+ } else {
292
+ ensureDirectoryExistence(path.dirname(entryPath));
293
+ entry.pipe(fs.createWriteStream(entryPath));
294
+ }
295
+ })
296
+ .on('close', resolve)
297
+ .on('error', reject);
298
+ });
299
+
300
+ console.log('File successfully extracted.');
301
+ } catch (err) {
302
+ console.error('Error extracting file:', err);
303
+ }
304
+ }
305
+
306
+ async ensureDirectoryExistsViaSSH(sshConfig:ISFTP, remoteDir:string) {
307
+ const ssh = new NodeSSH();
308
+
309
+ try {
310
+ await ssh.connect(sshConfig);
311
+
312
+ // Перевірка, чи існує директорія, і створення її, якщо вона не існує
313
+ const command = `if [ ! -d "${remoteDir}" ]; then mkdir -p "${remoteDir}"; fi`;
314
+ await ssh.execCommand(command);
315
+ console.log(`Перевірено або створено папку: ${remoteDir}`);
316
+ } catch (err) {
317
+ console.error(
318
+ 'Помилка під час перевірки або створення папки через SSH:',
319
+ err
320
+ );
321
+ throw err;
322
+ } finally {
323
+ ssh.dispose();
324
+ }
325
+ }
326
+ }
327
+ function ensureDirectoryExistence(outputDir: string) {
328
+ throw new Error("Function not implemented.");
278
329
  }
330
+