summaryrefslogtreecommitdiff
path: root/classes/CLIDispatcher.ts
blob: 50ba9e116e066f23a9691e7eff0af30aa49597e6 (plain)
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
import {ChildProcess} from "child_process";
import {randomUUID, UUID} from "crypto";
import {ICLIRequest} from "../types/ICLIRequest";
import {SignalCLIError} from "./SignalCLIError";
import {SignalAPIError} from "./SignalAPIError";

/**
 * A dispatcher used to send requests to signal-cli and receive a response
 */
export class CLIDispatcher {
    /**
     * Dispatch a request to signal-cli
     * @param method - The method to associate with the request.
     * Use `signal-cli --help` to get a full list
     * @param params - The parameters to pass with the request.
     * Use `signal-cli <method> --help` to get a full list for the current method
     * @param proc - The signal-cli process to dispatch to
     */
    static dispatch(method: string, params: any, proc: ChildProcess): Promise<any> {
        return new Promise((res, rej) => {
            let id: UUID = randomUUID();
            let payload: ICLIRequest = {
                jsonrpc: "2.0",
                method,
                params,
                id
            }

            let callback: (raw) => void = (raw): void => {
                if (raw.toString().trim() === "") return;
                let data = JSON.parse(raw.toString());

                if (data.error) {
                    rej(new SignalAPIError(data.error.message ?? null, data.error.code ?? null));
                }

                if (data.id === id) {
                    res(data);
                    proc.stdout.removeListener("data", callback);
                }
            }

            proc.stdout.addListener('data', callback);
            proc.stdin.write(JSON.stringify(payload) + "\n");
        });
    }
}