aboutsummaryrefslogtreecommitdiff
path: root/src/server/ActionUtilities.ts
blob: 520ebb42ef1504198a2937aeae30848e4d640242 (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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import { exec } from 'child_process';
import { Color, yellow } from 'colors';
import { createWriteStream, exists, mkdir, readFile, unlink, writeFile } from 'fs';
import * as nodemailer from 'nodemailer';
import { MailOptions } from 'nodemailer/lib/json-transport';
import * as path from 'path';
import { rimraf } from 'rimraf';
import { ExecOptions } from 'shelljs';
import * as Mail from 'nodemailer/lib/mailer';

const projectRoot = path.resolve(__dirname, '../../');
export function pathFromRoot(relative?: string) {
    if (!relative) {
        return projectRoot;
    }
    return path.resolve(projectRoot, relative);
}

export async function fileDescriptorFromStream(filePath: string) {
    const logStream = createWriteStream(filePath);
    return new Promise<number>(resolve => {
        logStream.on('open', resolve);
    });
}

export const commandLine = (command: string, fromDirectory?: string) =>
    new Promise<string>((resolve, reject) => {
        const options: ExecOptions = {};
        if (fromDirectory) {
            options.cwd = fromDirectory ? path.resolve(projectRoot, fromDirectory) : projectRoot;
        }
        exec(command, options, (err, stdout) => (err ? reject(err) : resolve(stdout)));
    });

export const readTextFile = (relativePath: string) => {
    const target = path.resolve(__dirname, relativePath);
    return new Promise<string>((resolve, reject) => {
        readFile(target, (err, data) => (err ? reject(err) : resolve(data.toString())));
    });
};

export const writeTextFile = (relativePath: string, contents: any) => {
    const target = path.resolve(__dirname, relativePath);
    return new Promise<void>((resolve, reject) => {
        writeFile(target, contents, err => (err ? reject(err) : resolve()));
    });
};

export type Messager<T> = (outcome: { result: T | undefined; error: Error | null }) => string;

export interface LogData<T> {
    startMessage: string;
    // if you care about the execution informing your log, you can pass in a function that takes in the result and a potential error and decides what to write
    endMessage: string | Messager<T>;
    action: () => T | Promise<T>;
    color?: Color;
}

function logHelper(content: string, color: Color | string) {
    if (typeof color === 'string') {
        console.log(color, content);
    } else {
        console.log(color(content));
    }
}

let current = Math.ceil(Math.random() * 20);
export async function logExecution<T>({ startMessage, endMessage, action, color }: LogData<T>): Promise<T | undefined> {
    let result: T | undefined;
    let error: Error | null = null;
    const resolvedColor = color || `\x1b[${31 + (++current % 6)}m%s\x1b[0m`;
    logHelper(`${startMessage}...`, resolvedColor);
    try {
        result = await action();
    } catch (e: any) {
        error = e;
    } finally {
        logHelper(typeof endMessage === 'string' ? endMessage : endMessage({ result, error }), resolvedColor);
    }
    return result;
}
export function logPort(listener: string, port: number) {
    console.log(`${listener} listening on port ${yellow(String(port))}`);
}

export function msToTime(duration: number) {
    const milliseconds = Math.floor((duration % 1000) / 100);
    const seconds = Math.floor((duration / 1000) % 60);
    const minutes = Math.floor((duration / (1000 * 60)) % 60);
    const hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

    const hoursS = hours < 10 ? '0' + hours : hours;
    const minutesS = minutes < 10 ? '0' + minutes : minutes;
    const secondsS = seconds < 10 ? '0' + seconds : seconds;

    return hoursS + ':' + minutesS + ':' + secondsS + '.' + milliseconds;
}

export const createIfNotExists = async (filePath: string) => {
    if (
        await new Promise<boolean>(resolve => {
            exists(filePath, resolve);
        })
    ) {
        return true;
    }
    return new Promise<boolean>(resolve => {
        mkdir(filePath, error => resolve(error === null));
    });
};

export async function Prune(rootDirectory: string): Promise<boolean> {
    // const error =  await new Promise<Error>(resolve => rimraf(rootDirectory).then(resolve));
    await new Promise<void>(resolve => {
        rimraf(rootDirectory).then(() => resolve());
    });
    // return error === null;
    return true;
}

export const Destroy = (mediaPath: string) =>
    new Promise<boolean>(resolve => {
        unlink(mediaPath, error => resolve(error === null));
    });

export namespace Email {
    const smtpTransport = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
            user: 'browndashptc@gmail.com',
            pass: 'TsarNicholas#2',
        },
    });

    export interface DispatchOptions<T extends string | string[]> {
        to: T;
        subject: string;
        content: string;
        attachments?: Mail.Attachment | Mail.Attachment[];
    }

    export interface DispatchFailure {
        recipient: string;
        error: Error;
    }

    export async function dispatchAll({ to, subject, content, attachments }: DispatchOptions<string[]>) {
        const failures: DispatchFailure[] = [];
        await Promise.all(
            to.map(async recipient => {
                const resolved = attachments ? ('length' in attachments ? attachments : [attachments]) : undefined;
                const error = await Email.dispatch({ to: recipient, subject, content, attachments: resolved });
                if (error !== null) {
                    failures.push({
                        recipient,
                        error,
                    });
                }
            })
        );
        return failures.length ? failures : undefined;
    }

    export async function dispatch({ to, subject, content, attachments }: DispatchOptions<string>): Promise<Error | null> {
        const mailOptions = {
            to,
            from: 'browndashptc@gmail.com',
            subject,
            text: `Hello ${to.split('@')[0]},\n\n${content}`,
            attachments,
        } as MailOptions;
        return new Promise<Error | null>(resolve => {
            smtpTransport.sendMail(mailOptions, resolve);
        });
    }
}