File size: 2,440 Bytes
4327358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// eslint-disable-next-line @typescript-eslint/no-var-requires
const fs = require('fs-extra');

import { fileExists } from '@waha/utils/files';

import { SessionConfig } from '../../structures/sessions.dto';
import { ISessionConfigRepository } from './ISessionConfigRepository';
import { LocalStore } from './LocalStore';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const writeFileAtomic = require('write-file-atomic');

export class LocalSessionConfigRepository extends ISessionConfigRepository {
  FILENAME = '.waha.session.config.json';
  private store: LocalStore;

  constructor(store: LocalStore) {
    super();
    this.store = store;
  }

  async exists(sessionName: string): Promise<boolean> {
    const filepath = this.getFilePath(sessionName);
    const exists = await fileExists(filepath);
    if (!exists) {
      // check directory exist for empty config sessions
      const folder = this.store.getSessionDirectory(sessionName);
      return await fileExists(folder);
    }
    return true;
  }

  async getConfig(sessionName: string): Promise<SessionConfig | null> {
    const filepath = this.getFilePath(sessionName);
    // Check file exists
    if (!(await fileExists(filepath))) {
      return null;
    }

    // Try to load config
    let content;
    try {
      content = await fs.readFile(filepath, 'utf-8');
    } catch (error) {
      return null;
    }

    return JSON.parse(content);
  }

  async saveConfig(sessionName: string, config: SessionConfig) {
    // Create a folder if not exist
    const folder = this.store.getSessionDirectory(sessionName);
    await fs.mkdir(folder, { recursive: true });
    // Save config
    const filepath = this.getFilePath(sessionName);
    const content = JSON.stringify(config || {});
    await writeFileAtomic(filepath, content);
  }

  private getFilePath(sessionName): string {
    return this.store.getFilePath(sessionName, this.FILENAME);
  }

  async deleteConfig(sessionName: string): Promise<void> {
    const sessionDirectory = this.store.getSessionDirectory(sessionName);
    await fs.remove(sessionDirectory);
  }

  async getAllConfigs(): Promise<string[]> {
    await this.store.init();
    const content = await fs.readdir(this.store.getEngineDirectory(), {
      withFileTypes: true,
    });
    return content
      .filter((dirent) => dirent.isDirectory())
      .map((dirent) => dirent.name);
  }

  async init() {
    return;
  }
}